diff --git a/.gitattributes b/.gitattributes index 51a00f8038..78693e2360 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,68 +1,71 @@ .git* export-ignore .hooks* export-ignore .mailmap export-ignore # Set general file size limit on all files * hooks.MaxObjectKiB=1024 *.bat -crlf *.bin -crlf *.blend -crlf *.bmp -crlf *.cpt -crlf *.gif -crlf *.icns -crlf *.ico -crlf *.jpeg -crlf *.jpg -crlf *.mha -crlf *.odg -crlf *.pbxproj -crlf *.pdf -crlf *.plist -crlf *.png -crlf *.ppt -crlf *.pptx -crlf *.raw -crlf *.vtk -crlf *.xcf -crlf *.xpm -crlf -diff *.sh crlf=input *.sh.in crlf=input configure crlf=input cvsrmvend crlf=input imcp crlf=input imglob crlf=input imln crlf=input immv crlf=input imrm crlf=input imtest crlf=input install-sh crlf=input newalpha crlf=input newversion crlf=input remove_ext crlf=input vxl_doxy.pl crlf=input zap.pl crlf=input *.c whitespace=tab-in-indent,no-lf-at-eof copyright=mitk-license hooks.style=KWStyle,uncrustify *.cpp whitespace=tab-in-indent,no-lf-at-eof copyright=mitk-license hooks.style=KWStyle,uncrustify *.h whitespace=tab-in-indent,no-lf-at-eof copyright=mitk-license hooks.style=KWStyle,uncrustify *.cxx whitespace=tab-in-indent,no-lf-at-eof copyright=mitk-license hooks.style=KWStyle,uncrustify *.hxx whitespace=tab-in-indent,no-lf-at-eof copyright=mitk-license hooks.style=KWStyle,uncrustify *.txx whitespace=tab-in-indent,no-lf-at-eof copyright=mitk-license hooks.style=KWStyle,uncrustify *.txt whitespace=tab-in-indent,no-lf-at-eof *.cmake whitespace=tab-in-indent,no-lf-at-eof # The Microservices use an apache copyright -Core/Code/CppMicroServices/**/*.c copyright=apache-license -Core/Code/CppMicroServices/**/*.cpp copyright=apache-license -Core/Code/CppMicroServices/**/*.h copyright=apache-license +Core/CppMicroServices/**/*.c copyright=apache-license +Core/CppMicroServices/**/*.cpp copyright=apache-license +Core/CppMicroServices/**/*.h copyright=apache-license + +# This is a file with special test data +Core/CppMicroServices/test/modules/libRWithResources/resources/foo.txt -whitespace # There is no need to check files in the utilities directory for copyright Utilities/** -copyright Applications/PluginGenerator/PluginTemplate/src/**/*.h -copyright Applications/PluginGenerator/PluginTemplate/src/**/*.cpp -copyright Applications/PluginGenerator/ProjectTemplate/Apps/TemplateApp/TemplateApp.cpp -copyright # ExternalData content links must have LF newlines *.md5 crlf=input 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 671a6a91f6..2a5a4cd041 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,945 +1,944 @@ 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} OR APPLE) 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() 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..5f0333020b 100644 --- a/Core/Code/Common/mitkCoreServices.cpp +++ b/Core/Code/Common/mitkCoreServices.cpp @@ -1,38 +1,81 @@ /*=================================================================== 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" + +#include +#include namespace mitk { -IShaderRepository* CoreServices::GetShaderRepository() -{ - IShaderRepository* shaderRepo = NULL; - ServiceReference serviceRef = GetModuleContext()->GetServiceReference(); - if (serviceRef) + static itk::SimpleFastMutexLock s_ContextToServicesMapMutex; + static std::map > s_ContextToServicesMap; + + template + static S* GetCoreService(us::ModuleContext* context) + { + itk::MutexLockHolder l(s_ContextToServicesMapMutex); + S* coreService = NULL; + us::ServiceReference serviceRef = context->GetServiceReference(); + if (serviceRef) + { + coreService = context->GetService(serviceRef); + } + + assert(coreService && "Asserting non-NULL MITK core service"); + s_ContextToServicesMap[context].insert(std::make_pair(coreService,serviceRef)); + + return coreService; + } + + IShaderRepository* CoreServices::GetShaderRepository(us::ModuleContext* context) + { + return GetCoreService(context); + } + + bool CoreServices::Unget(us::ModuleContext* context, const std::string& /*interfaceId*/, void* service) { - shaderRepo = GetModuleContext()->GetService(serviceRef); + bool success = false; + + itk::MutexLockHolder l(s_ContextToServicesMapMutex); + std::map >::iterator iter = s_ContextToServicesMap.find(context); + if (iter != s_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; } - return shaderRepo; -} -} +} \ No newline at end of file diff --git a/Core/Code/Common/mitkCoreServices.h b/Core/Code/Common/mitkCoreServices.h index b8b20f6385..96c8188da0 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 + +#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. + * + * 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 * - * It is not exported and not meant to be used by other MITK modules. + * @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); + // 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 +#endif // MITKCORESERVICES_H \ No newline at end of file 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/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/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/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/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/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/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-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/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/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/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/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/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/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 340ae0b533..1689ec6c29 100644 --- a/Core/Code/Testing/files.cmake +++ b/Core/Code/Testing/files.cmake @@ -1,152 +1,149 @@ # 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 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]"< INSTALL_DESTINATION +# [PATH_VARS ... ] +# [NO_SET_AND_CHECK_MACRO] +# [NO_CHECK_REQUIRED_COMPONENTS_MACRO]) +# +# CONFIGURE_PACKAGE_CONFIG_FILE() should be used instead of the plain +# configure_file() command when creating the Config.cmake or -config.cmake +# file for installing a project or library. It helps making the resulting package +# relocatable by avoiding hardcoded paths in the installed Config.cmake file. +# +# In a FooConfig.cmake file there may be code like this to make the +# install destinations know to the using project: +# set(FOO_INCLUDE_DIR "@CMAKE_INSTALL_FULL_INCLUDEDIR@" ) +# set(FOO_DATA_DIR "@CMAKE_INSTALL_PREFIX@/@RELATIVE_DATA_INSTALL_DIR@" ) +# set(FOO_ICONS_DIR "@CMAKE_INSTALL_PREFIX@/share/icons" ) +# ...logic to determine installedPrefix from the own location... +# set(FOO_CONFIG_DIR "${installedPrefix}/@CONFIG_INSTALL_DIR@" ) +# All 4 options shown above are not sufficient, since the first 3 hardcode +# the absolute directory locations, and the 4th case works only if the logic +# to determine the installedPrefix is correct, and if CONFIG_INSTALL_DIR contains +# a relative path, which in general cannot be guaranteed. +# This has the effect that the resulting FooConfig.cmake file would work poorly +# under Windows and OSX, where users are used to choose the install location +# of a binary package at install time, independent from how CMAKE_INSTALL_PREFIX +# was set at build/cmake time. +# +# Using CONFIGURE_PACKAGE_CONFIG_FILE() helps. If used correctly, it makes the +# resulting FooConfig.cmake file relocatable. +# Usage: +# 1. write a FooConfig.cmake.in file as you are used to +# 2. insert a line containing only the string "@PACKAGE_INIT@" +# 3. instead of set(FOO_DIR "@SOME_INSTALL_DIR@"), use set(FOO_DIR "@PACKAGE_SOME_INSTALL_DIR@") +# (this must be after the @PACKAGE_INIT@ line) +# 4. instead of using the normal configure_file(), use CONFIGURE_PACKAGE_CONFIG_FILE() +# +# The and arguments are the input and output file, the same way +# as in configure_file(). +# +# The given to INSTALL_DESTINATION must be the destination where the FooConfig.cmake +# file will be installed to. This can either be a relative or absolute path, both work. +# +# The variables to given as PATH_VARS are the variables which contain +# install destinations. For each of them the macro will create a helper variable +# PACKAGE_. These helper variables must be used +# in the FooConfig.cmake.in file for setting the installed location. They are calculated +# by CONFIGURE_PACKAGE_CONFIG_FILE() so that they are always relative to the +# installed location of the package. This works both for relative and also for absolute locations. +# For absolute locations it works only if the absolute location is a subdirectory +# of CMAKE_INSTALL_PREFIX. +# +# By default configure_package_config_file() also generates two helper macros, +# set_and_check() and check_required_components() into the FooConfig.cmake file. +# +# set_and_check() should be used instead of the normal set() +# command for setting directories and file locations. Additionally to setting the +# variable it also checks that the referenced file or directory actually exists +# and fails with a FATAL_ERROR otherwise. This makes sure that the created +# FooConfig.cmake file does not contain wrong references. +# When using the NO_SET_AND_CHECK_MACRO, this macro is not generated into the +# FooConfig.cmake file. +# +# check_required_components() should be called at the end of the +# FooConfig.cmake file if the package supports components. +# This macro checks whether all requested, non-optional components have been found, +# and if this is not the case, sets the Foo_FOUND variable to FALSE, so that the package +# is considered to be not found. +# It does that by testing the Foo__FOUND variables for all requested +# required components. +# When using the NO_CHECK_REQUIRED_COMPONENTS option, this macro is not generated +# into the FooConfig.cmake file. +# +# For an example see below the documentation for WRITE_BASIC_PACKAGE_VERSION_FILE(). +# +# +# WRITE_BASIC_PACKAGE_VERSION_FILE( filename VERSION major.minor.patch COMPATIBILITY (AnyNewerVersion|SameMajorVersion|ExactVersion) ) +# +# Writes a file for use as ConfigVersion.cmake file to . +# See the documentation of find_package() for details on this. +# filename is the output filename, it should be in the build tree. +# major.minor.patch is the version number of the project to be installed +# The COMPATIBILITY mode AnyNewerVersion means that the installed package version +# will be considered compatible if it is newer or exactly the same as the requested version. +# This mode should be used for packages which are fully backward compatible, +# also across major versions. +# If SameMajorVersion is used instead, then the behaviour differs from AnyNewerVersion +# in that the major version number must be the same as requested, e.g. version 2.0 will +# not be considered compatible if 1.0 is requested. +# This mode should be used for packages which guarantee backward compatibility within the +# same major version. +# If ExactVersion is used, then the package is only considered compatible if the requested +# version matches exactly its own version number (not considering the tweak version). +# For example, version 1.2.3 of a package is only considered compatible to requested version 1.2.3. +# This mode is for packages without compatibility guarantees. +# If your project has more elaborated version matching rules, you will need to write your +# own custom ConfigVersion.cmake file instead of using this macro. +# +# Internally, this macro executes configure_file() to create the resulting +# version file. Depending on the COMPATIBLITY, either the file +# BasicConfigVersion-SameMajorVersion.cmake.in or BasicConfigVersion-AnyNewerVersion.cmake.in +# is used. Please note that these two files are internal to CMake and you should +# not call configure_file() on them yourself, but they can be used as starting +# point to create more sophisticted custom ConfigVersion.cmake files. +# +# +# Example using both configure_package_config_file() and write_basic_package_version_file(): +# CMakeLists.txt: +# set(INCLUDE_INSTALL_DIR include/ ... CACHE ) +# set(LIB_INSTALL_DIR lib/ ... CACHE ) +# set(SYSCONFIG_INSTALL_DIR etc/foo/ ... CACHE ) +# ... +# include(CMakePackageConfigHelpers) +# configure_package_config_file(FooConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake +# INSTALL_DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake +# PATH_VARS INCLUDE_INSTALL_DIR SYSCONFIG_INSTALL_DIR) +# write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake +# VERSION 1.2.3 +# COMPATIBILITY SameMajorVersion ) +# install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake +# DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake ) +# +# With a FooConfig.cmake.in: +# set(FOO_VERSION x.y.z) +# ... +# @PACKAGE_INIT@ +# ... +# set_and_check(FOO_INCLUDE_DIR "@PACKAGE_INCLUDE_INSTALL_DIR@") +# set_and_check(FOO_SYSCONFIG_DIR "@PACKAGE_SYSCONFIG_INSTALL_DIR@") +# +# check_required_components(Foo) + +#============================================================================= +# Copyright 2012 Alexander Neundorf +# +# CMake - Cross Platform Makefile Generator +# Copyright 2000-2011 Kitware, Inc., Insight Software Consortium +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the names of Kitware, Inc., the Insight Software Consortium, +# nor the names of their contributors may be used to endorse or promote +# products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# ------------------------------------------------------------------------------ +# +# The above copyright and license notice applies to distributions of +# CMake in source and binary form. Some source files contain additional +# notices of original copyright by their contributors; see each source +# for details. Third-party software packages supplied with CMake under +# compatible licenses provide their own copyright notices documented in +# corresponding subdirectories. +# +#------------------------------------------------------------------------------ +# +# CMake was initially developed by Kitware with the following sponsorship: +# +# * National Library of Medicine at the National Institutes of Health +# as part of the Insight Segmentation and Registration Toolkit (ITK). +# +# * US National Labs (Los Alamos, Livermore, Sandia) ASC Parallel +# Visualization Initiative. +# +# * National Alliance for Medical Image Computing (NAMIC) is funded by the +# National Institutes of Health through the NIH Roadmap for Medical Research, +# Grant U54 EB005149. +# +# * Kitware, Inc. +#============================================================================= + +include(CMakeParseArguments) + +function(CONFIGURE_PACKAGE_CONFIG_FILE _inputFile _outputFile) + set(options NO_SET_AND_CHECK_MACRO NO_CHECK_REQUIRED_COMPONENTS_MACRO) + set(oneValueArgs INSTALL_DESTINATION ) + set(multiValueArgs PATH_VARS ) + + cmake_parse_arguments(CCF "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + + if(CCF_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to CONFIGURE_PACKAGE_CONFIG_FILE(): \"${CCF_UNPARSED_ARGUMENTS}\"") + endif() + + if(NOT CCF_INSTALL_DESTINATION) + message(FATAL_ERROR "No INSTALL_DESTINATION given to CONFIGURE_PACKAGE_CONFIG_FILE()") + endif() + + if(IS_ABSOLUTE "${CCF_INSTALL_DESTINATION}") + set(absInstallDir "${CCF_INSTALL_DESTINATION}") + else() + set(absInstallDir "${CMAKE_INSTALL_PREFIX}/${CCF_INSTALL_DESTINATION}") + endif() + + file(RELATIVE_PATH PACKAGE_RELATIVE_PATH "${absInstallDir}" "${CMAKE_INSTALL_PREFIX}" ) + + foreach(var ${CCF_PATH_VARS}) + if(NOT DEFINED ${var}) + message(FATAL_ERROR "Variable ${var} does not exist") + else() + if(IS_ABSOLUTE "${${var}}") + string(REPLACE "${CMAKE_INSTALL_PREFIX}" "\${PACKAGE_PREFIX_DIR}" + PACKAGE_${var} "${${var}}") + else() + set(PACKAGE_${var} "\${PACKAGE_PREFIX_DIR}/${${var}}") + endif() + endif() + endforeach() + + get_filename_component(inputFileName "${_inputFile}" NAME) + + set(PACKAGE_INIT " +####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() ####### +####### Any changes to this file will be overwritten by the next CMake run #### +####### The input file was ${inputFileName} ######## + +get_filename_component(PACKAGE_PREFIX_DIR \"\${CMAKE_CURRENT_LIST_DIR}/${PACKAGE_RELATIVE_PATH}\" ABSOLUTE) +") + + if("${absInstallDir}" MATCHES "^(/usr)?/lib(64)?/.+") + # Handle "/usr move" symlinks created by some Linux distros. + set(PACKAGE_INIT "${PACKAGE_INIT} +# Use original install prefix when loaded through a \"/usr move\" +# cross-prefix symbolic link such as /lib -> /usr/lib. +get_filename_component(_realCurr \"\${CMAKE_CURRENT_LIST_DIR}\" REALPATH) +get_filename_component(_realOrig \"${absInstallDir}\" REALPATH) +if(_realCurr STREQUAL _realOrig) + set(PACKAGE_PREFIX_DIR \"${CMAKE_INSTALL_PREFIX}\") +endif() +unset(_realOrig) +unset(_realCurr) +") + endif() + + if(NOT CCF_NO_SET_AND_CHECK_MACRO) + set(PACKAGE_INIT "${PACKAGE_INIT} +macro(set_and_check _var _file) + set(\${_var} \"\${_file}\") + if(NOT EXISTS \"\${_file}\") + message(FATAL_ERROR \"File or directory \${_file} referenced by variable \${_var} does not exist !\") + endif() +endmacro() +") + endif() + + + if(NOT CCF_NO_CHECK_REQUIRED_COMPONENTS_MACRO) + set(PACKAGE_INIT "${PACKAGE_INIT} +macro(check_required_components _NAME) + foreach(comp \${\${_NAME}_FIND_COMPONENTS}) + if(NOT \${_NAME}_\${comp}_FOUND) + if(\${_NAME}_FIND_REQUIRED_\${comp}) + set(\${_NAME}_FOUND FALSE) + endif() + endif() + endforeach() +endmacro() +") + endif() + + set(PACKAGE_INIT "${PACKAGE_INIT} +####################################################################################") + + configure_file("${_inputFile}" "${_outputFile}" @ONLY) + +endfunction() diff --git a/Core/CppMicroServices/CMake/CMakeParseArguments.cmake b/Core/CppMicroServices/CMake/CMakeParseArguments.cmake new file mode 100644 index 0000000000..5e58023943 --- /dev/null +++ b/Core/CppMicroServices/CMake/CMakeParseArguments.cmake @@ -0,0 +1,186 @@ +# CMAKE_PARSE_ARGUMENTS( args...) +# +# CMAKE_PARSE_ARGUMENTS() is intended to be used in macros or functions for +# parsing the arguments given to that macro or function. +# It processes the arguments and defines a set of variables which hold the +# values of the respective options. +# +# The argument contains all options for the respective macro, +# i.e. keywords which can be used when calling the macro without any value +# following, like e.g. the OPTIONAL keyword of the install() command. +# +# The argument contains all keywords for this macro +# which are followed by one value, like e.g. DESTINATION keyword of the +# install() command. +# +# The argument contains all keywords for this macro +# which can be followed by more than one value, like e.g. the TARGETS or +# FILES keywords of the install() command. +# +# When done, CMAKE_PARSE_ARGUMENTS() will have defined for each of the +# keywords listed in , and +# a variable composed of the given +# followed by "_" and the name of the respective keyword. +# These variables will then hold the respective value from the argument list. +# For the keywords this will be TRUE or FALSE. +# +# All remaining arguments are collected in a variable +# _UNPARSED_ARGUMENTS, this can be checked afterwards to see whether +# your macro was called with unrecognized parameters. +# +# As an example here a my_install() macro, which takes similar arguments as the +# real install() command: +# +# function(MY_INSTALL) +# set(options OPTIONAL FAST) +# set(oneValueArgs DESTINATION RENAME) +# set(multiValueArgs TARGETS CONFIGURATIONS) +# cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) +# ... +# +# Assume my_install() has been called like this: +# my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub) +# +# After the cmake_parse_arguments() call the macro will have set the following +# variables: +# MY_INSTALL_OPTIONAL = TRUE +# MY_INSTALL_FAST = FALSE (this option was not used when calling my_install() +# MY_INSTALL_DESTINATION = "bin" +# MY_INSTALL_RENAME = "" (was not used) +# MY_INSTALL_TARGETS = "foo;bar" +# MY_INSTALL_CONFIGURATIONS = "" (was not used) +# MY_INSTALL_UNPARSED_ARGUMENTS = "blub" (no value expected after "OPTIONAL" +# +# You can then continue and process these variables. +# +# Keywords terminate lists of values, e.g. if directly after a one_value_keyword +# another recognized keyword follows, this is interpreted as the beginning of +# the new option. +# E.g. my_install(TARGETS foo DESTINATION OPTIONAL) would result in +# MY_INSTALL_DESTINATION set to "OPTIONAL", but MY_INSTALL_DESTINATION would +# be empty and MY_INSTALL_OPTIONAL would be set to TRUE therefor. + +#============================================================================= +# Copyright 2010 Alexander Neundorf +# +# CMake - Cross Platform Makefile Generator +# Copyright 2000-2011 Kitware, Inc., Insight Software Consortium +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the names of Kitware, Inc., the Insight Software Consortium, +# nor the names of their contributors may be used to endorse or promote +# products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# ------------------------------------------------------------------------------ +# +# The above copyright and license notice applies to distributions of +# CMake in source and binary form. Some source files contain additional +# notices of original copyright by their contributors; see each source +# for details. Third-party software packages supplied with CMake under +# compatible licenses provide their own copyright notices documented in +# corresponding subdirectories. +# +#------------------------------------------------------------------------------ +# +# CMake was initially developed by Kitware with the following sponsorship: +# +# * National Library of Medicine at the National Institutes of Health +# as part of the Insight Segmentation and Registration Toolkit (ITK). +# +# * US National Labs (Los Alamos, Livermore, Sandia) ASC Parallel +# Visualization Initiative. +# +# * National Alliance for Medical Image Computing (NAMIC) is funded by the +# National Institutes of Health through the NIH Roadmap for Medical Research, +# Grant U54 EB005149. +# +# * Kitware, Inc. +#============================================================================= + + +if(__CMAKE_PARSE_ARGUMENTS_INCLUDED) + return() +endif() +set(__CMAKE_PARSE_ARGUMENTS_INCLUDED TRUE) + + +function(CMAKE_PARSE_ARGUMENTS prefix _optionNames _singleArgNames _multiArgNames) + # first set all result variables to empty/FALSE + foreach(arg_name ${_singleArgNames} ${_multiArgNames}) + set(${prefix}_${arg_name}) + endforeach() + + foreach(option ${_optionNames}) + set(${prefix}_${option} FALSE) + endforeach() + + set(${prefix}_UNPARSED_ARGUMENTS) + + set(insideValues FALSE) + set(currentArgName) + + # now iterate over all arguments and fill the result variables + foreach(currentArg ${ARGN}) + list(FIND _optionNames "${currentArg}" optionIndex) # ... then this marks the end of the arguments belonging to this keyword + list(FIND _singleArgNames "${currentArg}" singleArgIndex) # ... then this marks the end of the arguments belonging to this keyword + list(FIND _multiArgNames "${currentArg}" multiArgIndex) # ... then this marks the end of the arguments belonging to this keyword + + if(${optionIndex} EQUAL -1 AND ${singleArgIndex} EQUAL -1 AND ${multiArgIndex} EQUAL -1) + if(insideValues) + if("${insideValues}" STREQUAL "SINGLE") + set(${prefix}_${currentArgName} ${currentArg}) + set(insideValues FALSE) + elseif("${insideValues}" STREQUAL "MULTI") + list(APPEND ${prefix}_${currentArgName} ${currentArg}) + endif() + else() + list(APPEND ${prefix}_UNPARSED_ARGUMENTS ${currentArg}) + endif() + else() + if(NOT ${optionIndex} EQUAL -1) + set(${prefix}_${currentArg} TRUE) + set(insideValues FALSE) + elseif(NOT ${singleArgIndex} EQUAL -1) + set(currentArgName ${currentArg}) + set(${prefix}_${currentArgName}) + set(insideValues "SINGLE") + elseif(NOT ${multiArgIndex} EQUAL -1) + set(currentArgName ${currentArg}) + set(${prefix}_${currentArgName}) + set(insideValues "MULTI") + endif() + endif() + + endforeach() + + # propagate the result variables to the caller: + foreach(arg_name ${_singleArgNames} ${_multiArgNames} ${_optionNames}) + set(${prefix}_${arg_name} ${${prefix}_${arg_name}} PARENT_SCOPE) + endforeach() + set(${prefix}_UNPARSED_ARGUMENTS ${${prefix}_UNPARSED_ARGUMENTS} PARENT_SCOPE) + +endfunction() diff --git a/Core/Code/CppMicroServices/CMake/usCTestScript.cmake b/Core/CppMicroServices/CMake/usCTestScript.cmake similarity index 97% rename from Core/Code/CppMicroServices/CMake/usCTestScript.cmake rename to Core/CppMicroServices/CMake/usCTestScript.cmake index 7feac62e8e..0a7f96535b 100644 --- a/Core/Code/CppMicroServices/CMake/usCTestScript.cmake +++ b/Core/CppMicroServices/CMake/usCTestScript.cmake @@ -1,131 +1,134 @@ 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} ") + if(_shared) + set(_initial_cache "${_initial_cache} US_BUILD_EXAMPLES:BOOL=ON + ") + endif() 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/CppMicroServices/CMake/usCTestScript_custom.cmake similarity index 99% rename from Core/Code/CppMicroServices/CMake/usCTestScript_custom.cmake rename to Core/CppMicroServices/CMake/usCTestScript_custom.cmake index 1a1faac564..cbdcba4727 100644 --- a/Core/Code/CppMicroServices/CMake/usCTestScript_custom.cmake +++ b/Core/CppMicroServices/CMake/usCTestScript_custom.cmake @@ -1,25 +1,24 @@ 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/CppMicroServices/CMake/usCTestScript_travis.cmake similarity index 99% rename from Core/Code/CppMicroServices/CMake/usCTestScript_travis.cmake rename to Core/CppMicroServices/CMake/usCTestScript_travis.cmake index 1cd1030b3c..aea8b9e2ac 100644 --- a/Core/Code/CppMicroServices/CMake/usCTestScript_travis.cmake +++ b/Core/CppMicroServices/CMake/usCTestScript_travis.cmake @@ -1,18 +1,17 @@ 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/test/modules/libAL/usTestModuleAL.cpp b/Core/CppMicroServices/CMake/usExecutableInit.cpp similarity index 90% copy from Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp copy to Core/CppMicroServices/CMake/usExecutableInit.cpp index 9b0abf1b25..6e43c3d884 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp +++ b/Core/CppMicroServices/CMake/usExecutableInit.cpp @@ -1,31 +1,24 @@ /*============================================================================= 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 +#include +US_INITIALIZE_EXECUTABLE("@US_EXECUTABLE_IDENTIFIER@") diff --git a/Core/Code/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake b/Core/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake similarity index 99% rename from Core/Code/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake rename to Core/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake index 8e7e806576..4907ce5786 100644 --- a/Core/Code/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake +++ b/Core/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake @@ -1,53 +1,52 @@ # # 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/CppMicroServices/CMake/usFunctionCompileSnippets.cmake similarity index 94% rename from Core/Code/CppMicroServices/CMake/usFunctionCompileSnippets.cmake rename to Core/CppMicroServices/CMake/usFunctionCompileSnippets.cmake index 962e2e9c37..47f67f503f 100644 --- a/Core/Code/CppMicroServices/CMake/usFunctionCompileSnippets.cmake +++ b/Core/CppMicroServices/CMake/usFunctionCompileSnippets.cmake @@ -1,49 +1,48 @@ 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() + target_link_libraries(${snippet_target_name} ${US_LIBRARY_TARGET} ${snippet_link_libraries}) 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/CppMicroServices/CMake/usFunctionCreateTestModule.cmake similarity index 71% rename from Core/Code/CppMicroServices/CMake/usFunctionCreateTestModule.cmake rename to Core/CppMicroServices/CMake/usFunctionCreateTestModule.cmake index 6d90dc0ae4..2ff602e560 100644 --- a/Core/Code/CppMicroServices/CMake/usFunctionCreateTestModule.cmake +++ b/Core/CppMicroServices/CMake/usFunctionCreateTestModule.cmake @@ -1,51 +1,42 @@ 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() + target_link_libraries(${name} ${US_LIBRARY_TARGET} ${US_LINK_LIBRARIES}) 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}) + cmake_parse_arguments(US_TEST "" "RESOURCES_ROOT" "SOURCES;RESOURCES" "" ${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/CppMicroServices/CMake/usFunctionEmbedResources.cmake similarity index 98% rename from Core/Code/CppMicroServices/CMake/usFunctionEmbedResources.cmake rename to Core/CppMicroServices/CMake/usFunctionEmbedResources.cmake index c559177c5e..7452c168d1 100644 --- a/Core/Code/CppMicroServices/CMake/usFunctionEmbedResources.cmake +++ b/Core/CppMicroServices/CMake/usFunctionEmbedResources.cmake @@ -1,147 +1,148 @@ -#! Embed resources into a shared library or executable. +#! \ingroup MicroServicesCMake +#! \brief 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 +#! \code{.cmake} #! set(module_srcs ) #! usFunctionEmbedResources(module_srcs #! LIBRARY_NAME "mylib" #! ROOT_DIR resources #! FILES config.properties logo.png #! ) -#! \endverbatim +#! \endcode #! #! \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/CppMicroServices/CMake/usFunctionGenerateExecutableInit.cmake b/Core/CppMicroServices/CMake/usFunctionGenerateExecutableInit.cmake new file mode 100644 index 0000000000..fc4030cf80 --- /dev/null +++ b/Core/CppMicroServices/CMake/usFunctionGenerateExecutableInit.cmake @@ -0,0 +1,43 @@ +#! \ingroup MicroServicesCMake +#! \brief Generate a source file which handles proper initialization of an executable. +#! +#! This CMake function will store the path to a generated source file in the +#! src_var variable, which should be compiled into an executable. Example usage: +#! +#! \code{.cmake} +#! set(executable_srcs ) +#! usFunctionGenerateExecutableInit(executable_srcs +#! IDENTIFIER "MyExecutable" +#! ) +#! add_executable(MyExecutable ${executable_srcs}) +#! \endcode +#! +#! \param src_var (required) The name of a list variable to which the path of the generated +#! source file will be appended. +#! \param IDENTIFIER (required) A valid C identifier for the executable. +#! +#! \see #usFunctionGenerateModuleInit +#! \see \ref MicroServices_AutoLoading +#! +function(usFunctionGenerateExecutableInit src_var) + + cmake_parse_arguments(US_EXECUTABLE "" "IDENTIFIER" "" ${ARGN}) + + # sanity checks + if(NOT US_EXECUTABLE_IDENTIFIER) + message(SEND_ERROR "IDENTIFIER argument is mandatory") + endif() + + set(_regex_validation "[a-zA-Z_-][a-zA-Z_0-9-]*") + string(REGEX MATCH ${_regex_validation} _valid_chars ${US_EXECUTABLE_IDENTIFIER}) + if(NOT _valid_chars STREQUAL US_EXECUTABLE_IDENTIFIER) + message(FATAL_ERROR "IDENTIFIER contains illegal characters.") + endif() + + set(exec_init_src_file "${CMAKE_CURRENT_BINARY_DIR}/${US_EXECUTABLE_IDENTIFIER}_init.cpp") + configure_file(${CppMicroServices_EXECUTABLE_INIT_TEMPLATE} ${exec_init_src_file} @ONLY) + + set(_src ${${src_var}} ${exec_init_src_file}) + set(${src_var} ${_src} PARENT_SCOPE) + +endfunction() diff --git a/Core/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake b/Core/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake new file mode 100644 index 0000000000..e02cb839cb --- /dev/null +++ b/Core/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake @@ -0,0 +1,54 @@ +#! \ingroup MicroServicesCMake +#! \brief 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: +#! +#! \code{.cmake} +#! set(module_srcs ) +#! usFunctionGenerateModuleInit(module_srcs +#! NAME "My Module" +#! LIBRARY_NAME "mylib" +#! ) +#! add_library(mylib ${module_srcs}) +#! \endcode +#! +#! \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. +#! +#! \see #usFunctionGenerateExecutableInit +#! \see \ref MicroServices_AutoLoading +#! +function(usFunctionGenerateModuleInit src_var) + + cmake_parse_arguments(US_MODULE "EXECUTABLE" "NAME;LIBRARY_NAME" "" ${ARGN}) + + if(US_MODULE_EXECUTABLE) + message(SEND_ERROR "EXECUTABLE option no longer supported. Use usFunctionGenerateExecutableInit instead.") + endif() + + # sanity checks + if(NOT US_MODULE_NAME) + message(SEND_ERROR "NAME argument is mandatory") + endif() + + if(NOT US_MODULE_LIBRARY_NAME) + set(US_MODULE_LIBRARY_NAME ${US_MODULE_NAME}) + endif() + + set(_regex_validation "[a-zA-Z_-][a-zA-Z_0-9-]*") + 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() + + set(module_init_src_file "${CMAKE_CURRENT_BINARY_DIR}/${US_MODULE_LIBRARY_NAME}_init.cpp") + configure_file(${CppMicroServices_MODULE_INIT_TEMPLATE} ${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/CppMicroServices/CMake/usFunctionGetGccVersion.cmake similarity index 99% rename from Core/Code/CppMicroServices/CMake/usFunctionGetGccVersion.cmake rename to Core/CppMicroServices/CMake/usFunctionGetGccVersion.cmake index 053ef33b6b..022fa606cf 100644 --- a/Core/Code/CppMicroServices/CMake/usFunctionGetGccVersion.cmake +++ b/Core/CppMicroServices/CMake/usFunctionGetGccVersion.cmake @@ -1,19 +1,18 @@ #! \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/test/modules/libAL2/usTestModuleAL2.cpp b/Core/CppMicroServices/CMake/usModuleInit.cpp similarity index 88% copy from Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp copy to Core/CppMicroServices/CMake/usModuleInit.cpp index 6f81242b11..05678e8649 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp +++ b/Core/CppMicroServices/CMake/usModuleInit.cpp @@ -1,31 +1,24 @@ /*============================================================================= 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 +#include +US_INITIALIZE_MODULE("@US_MODULE_NAME@", "@US_MODULE_LIBRARY_NAME@") diff --git a/Core/Code/CppMicroServices/CMake/usPublicHeaderWrapper.h.in b/Core/CppMicroServices/CMake/usPublicHeaderWrapper.h.in similarity index 100% rename from Core/Code/CppMicroServices/CMake/usPublicHeaderWrapper.h.in rename to Core/CppMicroServices/CMake/usPublicHeaderWrapper.h.in diff --git a/Core/Code/CppMicroServices/CMakeLists.txt b/Core/CppMicroServices/CMakeLists.txt similarity index 60% rename from Core/Code/CppMicroServices/CMakeLists.txt rename to Core/CppMicroServices/CMakeLists.txt index bed7726a9c..f15f788bbe 100644 --- a/Core/Code/CppMicroServices/CMakeLists.txt +++ b/Core/CppMicroServices/CMakeLists.txt @@ -1,357 +1,375 @@ project(CppMicroServices) -set(${PROJECT_NAME}_MAJOR_VERSION 0) +set(${PROJECT_NAME}_MAJOR_VERSION 1) 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) +cmake_policy(VERSION 2.8) +cmake_policy(SET CMP0017 NEW) #----------------------------------------------------------------------------- # Update CMake module path #------------------------------------------------------------------------------ set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/CMake ${CMAKE_MODULE_PATH} ) #----------------------------------------------------------------------------- # CMake function(s) and macro(s) #----------------------------------------------------------------------------- -include(MacroParseArguments) +include(CMakeParseArguments) +include(CMakePackageConfigHelpers) include(CheckCXXSourceCompiles) include(usFunctionCheckCompilerFlags) include(usFunctionEmbedResources) include(usFunctionGetGccVersion) include(usFunctionGenerateModuleInit) +include(usFunctionGenerateExecutableInit) #----------------------------------------------------------------------------- # 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) +if(WIN32 AND NOT CYGWIN) + set(default_runtime_install_dir bin/) + set(default_library_install_dir bin/) + set(default_archive_install_dir lib/) + set(default_header_install_dir include/) + set(default_auxiliary_install_dir share/) +else() + set(default_runtime_install_dir bin/) + set(default_library_install_dir lib/${PROJECT_NAME}) + set(default_archive_install_dir lib/${PROJECT_NAME}) + set(default_header_install_dir include/${PROJECT_NAME}) + set(default_auxiliary_install_dir share/${PROJECT_NAME}) +endif() + +us_cache_var(RUNTIME_INSTALL_DIR ${default_runtime_install_dir} STRING "Relative install location for binaries" ADVANCED) +us_cache_var(LIBRARY_INSTALL_DIR ${default_library_install_dir} STRING "Relative install location for libraries" ADVANCED) +us_cache_var(ARCHIVE_INSTALL_DIR ${default_archive_install_dir} STRING "Relative install location for archives" ADVANCED) +us_cache_var(HEADER_INSTALL_DIR ${default_header_install_dir} STRING "Relative install location for headers" ADVANCED) +us_cache_var(AUXILIARY_INSTALL_DIR ${default_auxiliary_install_dir} STRING "Relative install location for auxiliary files" ADVANCED) + +if(MSVC10 OR MSVC11 OR MSVC12) # 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() +set(${PROJECT_NAME}_MODULE_INIT_TEMPLATE "${CMAKE_CURRENT_SOURCE_DIR}/CMake/usModuleInit.cpp") +set(${PROJECT_NAME}_EXECUTABLE_INIT_TEMPLATE "${CMAKE_CURRENT_SOURCE_DIR}/CMake/usExecutableInit.cpp") #----------------------------------------------------------------------------- # US C/CXX Flags #----------------------------------------------------------------------------- -set(US_C_FLAGS "${COVERAGE_C_FLAGS} ${ADDITIONAL_C_FLAGS}") -set(US_CXX_FLAGS "${COVERAGE_CXX_FLAGS} ${ADDITIONAL_CXX_FLAGS}") +set(US_C_FLAGS) +set(US_C_FLAGS_RELEASE) +set(US_CXX_FLAGS) +set(US_CXX_FLAGS_RELEASE) # 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) + -Wstrict-null-sentinel -Wsign-promo -fdiagnostics-show-option) 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) + if(${GCC_VERSION} VERSION_LESS "4.0.0") + message(FATAL_ERROR "gcc version ${GCC_VERSION} not supported. Please use gcc >= 4.") + endif() # 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) + else() + set(US_GCC_RTTI_WORKAROUND_NEEDED 1) endif() endif() + usFunctionCheckCompilerFlags("-O1 -D_FORTIFY_SOURCE=2" _fortify_source_flag) + if(_fortify_source_flag) + set(US_CXX_FLAGS_RELEASE "${US_CXX_FLAGS_RELEASE} -D_FORTIFY_SOURCE=2") + 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_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${US_CXX_FLAGS_RELEASE}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${US_C_FLAGS}") + set(CMAKE_C_FLAGS_REALEASE "${CMAKE_C_FLAGS_RELEASE} ${US_C_FLAGS_RELEASE}") 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 +# link library for third party libs if(US_IS_EMBEDDED) - set(US_LINK_LIBRARIES ${US_EMBEDDING_LIBRARY}) + set(US_LIBRARY_TARGET ${US_EMBEDDING_LIBRARY}) else() - set(US_LINK_LIBRARIES ${PROJECT_NAME}) + set(US_LIBRARY_TARGET ${PROJECT_NAME}) endif() # link libraries for the CppMicroServices lib -set(_link_libraries ) +set(US_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}) + list(APPEND US_LINK_LIBRARIES dl) 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 +# Last configuration and install steps #----------------------------------------------------------------------------- -configure_file(${PROJECT_NAME}Config.cmake.in ${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake @ONLY) +if(NOT US_IS_EMBEDDED) + export(TARGETS ${PROJECT_NAME} ${US_RCC_EXECUTABLE_NAME} + FILE ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Targets.cmake) + install(EXPORT ${PROJECT_NAME}Targets + FILE ${PROJECT_NAME}Targets.cmake + DESTINATION ${AUXILIARY_INSTALL_DIR}/CMake/) +endif() + +set(_install_cmake_scripts + ${${PROJECT_NAME}_MODULE_INIT_TEMPLATE} + ${${PROJECT_NAME}_EXECUTABLE_INIT_TEMPLATE} + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/CMakeParseArguments.cmake + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/usFunctionGenerateModuleInit.cmake + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/usFunctionGenerateExecutableInit.cmake + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/usFunctionEmbedResources.cmake + ) + +install(FILES ${_install_cmake_scripts} + DESTINATION ${AUXILIARY_INSTALL_DIR}/CMake/ + ) + +# Configure CppMicroServicesConfig.cmake for the build tree + +set(PACKAGE_CONFIG_INCLUDE_DIR ${US_INCLUDE_DIRS}) +set(PACKAGE_CONFIG_RUNTIME_DIR ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +set(PACKAGE_CONFIG_CMAKE_DIR ${PROJECT_SOURCE_DIR}/CMake) +if(US_IS_EMBEDDED) + set(PACKAGE_EMBEDDED "if(@PROJECT_NAME@_IS_EMBEDDED) + set(@PROJECT_NAME@_INTERNAL_INCLUDE_DIRS @US_INTERNAL_INCLUDE_DIRS@) + set(@PROJECT_NAME@_SOURCES @US_SOURCES@) + set(@PROJECT_NAME@_PUBLIC_HEADERS @US_PUBLIC_HEADERS@) + set(@PROJECT_NAME@_PRIVATE_HEADERS @US_PRIVATE_HEADERS@) +endif()") +else() + set(PACKAGE_EMBEDDED ) +endif() + +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}Config.cmake.in + ${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake + @ONLY + ) + +# Configure CppMicroServicesConfig.cmake for the install tree +set(CONFIG_INCLUDE_DIR ${HEADER_INSTALL_DIR}) +set(CONFIG_RUNTIME_DIR ${RUNTIME_INSTALL_DIR}) +set(CONFIG_CMAKE_DIR ${AUXILIARY_INSTALL_DIR}/CMake) +configure_package_config_file( + ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}Config.cmake.in + ${PROJECT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${PROJECT_NAME}Config.cmake + INSTALL_DESTINATION ${AUXILIARY_INSTALL_DIR}/CMake/ + PATH_VARS CONFIG_INCLUDE_DIR CONFIG_RUNTIME_DIR CONFIG_CMAKE_DIR + NO_SET_AND_CHECK_MACRO + NO_CHECK_REQUIRED_COMPONENTS_MACRO + ) + +# Version information +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}ConfigVersion.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake + @ONLY + ) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${PROJECT_NAME}Config.cmake + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake + DESTINATION ${AUXILIARY_INSTALL_DIR}/CMake/ + COMPONENT sdk + ) + +#----------------------------------------------------------------------------- +# Build the examples +#----------------------------------------------------------------------------- + +option(US_BUILD_EXAMPLES "Build example projects" OFF) +if(US_BUILD_EXAMPLES) + if(NOT US_BUILD_SHARED_LIBS) + message(WARNING "Examples are not available if US_BUILD_SHARED_LIBS is OFF") + else() + set(CppMicroServices_DIR ${PROJECT_BINARY_DIR}) + add_subdirectory(examples) + endif() +endif() diff --git a/Core/Code/CppMicroServices/CTestConfig.cmake b/Core/CppMicroServices/CTestConfig.cmake similarity index 100% rename from Core/Code/CppMicroServices/CTestConfig.cmake rename to Core/CppMicroServices/CTestConfig.cmake diff --git a/Core/CppMicroServices/CppMicroServicesConfig.cmake.in b/Core/CppMicroServices/CppMicroServicesConfig.cmake.in new file mode 100644 index 0000000000..0a8e57d74d --- /dev/null +++ b/Core/CppMicroServices/CppMicroServicesConfig.cmake.in @@ -0,0 +1,36 @@ +@PACKAGE_INIT@ + +set(@PROJECT_NAME@_USE_CXX11 @US_USE_CXX11@) + +set(@PROJECT_NAME@_CXX_FLAGS "@US_CXX_FLAGS@") +set(@PROJECT_NAME@_CXX_FLAGS_RELEASE "@US_CXX_FLAGS_RELEASE@") +set(@PROJECT_NAME@_CXX_FLAGS_DEBUG "@US_CXX_FLAGS_DEBUG@") +set(@PROJECT_NAME@_C_FLAGS "@US_C_FLAGS@") +set(@PROJECT_NAME@_C_FLAGS_RELEASE "@US_C_FLAGS_RELEASE@") +set(@PROJECT_NAME@_C_FLAGS_DEBUG "@US_C_FLAGS_DEBUG@") + +set(@PROJECT_NAME@_INCLUDE_DIR @PACKAGE_CONFIG_INCLUDE_DIR@) + +set(@PROJECT_NAME@_RCC_EXECUTABLE_NAME @CppMicroServices_RCC_EXECUTABLE_NAME@) +set(@PROJECT_NAME@_MODULE_INIT_TEMPLATE @PACKAGE_CONFIG_CMAKE_DIR@/usModuleInit.cpp) +set(@PROJECT_NAME@_EXECUTABLE_INIT_TEMPLATE @PACKAGE_CONFIG_CMAKE_DIR@/usExecutableInit.cpp) + +set(@PROJECT_NAME@_INCLUDE_DIRS ${@PROJECT_NAME@_INCLUDE_DIR}) +set(@PROJECT_NAME@_LIBRARIES @US_LIBRARY_TARGET@) + +find_program(@PROJECT_NAME@_RCC_EXECUTABLE ${@PROJECT_NAME@_RCC_EXECUTABLE_NAME} + PATHS "@PACKAGE_CONFIG_RUNTIME_DIR@" + PATH_SUFFIXES Release Debug RelWithDebInfo MinSizeRel) +mark_as_advanced(@PROJECT_NAME@_RCC_EXECUTABLE) + +set(@PROJECT_NAME@_IS_EMBEDDED @US_IS_EMBEDDED@) +@PACKAGE_EMBEDDED@ + +if(NOT TARGET @PROJECT_NAME@ AND NOT @PROJECT_NAME@_IS_EMBEDDED) + include(${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake) +endif() + +include(@PACKAGE_CONFIG_CMAKE_DIR@/CMakeParseArguments.cmake) +include(@PACKAGE_CONFIG_CMAKE_DIR@/usFunctionGenerateModuleInit.cmake) +include(@PACKAGE_CONFIG_CMAKE_DIR@/usFunctionGenerateExecutableInit.cmake) +include(@PACKAGE_CONFIG_CMAKE_DIR@/usFunctionEmbedResources.cmake) diff --git a/Core/CppMicroServices/CppMicroServicesConfigVersion.cmake.in b/Core/CppMicroServices/CppMicroServicesConfigVersion.cmake.in new file mode 100644 index 0000000000..b5be35dea9 --- /dev/null +++ b/Core/CppMicroServices/CppMicroServicesConfigVersion.cmake.in @@ -0,0 +1,34 @@ +# The created file sets PACKAGE_VERSION_EXACT if the current version string and +# the requested version string are exactly the same and it sets +# PACKAGE_VERSION_COMPATIBLE if the current version major number == requested version major number +# and the current version minor number >= requested version minor number + +set(PACKAGE_VERSION_MAJOR @CppMicroServices_MAJOR_VERSION@) +set(PACKAGE_VERSION_MINOR @CppMicroServices_MINOR_VERSION@) +set(PACKAGE_VERSION_PATCH @CppMicroServices_PATCH_VERSION@) +set(PACKAGE_VERSION "@CppMicroServices_VERSION@") + +if(PACKAGE_VERSION VERSION_EQUAL PACKAGE_FIND_VERSION) + set(PACKAGE_VERSION_EXACT TRUE) +else() + set(PACKAGE_VERSION_EXACT FALSE) + if(NOT PACKAGE_VERSION_MAJOR EQUAL PACKAGE_FIND_VERSION_MAJOR) + set(PACKAGE_VERSION_COMPATIBLE FALSE) + elseif(PACKAGE_VERSION_MINOR LESS PACKAGE_FIND_VERSION_MINOR) + set(PACKAGE_VERSION_COMPATIBLE FALSE) + else() + set(PACKAGE_VERSION_COMPATIBLE TRUE) + endif() +endif() + +# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it: +if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "@CMAKE_SIZEOF_VOID_P@" STREQUAL "") + return() +endif() + +# check that the installed version has the same 32/64bit-ness as the one which is currently searching: +if(NOT "${CMAKE_SIZEOF_VOID_P}" STREQUAL "@CMAKE_SIZEOF_VOID_P@") + math(EXPR installedBits "@CMAKE_SIZEOF_VOID_P@ * 8") + set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)") + set(PACKAGE_VERSION_UNSUITABLE TRUE) +endif() diff --git a/Core/Code/CppMicroServices/LICENSE b/Core/CppMicroServices/LICENSE similarity index 100% rename from Core/Code/CppMicroServices/LICENSE rename to Core/CppMicroServices/LICENSE diff --git a/Core/Code/CppMicroServices/README.md b/Core/CppMicroServices/README.md similarity index 100% rename from Core/Code/CppMicroServices/README.md rename to Core/CppMicroServices/README.md diff --git a/Core/CppMicroServices/documentation/CMakeDoxygenFilter.cpp b/Core/CppMicroServices/documentation/CMakeDoxygenFilter.cpp new file mode 100644 index 0000000000..7aba552149 --- /dev/null +++ b/Core/CppMicroServices/documentation/CMakeDoxygenFilter.cpp @@ -0,0 +1,494 @@ +/*============================================================================= + + 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 + +//-------------------------------------- +// Utilitiy classes and functions +//-------------------------------------- + +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 toupper(c1) == toupper(c2); } + + static bool ne(char c1, char c2) + { return toupper(c1) != toupper(c2); } + + static bool lt(char c1, char c2) + { return toupper(c1) < toupper(c2); } + + static bool gt(char c1, char c2) + { return toupper(c1) > 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 && toupper(*s) != toupper(a)) + { + ++s; + } + return s; + } +}; + +typedef std::basic_string ci_string; + +//-------------------------------------- +// Lexer +//-------------------------------------- + +class CMakeLexer +{ +public: + + enum Token { + TOK_EOF = -1, + TOK_EOL = -2, + + // commands + TOK_MACRO = -3, TOK_ENDMACRO = -4, + TOK_FUNCTION = -5, TOK_ENDFUNCTION = -6, + TOK_DOXYGEN_COMMENT = -7, + TOK_SET = -8, + TOK_STRING_LITERAL = -100, + TOK_NUMBER_LITERAL = -102, + + // primary + TOK_IDENTIFIER = -200 + }; + + CMakeLexer(std::istream& is) + : _lastChar(' '), _is(is), _line(1), _col(1) + {} + + int getToken() + { + // skip whitespace + while (isspace(_lastChar) && _lastChar != '\r' && _lastChar != '\n') + { + _lastChar = getChar(); + } + + if (isalpha(_lastChar) || _lastChar == '_') + { + _identifier = _lastChar; + while (isalnum(_lastChar = getChar()) || _lastChar == '-' || _lastChar == '_') + { + _identifier += _lastChar; + } + + if (_identifier == "set") + return TOK_SET; + if (_identifier == "function") + return TOK_FUNCTION; + if (_identifier == "macro") + return TOK_MACRO; + if (_identifier == "endfunction") + return TOK_ENDFUNCTION; + if (_identifier == "endmacro") + return TOK_ENDMACRO; + return TOK_IDENTIFIER; + } + + if (isdigit(_lastChar)) + { + // very lax!! number detection + _identifier = _lastChar; + while (isalnum(_lastChar = getChar()) || _lastChar == '.' || _lastChar == ',') + { + _identifier += _lastChar; + } + return TOK_NUMBER_LITERAL; + } + + if (_lastChar == '#') + { + _lastChar = getChar(); + if (_lastChar == '!') + { + // found a doxygen comment marker + _identifier.clear(); + + _lastChar = getChar(); + while (_lastChar != EOF && _lastChar != '\n' && _lastChar != '\r') + { + _identifier += _lastChar; + _lastChar = getChar(); + } + return TOK_DOXYGEN_COMMENT; + } + + // skip the comment + while (_lastChar != EOF && _lastChar != '\n' && _lastChar != '\r') + { + _lastChar = getChar(); + } + } + + if (_lastChar == '"') + { + _lastChar = getChar(); + _identifier.clear(); + while (_lastChar != EOF && _lastChar != '"') + { + _identifier += _lastChar; + _lastChar = getChar(); + } + + // eat the closing " + _lastChar = getChar(); + return TOK_STRING_LITERAL; + } + + // don't eat the EOF + if (_lastChar == EOF) return TOK_EOF; + + // don't eat the EOL + if (_lastChar == '\r' || _lastChar == '\n') + { + if (_lastChar == '\r') _lastChar = getChar(); + if (_lastChar == '\n') _lastChar = getChar(); + return TOK_EOL; + } + + // return the character as its ascii value + int thisChar = _lastChar; + _lastChar = getChar(); + return thisChar; + } + + std::string getIdentifier() const + { + return std::string(_identifier.c_str()); + } + + int curLine() const + { return _line; } + + int curCol() const + { return _col; } + + int getChar() + { + int c = _is.get(); + updateLoc(c); + return c; + } + +private: + + void updateLoc(int c) + { + if (c == '\n' || c == '\r') + { + ++_line; + _col = 1; + } + else + { + ++_col; + } + } + + ci_string _identifier; + int _lastChar; + std::istream& _is; + + int _line; + int _col; +}; + +//-------------------------------------- +// Parser +//-------------------------------------- + +class CMakeParser +{ + +public: + + CMakeParser(std::istream& is, std::ostream& os) + : _is(is), _os(os), _lexer(is), _curToken(CMakeLexer::TOK_EOF), _lastToken(CMakeLexer::TOK_EOF) + { } + + int curToken() + { + return _curToken; + } + + int nextToken() + { + _lastToken = _curToken; + _curToken = _lexer.getToken(); + while (_curToken == CMakeLexer::TOK_EOL) + { + // Try to preserve lines in output to allow correct line number referencing by doxygen. + _os << std::endl; + _curToken = _lexer.getToken(); + } + return _curToken; + } + + void handleMacro() + { + if(!parseMacro()) + { + // skip token for error recovery + nextToken(); + } + } + + void handleFunction() + { + if(!parseFunction()) + { + // skip token for error recovery + nextToken(); + } + } + + void handleSet() + { + // SET(var ...) following a documentation block is assumed to be a variable declaration. + if (_lastToken != CMakeLexer::TOK_DOXYGEN_COMMENT) + { + // No comment block before + nextToken(); + } else if(!parseSet()) + { + // skip token for error recovery + nextToken(); + } + } + + void handleDoxygenComment() + { + _os << "///" << _lexer.getIdentifier(); + nextToken(); + } + + void handleTopLevelExpression() + { + // skip token + nextToken(); + } + +private: + + void printError(const char* str) + { + std::cerr << "Error: " << str << " (at line " << _lexer.curLine() << ", col " << _lexer.curCol() << ")"; + } + + bool parseMacro() + { + if (nextToken() != '(') + { + printError("Expected '(' after MACRO"); + return false; + } + + nextToken(); + std::string macroName = _lexer.getIdentifier(); + if (curToken() != CMakeLexer::TOK_IDENTIFIER || macroName.empty()) + { + printError("Expected macro name"); + return false; + } + + _os << macroName << '('; + if (nextToken() == CMakeLexer::TOK_IDENTIFIER) + { + _os << _lexer.getIdentifier(); + while (nextToken() == CMakeLexer::TOK_IDENTIFIER) + { + _os << ", " << _lexer.getIdentifier(); + } + } + + if (curToken() != ')') + { + printError("Missing expected ')'"); + } + else + { + _os << ");"; + } + + // eat the ')' + nextToken(); + return true; + } + + bool parseSet() + { + if (nextToken() != '(') + { + printError("Expected '(' after SET"); + return false; + } + + nextToken(); + std::string variableName = _lexer.getIdentifier(); + if (curToken() != CMakeLexer::TOK_IDENTIFIER || variableName.empty()) + { + printError("Expected variable name"); + return false; + } + + _os << "CMAKE_VARIABLE " << variableName; + + nextToken(); + while ((curToken() == CMakeLexer::TOK_IDENTIFIER) + || (curToken() == CMakeLexer::TOK_STRING_LITERAL) + || (curToken() == CMakeLexer::TOK_NUMBER_LITERAL)) + { + nextToken(); + } + + if (curToken() != ')') + { + printError("Missing expected ')'"); + } + else + { + _os << ";"; + } + + // eat the ')' + nextToken(); + return true; + } + + bool parseFunction() + { + if (nextToken() != '(') + { + printError("Expected '(' after FUNCTION"); + return false; + } + + nextToken(); + std::string funcName = _lexer.getIdentifier(); + if (curToken() != CMakeLexer::TOK_IDENTIFIER || funcName.empty()) + { + printError("Expected function name"); + return false; + } + + _os << funcName << '('; + if (nextToken() == CMakeLexer::TOK_IDENTIFIER) + { + _os << _lexer.getIdentifier(); + while (nextToken() == CMakeLexer::TOK_IDENTIFIER) + { + _os << ", " << _lexer.getIdentifier(); + } + } + + if (curToken() != ')') + { + printError("Missing expected ')'"); + } + else + { + _os << ");"; + } + + // eat the ')' + nextToken(); + + return true; + } + + std::istream& _is; + std::ostream& _os; + CMakeLexer _lexer; + int _curToken; + int _lastToken; +}; + + +#define STRINGIFY(a) #a +#define DOUBLESTRINGIFY(a) STRINGIFY(a) + +int main(int argc, char** argv) +{ + assert(argc > 1); + + for (int i = 1; i < argc; ++i) + { + std::ifstream ifs(argv[i]); + std::ostream& os = std::cout; + + #ifdef USE_NAMESPACE + os << "namespace " << DOUBLESTRINGIFY(USE_NAMESPACE) << " {\n"; + #endif + + CMakeParser parser(ifs, os); + parser.nextToken(); + while (ifs.good()) + { + switch (parser.curToken()) + { + case CMakeLexer::TOK_EOF: + return ifs.get(); // eat EOF + case CMakeLexer::TOK_MACRO: + parser.handleMacro(); + break; + case CMakeLexer::TOK_FUNCTION: + parser.handleFunction(); + break; + case CMakeLexer::TOK_SET: + parser.handleSet(); + break; + case CMakeLexer::TOK_DOXYGEN_COMMENT: + parser.handleDoxygenComment(); + break; + default: + parser.handleTopLevelExpression(); + break; + } + } + + #ifdef USE_NAMESPACE + os << "}\n"; + #endif + } + + return EXIT_SUCCESS; +} diff --git a/Core/Code/CppMicroServices/documentation/CMakeLists.txt b/Core/CppMicroServices/documentation/CMakeLists.txt similarity index 61% rename from Core/Code/CppMicroServices/documentation/CMakeLists.txt rename to Core/CppMicroServices/documentation/CMakeLists.txt index 8ce17b7663..7aec333a00 100644 --- a/Core/Code/CppMicroServices/documentation/CMakeLists.txt +++ b/Core/CppMicroServices/documentation/CMakeLists.txt @@ -1,65 +1,84 @@ if(US_BUILD_TESTING) include(usFunctionCompileSnippets) # Compile source code snippets add_subdirectory(snippets) endif() -if(NOT US_IS_EMBEDDED) +if(NOT US_IS_EMBEDDED AND NOT US_NO_DOCUMENTATION) 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) - + configure_file(doxygen/doxygen_extra.css + ${CMAKE_CURRENT_BINARY_DIR}/doxygen_extra.css COPY_ONLY) + set(US_DOXYGEN_EXTRA_CSS doxygen_extra.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() - + + # Compile a command line tool which transforms comments in CMake scripts into + # Doxygen parseable C code. + set(CMakeDoxygenFilter_EXECUTABLE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CMakeDoxygenFilter${CMAKE_EXECUTABLE_SUFFIX}") + try_compile(_result_var + "${CMAKE_CURRENT_BINARY_DIR}" + "${CMAKE_CURRENT_SOURCE_DIR}/CMakeDoxygenFilter.cpp" + OUTPUT_VARIABLE _compile_output + COPY_FILE ${CMakeDoxygenFilter_EXECUTABLE} + ) + + if(NOT _result_var) + message(FATAL_ERROR "error: Faild to compile ${CMAKE_CURRENT_SOURCE_DIR}/CMakeDoxygenFilter.cpp (result: ${result_var})\n${_compile_output}") + 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} ) + + install(CODE "execute_process(COMMAND \"${CMAKE_COMMAND}\" --build \"${PROJECT_BINARY_DIR}\" --target doc)") + + install(DIRECTORY ${US_DOXYGEN_OUTPUT_DIR}/${US_DOXYGEN_HTML_OUTPUT} + DESTINATION ${AUXILIARY_INSTALL_DIR}/doc/ + COMPONENT doc) endif() endif() - diff --git a/Core/Code/CppMicroServices/documentation/doxygen.conf.in b/Core/CppMicroServices/documentation/doxygen.conf.in similarity index 92% rename from Core/Code/CppMicroServices/documentation/doxygen.conf.in rename to Core/CppMicroServices/documentation/doxygen.conf.in index b3f88c4728..275eb52db2 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen.conf.in +++ b/Core/CppMicroServices/documentation/doxygen.conf.in @@ -1,1808 +1,1894 @@ -# Doxyfile 1.8.1 +# Doxyfile 1.8.3.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. +# path to strip. Note that you specify absolute paths here, but also +# relative paths, which will be relative from the directory where doxygen is +# started. 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 +JAVADOC_AUTOBRIEF = YES # 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. +# 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 +# When enabled doxygen tries to link words that correspond to documented classes, +# or namespaces to their corresponding documentation. Such a link can be +# prevented in individual cases by by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. + +AUTOLINK_SUPPORT = YES + # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); 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 +# 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 +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. +# 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. +# documentation sections, marked by \if section-label ... \endif +# and \cond section-label ... \endcond blocks. 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 +# output files in an output format independent way. To create the layout file # that represents doxygen's defaults, run doxygen with the -l option. # You can optionally specify a file name after the option, if omitted # DoxygenLayout.xml will be used as the name of the layout file. 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. +# feature you need bibtex and perl available in the search path. Do not use +# file names with spaces, bibtex cannot handle them. 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_SOURCE_DIR@/CMake/usFunctionEmbedResources.cmake \ + @PROJECT_SOURCE_DIR@/CMake/usFunctionGenerateModuleInit.cmake \ + @PROJECT_SOURCE_DIR@/CMake/usFunctionGenerateExecutableInit.cmake \ @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@/examples/ \ @PROJECT_SOURCE_DIR@/test/ \ - @PROJECT_SOURCE_DIR@/gh-pages \ + @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 +EXCLUDE_SYMBOLS = us \ + US_NAMESPACE \ + *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 = @PROJECT_SOURCE_DIR@/documentation/snippets/ +EXAMPLE_PATH = @PROJECT_SOURCE_DIR@/documentation/snippets/ \ + @PROJECT_SOURCE_DIR@/examples/ # 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 = +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 = +# If the USE_MD_FILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page (index.html). +# This can be useful if you have a project on for instance GitHub and want reuse +# the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = + #--------------------------------------------------------------------------- # 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. +# fragments. Normal C, C++ and Fortran comments will always remain visible. -STRIP_CODE_COMMENTS = YES +STRIP_CODE_COMMENTS = NO # 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! +# fine-tune the look of the HTML output. If left blank doxygen will +# generate a default style sheet. Note that it is recommended to use +# HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this +# tag will in the future become obsolete. + +HTML_STYLESHEET = -HTML_STYLESHEET = @US_DOXYGEN_CSS@ +# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional +# user-defined cascading style sheet that is included after the standard +# style sheets created by doxygen. Using this option one can overrule +# certain style aspects. This is preferred over using HTML_STYLESHEET +# since it does not replace the standard style sheet and is therefor more +# robust against future updates. Doxygen will copy the style sheet file to +# the output directory. + +HTML_EXTRA_STYLESHEET = @US_DOXYGEN_EXTRA_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. +# 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 can set the default output format to be used for +# thA MathJax output. Supported types are HTML-CSS, NativeMML (i.e. MathML) and +# SVG. The default value is HTML-CSS, which is slower, but has the best +# compatibility. + +MATHJAX_FORMAT = HTML-CSS + # When MathJax is enabled you need to specify the location relative to the # HTML output directory using the MATHJAX_RELPATH option. The destination # directory should contain the MathJax.js script. For instance, if the mathjax # directory is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to # the MathJax Content Delivery Network so you can quickly see the result without # installing MathJax. # However, it is strongly recommended to install a local # copy of MathJax from 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. +# implemented using a web server instead of a web client using Javascript. +# There are two flavours of web server based search depending on the +# EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for +# searching and an index file used by the script. When EXTERNAL_SEARCH is +# enabled the indexing and searching needs to be provided by external tools. +# See the manual for details. SERVER_BASED_SEARCH = NO +# When EXTERNAL_SEARCH is enabled doxygen will no longer generate the PHP +# script for searching. Instead the search results are written to an XML file +# which needs to be processed by an external indexer. Doxygen will invoke an +# external search engine pointed to by the SEARCHENGINE_URL option to obtain +# the search results. Doxygen ships with an example indexer (doxyindexer) and +# search engine (doxysearch.cgi) which are based on the open source search engine +# library Xapian. See the manual for configuration details. + +EXTERNAL_SEARCH = NO + +# The SEARCHENGINE_URL should point to a search engine hosted by a web server +# which will returned the search results when EXTERNAL_SEARCH is enabled. +# Doxygen ships with an example search engine (doxysearch) which is based on +# the open source search engine library Xapian. See the manual for configuration +# details. + +SEARCHENGINE_URL = + +# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed +# search data is written to a file for indexing by an external tool. With the +# SEARCHDATA_FILE tag the name of this file can be specified. + +SEARCHDATA_FILE = searchdata.xml + +# When SERVER_BASED_SEARCH AND EXTERNAL_SEARCH are both enabled the +# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is +# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple +# projects and redirect the results back to the right project. + +EXTERNAL_SEARCH_ID = + +# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen +# projects other than the one defined by this configuration file, but that are +# all added to the same external search index. Each project needs to have a +# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id +# of to a relative location where the documentation can be found. +# The format is: EXTRA_SEARCH_MAPPINGS = id1=loc1 id2=loc2 ... + +EXTRA_SEARCH_MAPPINGS = + #--------------------------------------------------------------------------- # 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/CppMicroServices/documentation/doxygen/MicroServices.dox b/Core/CppMicroServices/documentation/doxygen/MicroServices.dox new file mode 100644 index 0000000000..86032cd9d6 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices.dox @@ -0,0 +1,126 @@ + +/** + +\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. + +*/ + +/** + +\defgroup MicroServicesCMake CMake Functions + +\brief This category includes CMake utility functions for external projects. + +External projects can include the CMake scripts provided by the CppMicroServices +library to automatically generate module initialization code and to embed external resources +into a modules shared library. + +*/ + +/** + +\page MicroServices_Tutorials Tutorial + +This tutorial creates successively more complex modules to illustrate +most of the features and functionality offered by the C++ Micro Services library. +It is heavily base on the Apache Felix OSGi Tutorial. + +- \subpage MicroServices_Example1 +- \subpage MicroServices_Example2 +- \subpage MicroServices_Example2b +- \subpage MicroServices_Example3 +- \subpage MicroServices_Example4 +- \subpage MicroServices_Example5 +- \subpage MicroServices_Example6 +- \subpage MicroServices_Example7 + +*/ + +/** + +\page MicroServices_UserDocs User Documentation + +This is a list of available documentation for different aspects of the C++ +Micro Services library: + +\if us_standalone +- \subpage BuildInstructions +- \subpage MicroServices_GettingStarted +\endif +- \subpage MicroServices_TheModuleContext +- \subpage MicroServices_Resources +- \subpage MicroServices_ModuleProperties +- \subpage MicroServices_AutoLoading +- \subpage MicroServices_StaticModules +- \subpage MicroServices_EmulateSingleton + +*/ + +/** + +\embmainpage{MicroServices_Overview} The C++ Micro Services + +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. + +\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 + +

Tutorial

+ +\if us_standalone +Here is a list of \ref MicroServices_Tutorials "tutorial examples" +\else +Here is a list of \subpage MicroServices_Tutorials "tutorial examples" +\endif +which create successively more complex modules to illustrate most of the features and +functionality offered by the C++ Micro Services library: + +- \ref MicroServices_Example1 +- \ref MicroServices_Example2 +- \ref MicroServices_Example2b +- \ref MicroServices_Example3 +- \ref MicroServices_Example4 +- \ref MicroServices_Example5 +- \ref MicroServices_Example6 +- \ref MicroServices_Example7 + +

User Documentation

+ +The links in the following list point to important +\if us_standalone +\ref MicroServices_UserDocs "user documentation": +\else +\subpage MicroServices_UserDocs "user documentation": +\endif + +\if us_standalone +- \ref BuildInstructions +- \ref MicroServices_GettingStarted +\endif +- \ref MicroServices_TheModuleContext +- \ref MicroServices_Resources +- \ref MicroServices_ModuleProperties +- \ref MicroServices_AutoLoading +- \ref MicroServices_StaticModules +- \ref MicroServices_EmulateSingleton + +*/ diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md b/Core/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md similarity index 74% rename from Core/Code/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md rename to Core/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md index 7e2ca58433..66a39cbb95 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md @@ -1,78 +1,86 @@ 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. +See the ModuleSettings class for details about auto-load paths. The auto-load directory of +a module defaults to the module's library name, but can be customized using a `manifest.json` +file (see \ref MicroServices_ModuleProperties). For executables, the auto-load directory +defaults to the special value `main`. This allows third-party modules to be auto-loaded +during application start-up, without having to reference a special auto-load directory. If module *A* in the example above contains initialization code like \code -US_INITIALIZE_MODULE("Module A", "A", "", "1.0.0") +US_INITIALIZE_MODULE("Module A", "A") \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. +\note If you need to add additional auto-load search paths during application start-up, provide +a ModuleActivator instance in your executable and call ModuleSettings::AddAutoLoadPath() in +your executable's ModuleActivator::Load() method. If there are modules inside a `main` sub-directory +of any of the provided auto-load search paths, these modules will then be auto-loaded before +your executable's main() function is executed. + 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/CppMicroServices/documentation/doxygen/MicroServices_Debugging.dox similarity index 100% rename from Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Debugging.dox rename to Core/CppMicroServices/documentation/doxygen/MicroServices_Debugging.dox diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox b/Core/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox similarity index 95% rename from Core/Code/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox rename to Core/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox index 0b3094f105..55e51753e9 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox @@ -1,91 +1,89 @@ /** \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. + - 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/CppMicroServices/documentation/doxygen/MicroServices_ModuleProperties.md b/Core/CppMicroServices/documentation/doxygen/MicroServices_ModuleProperties.md new file mode 100644 index 0000000000..29464ae39b --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices_ModuleProperties.md @@ -0,0 +1,51 @@ +Module Properties {#MicroServices_ModuleProperties} +================= + +A C++ Micro Services Module provides meta-data in the form of so-called *properties* about itself. +Properties are key - value pairs where the key is of type `std::string` and the value of type `Any`. +The following properties are always set by the C++ Micro Services library and cannot be altered by +the module author: + + * `module.id` - The unique id of the module (type `long`) + * `module.name` - The human readable name of the module (type `std::string`) + * `module.location` - The full path to the module's shared library on the file system (type `std::string`) + +Module authors can add custom properties by providing a `manifest.json` file, embedded as a top-level +resource into the module (see \ref MicroServices_Resources). The root value of the Json file must be +a Json object. An example `manifest.json` file would be: + +~~~{.json} +{ + "module.version" : "1.0.2", + "module.description" : "This module provides an awesome service", + "authors" : [ "John Doe", "Douglas Reynolds", "Daniel Cannady" ], + "rating" : 5 +} +~~~ + +All Json member names of the root object will be available as property keys in the module containing +the `manifest.json` file. The C++ Micro Services library specifies the following standard keys for +re-use in `manifest.json` files: + + * `module.version` - The version of the module (type `std::string`). The version string must be a + valid version identifier, as specified in the ModuleVersion class. + * `module.vendor` - The vendor name of the module (type `std::string`) + * `module.description` - A description for the module (type `std::string`) + * `module.autoload_dir` - A custom auto-load directory for the module (type `std::string`). If not + set, this property defaults to the module's library name. + +\note Some of the properties mentioned above may also be accessed via dedicated methods in the Module class, +e.g. Module::GetName() or Module::GetVersion(). + +When parsing the `manifest.json` file, the Json types are mapped to C++ types and stored in instances of +the Any class. The mapping is as follows: + +| Json | C++ (%Any) | +|-------|-----------| +|object | std::map | +|array | std::vector | +|string | std::string | +|number | int or double | +|true | bool | +|false | bool | +|null | %Any() | diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Resources.md b/Core/CppMicroServices/documentation/doxygen/MicroServices_Resources.md similarity index 94% rename from Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Resources.md rename to Core/CppMicroServices/documentation/doxygen/MicroServices_Resources.md index da80b20349..101044d143 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Resources.md +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices_Resources.md @@ -1,56 +1,56 @@ 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 +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/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md similarity index 84% rename from Core/Code/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md rename to Core/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md index a62d196755..344cfb5146 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md @@ -1,92 +1,90 @@ 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 +# 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 +# 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). +using a ModuleContext), the importing library or executable needs to put a call to the `#US_INITIALIZE_MODULE` +or the `#US_INITIALIZE_EXECUTABLE` 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 +## 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. +needs to provide a module context by calling the `#US_INITIALIZE_MODULE` or `#US_INITIALIZE_EXECUTABLE` 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. +Note that shared (but not static) modules also need the `#US_INITIALIZE_MODULE` call when importing static modules. -### Using a Static CppMicroServices Library +## 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} +# 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). +the `#US_INITIALIZE_MODULE` or `#US_INITIALIZE_EXECUTABLE` 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/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md similarity index 75% rename from Core/Code/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md rename to Core/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md index dc7b9cda42..f35054b556 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md @@ -1,36 +1,37 @@ 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 +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}) - +~~~{.cpp} +set(module_srcs ) +usFunctionGenerateModuleInit(module_srcs + NAME "My Module" + LIBRARY_NAME "mylibname" + ) +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/CppMicroServices/documentation/doxygen/doxygen_extra.css b/Core/CppMicroServices/documentation/doxygen/doxygen_extra.css new file mode 100644 index 0000000000..4328573360 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/doxygen_extra.css @@ -0,0 +1,283 @@ + +#MSearchField { + height: 14px; +} + +#MSearchClose { + top: 1px; +} + +#MSearchResultsWindow { + z-index: 200; +} + +body { + background-color: inherit; +} + +body, table, div, p, dl { + font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; + font-size: 13px; + line-height: 18px; + color: #333333; +} + +h1 { + font-size: 150%; +} + +h2 { + font-size: 120%; +} + +h3 { + font-size: 100%; +} + +a { + color: #0088CC; +} + +div#top { + background-color: #F5F5F5; + margin: -20px -20px 20px; +} + +.tabs, .tabs2, .tabs3 { + font-size: 16px; + position: relative; + background-image: none; +} + +.tabs2 { + font-size: 14px; +} +.tabs3 { + font-size: 12px; +} + +.tablist li { + background-image: none; + line-height: inherit; +} + +.tablist a { + background-image: none; + padding: 10px 20px; + color: #999999; +} + +.tablist a:hover { + text-decoration: underline; + background-image: none; + text-shadow: none; + color: #999999; +} + +.tablist li.current a { + background-image: none; + background-color: #BBBBBB; + text-shadow: none; +} + +div.qindex, div.navtab { + background-color: inherit; + border: 1px solid #e6e6e6; +} + +h2.groupheader { + border: none; + font-size: 120%; + font-weight: bold; + color: #333333; +} + +pre.fragment { + border: none; + border-top-style: solid; + border-bottom-style: solid; + border-width: 1px 0 1px 0; + border-color: #e6e6e6; + border-radius: 0; +} + +div.fragment { + padding: 4px 6px; + margin: 4px 8px 4px 2px; + border: none; + border-top-style: solid; + border-bottom-style: solid; + border-width: 1px 0 1px 0; + border-color: #e6e6e6; + background-color: #F5F5F5; +} + +div.line { + -webkit-transition-property: none; + -moz-transition-property: none; + -ms-transition-property: none; + -o-transition-property: none; + transition-property: none; +} + +div.ah { + background-color: #f6f6f6; + border: solid thin #e6e6e6; + box-shadow: none; + -webkit-box-shadow: none; + -moz-box-shadow: none; + background-image: none; + color: #333333; +} + +td.indexkey, td.indexvalue { + background-color: inherit; + border: none; +} + +tr.separator\3A, td.memSeparator { + display: none; +} + +hr { + border-top: 1px solid #e6e6e6; +} + +.mdescLeft, .mdescRight, +.memItemLeft, .memItemRight, +.memTemplItemLeft, .memTemplItemRight, .memTemplParams { + background-color: inherit; +} + +.memItemLeft, .memItemRight, .memTemplParams { + border: none; +} + +.memproto, dl.reflist dt { + border-top: 1px solid #e6e6e6; + border-left: 1px solid #e6e6e6; + border-right: 1px solid #e6e6e6; + text-shadow: none; + background-image: none; + background-color: #f6f6f6; + /* opera specific markup */ + box-shadow: none; + border-top-right-radius: 8px; + border-top-left-radius: 8px; + /* firefox specific markup */ + -moz-box-shadow: none; + -moz-border-radius-topright: 8px; + -moz-border-radius-topleft: 8px; + /* webkit specific markup */ + -webkit-box-shadow: none; + -webkit-border-top-right-radius: 8px; + -webkit-border-top-left-radius: 8px; +} + +.memdoc, dl.reflist dd { + border-bottom: 1px solid #e6e6e6; + border-left: 1px solid #e6e6e6; + border-right: 1px solid #e6e6e6; + padding: 2px 5px; + background-color: inherit; + background-image: none; + border-top-width: 0; + /* opera specific markup */ + border-bottom-left-radius: 8px; + border-bottom-right-radius: 8px; + box-shadow:none; + /* firefox specific markup */ + -moz-border-radius-bottomleft: 8px; + -moz-border-radius-bottomright: 8px; + -moz-box-shadow: none; + /* webkit specific markup */ + -webkit-border-bottom-left-radius: 8px; + -webkit-border-bottom-right-radius: 8px; + -webkit-box-shadow: none; +} + +.paramname code { + line-height: inherit; +} + +.params .paramname, .tparams .paramname, .retval .paramname { + padding-right: 10px; +} + +span.mlabel { + border-top:1px solid #405C93; + border-left:1px solid #405C93; +} + +div.directory { + border: none; +} + +.directory td { + vertical-align: baseline; +} + +.directory tr.even { + background-color: inherit; +} + +address { + color: inherit; + margin: 0; +} + +.navpath ul +{ + background-image: none; + height: auto; + line-height: inherit; + color: inherit; + border: none; +} + +.navpath li +{ + background-image: none; + color: inherit; +} + +.navpath li.navelem a +{ + height:22px; + color: #999; +} + +.navpath li.navelem a:hover +{ + text-decoration: underline; +} + +div.ingroups +{ + margin-left: 5px; + padding-left: 5px; +} + +div.header +{ + background-image: none; + background-color: inherit; + border-bottom: 1px solid #333333; +} + +div.headertitle +{ + padding: 0px 5px 0px 7px; +} + +dl.note, dl.warning, dl.attention, dl.pre, dl.post, dl.invariant, dl.deprecated, dl.todo, dl.test, dl.bug +{ + margin-left: 12px; +} + +code { + background-color: none; + border: none; + color: #333333; + padding: 1; +} diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example1.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example1.md new file mode 100644 index 0000000000..e5c92e2981 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example1.md @@ -0,0 +1,97 @@ +Example 1 - Service Event Listener {#MicroServices_Example1} +================================== + +This example creates a simple module that listens for service events. +This example does not do much at first, because it only prints out the details +of registering and unregistering services. In the next example we will create +a module that implements a service, which will cause this module to actually +do something. For now, we will just use this example to help us understand the +basics of creating a module and its activator. + +A module gains access to the C++ Micro Services API using a unique instance +of ModuleContext. This unique module context can be used during static +initialization of the module or at any later point during the life-time of the +module. To execute code during static initialization (and de-initialization) +time, the module must provide an implementation of the ModuleActivator interface; +this interface has two methods, Load() and Unload(), that both receive the +module's context and are called when the module is loaded (statically initialized) +and unloaded, respectively. + +\note You do not need to remember the ModuleContext instance within the +ModuleActivator::Load() method and provide custom access methods for later +retrieval. Use the GetModuleContext() function to easily retrieve the current +module's context. + +In the following source code, our module implements +the ModuleActivator interface and uses the context to add itself as a listener +for service events (in the `eventlistener/Activator.cpp` file): + +\snippet eventlistener/Activator.cpp Activator + +After implementing the C++ source code for the module activator, we must *export* +the activator such that the C++ Micro Services library can create an instance +of it and call the `Load()` and `Unload()` methods: + +\dontinclude eventlistener/Activator.cpp +\skipline US_EXPORT + +Now we need to compile the source code. This example uses CMake as the build +system and the top-level CMakeLists.txt file could look like this: + +\dontinclude examples/CMakeLists.txt +\skip project +\until eventlistener + +and the CMakeLists.txt file in the eventlistener subdirectory is: + +\include eventlistener/CMakeLists.txt + +The call to `#usFunctionGenerateModuleInit` is necessary to integrate the shared +library as a module within the C++ Micro Service library. If you are not using +CMake, you have to place a macro call to `#US_INITIALIZE_MODULE` yourself into the +module's source code, e.g. in `Activator.cpp`. Have a look at the +\ref MicroServices_GettingStarted documentation for more details about using CMake +or other build systems (e.g. Makefiles) when writing modules. + +To run the examples contained in the C++ Micro Services library, we use a small +driver program called `CppMicroServicesExampleDriver`: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> h +h This help text +l Load the module with id or name +u Unload the module with id +s Print status information +q Quit +> +\endverbatim + +Typing `s` at the command prompt lists the available, loaded, and unloaded modules. +To load the eventlistener module, type `l eventlistener` at the command prompt: + +\verbatim +> s +Id | Name | Status +----------------------------------- + - | dictionaryclient | - + - | dictionaryclient2 | - + - | dictionaryclient3 | - + - | dictionaryservice | - + - | eventlistener | - + - | frenchdictionary | - + - | spellcheckclient | - + - | spellcheckservice | - + 1 | CppMicroServices | LOADED +> l eventlistener +Starting to listen for service events. +> +\endverbatim + +The above command loaded the eventlistener module (by loading its shared library). +Keep in mind, that this module will not do much at this point since it only +listens for service events and we are not registering any services. In the next +example we will register a service that will generate an event for this module to +receive. To exit the `CppMicroServicesExampleDriver`, use the `q` command. + +Next: \ref MicroServices_Example2 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example2.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example2.md new file mode 100644 index 0000000000..b7fe0bbca3 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example2.md @@ -0,0 +1,87 @@ +Example 2 - Dictionary Service Module {#MicroServices_Example2} +===================================== + +This example creates a module that implements a service. Implementing a +service is a two-step process, first we must define the interface of the service +and then we must define an implementation of the service 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. First, +we will start by defining a simple dictionary service interface in a file called +`dictionaryservice/IDictionaryService.h`: + +\snippet dictionaryservice/IDictionaryService.h service + +The service interface is quite simple, with only one method that needs to be +implemented. Because we provide an empty out-of-line destructor (defined in the +file `IDictionaryService.cpp`) we must export the service interface by using the +module specific `DICTIONARYSERVICE_EXPORT` macro. + +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. The source code for our module is as follows in a file called +`dictionaryservice/Activator.cpp`: + +\snippet dictionaryservice/Activator.cpp Activator + +Note that we do not need to unregister the service in the Unload() method, +because the C++ Micro Services library will automatically do so for us. The +dictionary service that we have implemented is very simple; its dictionary +is a set of only five words, so this solution is not optimal and is only +intended for educational purposes. + +\note In this example, the service interface and implementation are both +contained in one module which exports the interface class. However, service +implementations almost never need to be exported and in many use cases +it is beneficial to provide the service interface and its implementation(s) +in separate modules. In such a scenario, clients of a service will only +have a link-time dependency on the shared library providing the service interface +(because of the out-of-line destructor) but not on any modules containing +service implementations. This often leads to modules which do not export +any symbols at all and hence need to be loaded into the running process +manually or by using the \ref MicroServices_AutoLoading "auto-loading mechanism". + +For an introduction how to compile our source code, see \ref MicroServices_Example1. + +After running the `CppMicroServicesExampleDriver` program we should make sure that the +module from Example 1 is active. We can use the `s` shell command to get +a list of all modules, their state, and their module identifier number. +If the Example 1 module is not active, we should load the module using the +load command and the module's identifier number or name that is displayed +by the `s` command. Now we can load our dictionary service module by typing +the `l dictionaryservice` command: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> s +Id | Name | Status +----------------------------------- + - | dictionaryservice | - + - | eventlistener | - + 1 | CppMicroServices | LOADED +> l eventlistener +Starting to listen for service events. +> l dictionaryservice +Ex1: Service of type IDictionaryService/1.0 registered. +> s +Id | Name | Status +----------------------------------- + 1 | CppMicroServices | LOADED + 2 | Event Listener | LOADED + 3 | Dictionary Service | LOADED +> +\endverbatim + +To unload the module, use the `u ` command. If the module from +\ref MicroServices_Example1 "Example 1" is still active, +then we should see it print out the details of the service event it receives +when our new module registers its dictionary service. Using the `CppMicroServicesExampleDriver` +commands `u` and `l` we can unload and load it at will, respectively. Each +time we load and unload our dictionary service module, we should see the details +of the associated service event printed from the module from Example 1. In +\ref MicroServices_Example3 "Example 3", we will create a client for our +dictionary service. To exit `CppMicroServicesExampleDriver`, we use the `q` command. + +Next: \ref MicroServices_Example2b + +Previous: \ref MicroServices_Example1 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example2b.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example2b.md new file mode 100644 index 0000000000..4045a8e483 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example2b.md @@ -0,0 +1,76 @@ +Example 2b - Alternative Dictionary Service Module {#MicroServices_Example2b} +================================================== + +This example creates an alternative implementation of the dictionary service +defined in \ref MicroServices_Example2 "Example 2". The source code for the +module is identical except that instead of using English words, French words +are used. The only other difference is that in this module we do not need to +define the dictionary service interface again, since we can just link the +definition from the module in Example 2. The main point of this example is +to illustrate that multiple implementations of the same service may exist; +this example will also be of use to us in \ref MicroServices_Example5 "Example 5". + +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. The source code for our module is as follows in a file called +`dictionaryclient/Activator.cpp`: + +\snippet frenchdictionary/Activator.cpp Activator + +For an introduction how to compile our source code, see \ref MicroServices_Example1. +Because we use the `IDictionaryService` definition from Example 2, we also +need to make sure that the proper include paths and linker dependencies are set: + +\include frenchdictionary/CMakeLists.txt + +After running the `CppMicroServicesExampleDriver` program we should make sure that the +module from Example 1 is active. We can use the `s` shell command to get +a list of all modules, their state, and their module identifier number. +If the Example 1 module is not active, we should load the module using the +load command and the module's identifier number or name that is displayed +by the `s` command. Now we can load our dictionary service module by typing +the `l frenchdictionary` command: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> s +Id | Name | Status +----------------------------------- + - | dictionaryservice | - + - | eventlistener | - + - | frenchdictionary | - + 1 | CppMicroServices | LOADED +> l eventlistener +Starting to listen for service events. +> l frenchdictionary +Ex1: Service of type IDictionaryService/1.0 registered. +Ex1: Service of type IDictionaryService/1.0 registered. +> s +Id | Name | Status +----------------------------------- + 1 | CppMicroServices | LOADED + 2 | Event Listener | LOADED + 3 | Dictionary Service | LOADED + 4 | French Dictionary | LOADED +> +\endverbatim + +To unload the module, use the `u ` command. If the module from +\ref MicroServices_Example1 "Example 1" is still active, +then we should see it print out the details of the service event it receives +when our new module registers its dictionary service. Using the `CppMicroServicesExampleDriver` +commands `u` and `l` we can unload and load it at will, respectively. Each +time we load and unload our dictionary service module, we should see the details +of the associated service event printed from the module from Example 1. In +\ref MicroServices_Example3 "Example 3", we will create a client for our +dictionary service. To exit `CppMicroServicesExampleDriver`, we use the `q` command. + +\note Because our french dictionary module has a link dependency on the +dictionary service module from Example 2, this module is automatically loaded +by the operating system loader. Unloading it will only succeed if there are +no other dependent modules like our french dictionary module currently loaded. + +Next: \ref MicroServices_Example3 + +Previous: \ref MicroServices_Example2 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example3.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example3.md new file mode 100644 index 0000000000..2c225c7ecf --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example3.md @@ -0,0 +1,58 @@ +Example 3 - Dictionary Client Module {#MicroServices_Example3} +==================================== + +This example creates a module that is a client of the dictionary service +implemented in \ref MicroServices_Example2 "Example 2". In the following +source code, our module uses its module context to query for a dictionary +service. Our client module uses the first dictionary service it finds and +if none are found it simply prints a message saying so and stops. Using +a service is the same as using any C++ class. The source code for our +module is as follows in a file called `dictionaryclient2/Activator.cpp`: + +\snippet dictionaryclient/Activator.cpp Activator + +Note that we do not need to unget or release the service in the Unload() +method, because the C++ Micro Services library will automatically do so +for us. + +Since we are using the `IDictionaryService` interface defined in Example 1, +we must link our module to the `dictionaryservice` module: + +\include dictionaryclient/CMakeLists.txt + +After running the `CppMicroServicesExampleDriver` executable, and loading the event +listener module, we can use the `l dictionaryclient` command to load +our dictionary client module: + +\verbatim +CppMicroServices-debug> bin/CppMicroServicesExampleDriver +> l eventlistener +Starting to listen for service events. +> l dictionaryclient +Ex1: Service of type IDictionaryService/1.0 registered. +Enter a blank line to exit. +Enter word: +\endverbatim + +The above command loads the module and its dependencies (the `dictionaryservice` +module) in a single step. When we load the module, it will use the main thread to +prompt us for words. Enter one word at a time to check the words and enter a +blank line to stop checking words. To reload the module, we must use the `s` +command to get the module identifier number for the module and first use the +`u ` command to unload the module, then the `l ` command to re-load it. +To test the dictionary service, enter any of the words in the dictionary +(e.g., "welcome", "to", "the", "micro", "services", "tutorial") or any word not +in the dictionary. + +This example client is simple enough and, in fact, is too simple. What would +happen if the dictionary service were to unregister suddenly? Our client would +abort with a segmentation fault due to a null pointer access when trying to use +the service object. This dynamic service availability issue is a central tenent +of the service model. As a result, we must make our client more robust in dealing +with such situations. In \ref MicroServices_Example4 "Example 4", we explore a +slightly more complicated dictionary client that dynamically monitors service +availability. + +Next: \ref MicroServices_Example4 + +Previous: \ref MicroServices_Example2 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example4.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example4.md new file mode 100644 index 0000000000..a43e7dc970 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example4.md @@ -0,0 +1,66 @@ +Example 4 - Robust Dictionary Client Module {#MicroServices_Example4} +=========================================== + +In \ref MicroServices_Example3 "Example 3", we create a simple client module +for our dictionary service. The problem with that client was that it did not +monitor the dynamic availability of the dictionary service, thus an error +would occur if the dictionary service disappeared while the client was using it. +In this example we create a client for the dictionary service that monitors +the dynamic availability of the dictionary service. The result is a more robust +client. + +The functionality of the new dictionary client is essentially the same as the +old client, it reads words from standard input and checks for their existence +in the dictionary service. Our module uses its module context to register itself +as a service event listener; monitoring service events allows the module to +monitor the dynamic availability of the dictionary service. Our client uses the +first dictionary service it finds. The source code for our module is as follows +in a file called `Activator.cpp`: + +\snippet dictionaryclient2/Activator.cpp Activator + +The client listens for service events indicating the arrival or departure of +dictionary services. If a new dictionary service arrives, the module will start +using that service if and only if it currently does not have a dictionary service. +If an existing dictionary service disappears, the module will check to see if the +disappearing service is the one it is using; if it is it stops using it and tries +to query for another dictionary service, otherwise it ignores the event. + +As in Example 3, we must link our module to the `dictionaryservice` module: + +\include dictionaryclient2/CMakeLists.txt + +After running the `CppMicroServicesExampleDriver` executable, and loading the event +listener module, we can use the `l dictionaryclient2` command to load +our robust dictionary client module: + +\verbatim +CppMicroServices-debug> bin/CppMicroServicesExampleDriver +> l eventlistener +Starting to listen for service events. +> l dictionaryclient2 +Ex1: Service of type IDictionaryService/1.0 registered. +Enter a blank line to exit. +Enter word: +\endverbatim + +The above command loads the module and its dependencies (the `dictionaryservice` +module) in a single step. When we load the module, it will use the main thread to +prompt us for words. Enter one word at a time to check the words and enter a +blank line to stop checking words. To reload the module, we must use the `s` +command to get the module identifier number for the module and first use the +`u ` command to unload the module, then the `l ` command to re-load it. +To test the dictionary service, enter any of the words in the dictionary +(e.g., "welcome", "to", "the", "micro", "services", "tutorial") or any word not +in the dictionary. + +Since this client monitors the dynamic availability of the dictionary service, +it is robust in the face of sudden departures of the the dictionary service. +Further, when a dictionary service arrives, it automatically gets the service if +it needs it and continues to function. These capabilities are a little difficult +to demonstrate since we are using a simple single-threaded approach, but in a +multi-threaded or GUI-oriented application this robustness is very useful. + +Next: \ref MicroServices_Example5 + +Previous: \ref MicroServices_Example3 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example5.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example5.md new file mode 100644 index 0000000000..419fbad5bb --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example5.md @@ -0,0 +1,61 @@ +Example 5 - Service Tracker Dictionary Client Module {#MicroServices_Example5} +==================================================== + +In \ref MicroServices_Example4 "Example 4", we created a more robust client bundle +for our dictionary service. Due to the complexity of dealing with dynamic service +availability, even that client may not sufficiently address all situations. To +deal with this complexity the C++ Micro Services library provides the `ServiceTracker` +utility class. In this example we create a client for the dictionary service that +uses the `ServiceTracker` class to monitor the dynamic availability of the dictionary +service, resulting in an even more robust client. + +The functionality of the new dictionary client is essentially the same as the one +from Example 4. Our module uses its module context to create a `ServiceTracker` +instance to track the dynamic availability of the dictionary service on our behalf. +Our client uses the dictionary service returned by the `ServiceTracker`, which is +selected based on a ranking algorithm defined by the C++ Micro Services library. +The source code for our modules is as follows in a file called +`dictionaryclient3/Activator.cpp`: + +\snippet dictionaryclient3/Activator.cpp Activator + +Since this client uses the `ServiceTracker` utility class, it will automatically +monitor the dynamic availability of the dictionary service. Again, we must link +our module to the `dictionaryservice` module: + +\include dictionaryclient3/CMakeLists.txt + +After running the `CppMicroServicesExampleDriver` executable, and loading the event +listener module, we can use the `l dictionaryclient3` command to load +our robust dictionary client module: + +\verbatim +CppMicroServices-debug> bin/CppMicroServicesExampleDriver +> l eventlistener +Starting to listen for service events. +> l dictionaryclient3 +Ex1: Service of type IDictionaryService/1.0 registered. +Enter a blank line to exit. +Enter word: +\endverbatim + +The above command loads the module and its dependencies (the `dictionaryservice` +module) in a single step. When we load the module, it will use the main thread to +prompt us for words. Enter one word at a time to check the words and enter a +blank line to stop checking words. To reload the module, we must use the `s` +command to get the module identifier number for the module and first use the +`u ` command to unload the module, then the `l ` command to re-load it. +To test the dictionary service, enter any of the words in the dictionary +(e.g., "welcome", "to", "the", "micro", "services", "tutorial") or any word not +in the dictionary. + +Since this client monitors the dynamic availability of the dictionary service, +it is robust in the face of sudden departures of the the dictionary service. +Further, when a dictionary service arrives, it automatically gets the service if +it needs it and continues to function. These capabilities are a little difficult +to demonstrate since we are using a simple single-threaded approach, but in a +multi-threaded or GUI-oriented application this robustness is very useful. + +Next: \ref MicroServices_Example6 + +Previous: \ref MicroServices_Example4 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example6.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example6.md new file mode 100644 index 0000000000..66559e8931 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example6.md @@ -0,0 +1,123 @@ +Example 6 - Spell Checker Service Module {#MicroServices_Example6} +======================================== + +In this example, we complicate things further by defining a new service that +uses an arbitrary number of dictionary services to perform its function. More +precisely, we define a spell checker service which will aggregate all dictionary +services and provide another service that allows us to spell check passages +using our underlying dictionary services to verify the spelling of words. Our +module will only provide the spell checker service if there are at least two +dictionary services available. First, we will start by defining the spell checker +service interface in a file called `spellcheckservice/ISpellCheckService.h`: + +\snippet spellcheckservice/ISpellCheckService.h service + +The service interface is quite simple, with only one method that needs to be +implemented. Because we provide an empty out-of-line destructor (defined in the +file `ISpellCheckService.cpp`) we must export the service interface by using the +module specific `SPELLCHECKSERVICE_EXPORT` macro. + +In the following source code, the module needs to create a complete list of all +dictionary services; this is somewhat tricky and must be done carefully if done +manually via service event listners. Our module makes use of the `ServiceTracker` +and `ServiceTrackerCustomizer` classes to robustly react to service events related +to dictionary services. The module activator of our module now additionally implements +the `ServiceTrackerCustomizer` class to be automatically notified of arriving, departing, +or modified dictionary services. In case of a newly added dictionary service, our +`ServiceTrackerCustomizer::AddingService()` implementation checks if a spell checker +service was already registered and if not registers a new `ISpellCheckService` instance +if at lead two dictionary services are available. +If the number of dictionary services drops below two, our `ServiceTrackerCustomizer` +implementation un-registers the previously registered spell checker service instance. +These actions must be performed in a synchronized manner to avoid interference from +service events originating from different threads. The implementation of our module +activator is done in a file called `spellcheckservice/Activator.cpp`: + +\snippet spellcheckservice/Activator.cpp Activator + +Note that we do not need to unregister the service in stop() method, because the +C++ Micro Services library will automatically do so for us. The spell checker service +that we have implemented is very simple; it simply parses a given passage into words +and then loops through all available dictionary services for each word until it +determines that the word is correct. Any incorrect words are added to an error list +that will be returned to the caller. This solution is not optimal and is only intended +for educational purposes. + +\note In this example, the service interface and implementation are both +contained in one module which exports the interface class. However, service +implementations almost never need to be exported and in many use cases +it is beneficial to provide the service interface and its implementation(s) +in separate modules. In such a scenario, clients of a service will only +have a link-time dependency on the shared library providing the service interface +(because of the out-of-line destructor) but not on any modules containing +service implementations. This often leads to modules which do not export +any symbols at all and hence need to be loaded into the running process +manually or by using the \ref MicroServices_AutoLoading "auto-loading mechanism". + +\note Due to the link dependency of our module to the module containing the +dictionary service interface as well as a default implementation for it, there +might be at least one dictionary service registered when our module is +loaded, depending on your linker settings (e.g. on Windows, the linker usually +by default optimizes the link dependency away since our module does not actually +use any symbols from the dictionaryservice module. On Linux however, the link +dependency is kept by default.) To observe the dynamic registration and +un-registration of our spell checker service, we require the availability of +at least two dictionary services. + +For an introduction how to compile our source code, see \ref MicroServices_Example1. + +After running the `CppMicroServicesExampleDriver` program we should make sure that the +module from Example 1 is active. We can use the `s` shell command to get +a list of all modules, their state, and their module identifier number. +If the Example 1 module is not active, we should load the module using the +load command and the module's identifier number or name that is displayed +by the `s` command. Now we can load the spell checker service module by +entering the `l spellcheckservice` command which will also trigger the loading +of the dictionaryservice module containing the english dictionary: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> l eventlistener +Starting to listen for service events. +> l spellcheckservice +Ex1: Service of type IDictionaryService/1.0 registered. +> s +Id | Name | Status +----------------------------------- + - | dictionaryclient | - + - | dictionaryclient2 | - + - | dictionaryclient3 | - + - | frenchdictionary | - + - | spellcheckclient | - + 1 | CppMicroServices | LOADED + 2 | Event Listener | LOADED + 3 | Dictionary Service | LOADED + 4 | Spell Check Service | LOADED +> +\endverbatim + +To trigger the registration of the spell checker service from our module, we +load the frenchdictionary using the `l frenchdictionary` command. If the module from +\ref MicroServices_Example1 "Example 1" is still active, +then we should see it print out the details of the service event it receives +when our new module registers its spell checker service: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> l frenchdictionary +Ex1: Service of type IDictionaryService/1.0 registered. +Ex1: Service of type ISpellCheckService/1.0 registered. +> +\endverbatim + +We can experiment with our spell checker service's dynamic availability by stopping +the french dictionary service; when the service is stopped, +the eventlistener module will print that our module is no longer offering its +spell checker service. Likewise, when the french dictionary service comes back, so will +our spell checker service. We create a client for our spell checker service in +\ref MicroServices_Example7 "Example 7". To exit the `CppMicroServicesExampleDriver` program, we +use the `q` command. + +Next: \ref MicroServices_Example7 + +Previous: \ref MicroServices_Example5 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example7.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example7.md new file mode 100644 index 0000000000..8bcdc5e997 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example7.md @@ -0,0 +1,73 @@ +Example 7 - Spell Checker Client Module {#MicroServices_Example7} +======================================= + +In this example we create a client for the spell checker service we implemented +in \ref MicroServices_Example6 "Example 6". This client monitors the dynamic +availability of the spell checker service using the Service Tracker and is very +similar in structure to the dictionary client we implemented in +\ref MicroServices_Example5 "Example 5". The functionality of the spell checker +client reads passages from standard input and spell checks them using the spell +checker service. Our module uses its module context to create a `ServiceTracker` +object to monitor spell checker services. The source code for our module is as +follows in a file called `spellcheckclient/Activator.cpp`: + +\snippet spellcheckclient/Activator.cpp Activator + +After running the `CppMicroServicesExampleDriver` program use the `s` command to make sure that +only the modules from Example 2, Example 2b, and Example 6 are loaded; use the +load (`l`) and un-load (`u`) commands as appropriate to load and un-load the +various tutorial modules, respectively. Now we can load our spell checker client +module by entering `l spellcheckclient`: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> l +Starting to listen for service events. +> l spellcheckservice +Ex1: Service of type IDictionaryService/1.0 registered. +> s +Id | Name | Status +----------------------------------- + - | dictionaryclient | - + - | dictionaryclient2 | - + - | dictionaryclient3 | - + - | frenchdictionary | - + - | spellcheckclient | - + 1 | CppMicroServices | LOADED + 2 | Event Listener | LOADED + 3 | Dictionary Service | LOADED + 4 | Spell Check Service | LOADED +> +\endverbatim + +To trigger the registration of the spell checker service from our module, we +load the frenchdictionary using the `l frenchdictionary` command. If the module from +\ref MicroServices_Example1 "Example 1" is still active, +then we should see it print out the details of the service event it receives +when our new module registers its spell checker service: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> l spellcheckservice +> l frenchdictionary +> l spellcheckclient +Enter a blank line to exit. +Enter passage: +\endverbatim + +When we start the module, it will use the main thread to prompt us for passages; a +passage is a collection or words separate by spaces, commas, periods, exclamation +points, question marks, colons, or semi-colons. Enter a passage and press the enter +key to spell check the passage or enter a blank line to stop spell checking passages. +To restart the module, we must use the command `s` command to get the module identifier +number for the module and first use the `u` command to un-load the module, then the +`l` command to re-load it. + +Since this client uses the Service Tracker to monitor the dynamic availability of the +spell checker service, it is robust in the scenario where the spell checker service +suddenly departs. Further, when a spell checker service arrives, it automatically gets +the service if it needs it and continues to function. These capabilities are a little +difficult to demonstrate since we are using a simple single-threaded approach, but in +a multi-threaded or GUI-oriented application this robustness is very useful. + +Previous: \ref MicroServices_Example6 diff --git a/Core/Code/CppMicroServices/documentation/doxygen/footer.html b/Core/CppMicroServices/documentation/doxygen/footer.html similarity index 64% rename from Core/Code/CppMicroServices/documentation/doxygen/footer.html rename to Core/CppMicroServices/documentation/doxygen/footer.html index 38c8204a29..ea6b6dac83 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/footer.html +++ b/Core/CppMicroServices/documentation/doxygen/footer.html @@ -1,9 +1,4 @@ - - -
- - + diff --git a/Core/CppMicroServices/documentation/doxygen/header.html b/Core/CppMicroServices/documentation/doxygen/header.html new file mode 100644 index 0000000000..cc5afab151 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/header.html @@ -0,0 +1,23 @@ +--- +layout: default +title: $title +--- + + + + $projectname: $title + $title + + + + + $treeview + $search + $mathjax + + + $extrastylesheet + + + +
diff --git a/Core/CppMicroServices/documentation/doxygen/standalone/BuildInstructions.md b/Core/CppMicroServices/documentation/doxygen/standalone/BuildInstructions.md new file mode 100644 index 0000000000..8319e6bd7a --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/standalone/BuildInstructions.md @@ -0,0 +1,59 @@ +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) + - GCC 4.7 (Ubuntu 12.10) + - Visual Studio 2008, 2010, and 2012 + - Clang 3.0 (Ubuntu 12.10 and MacOS X 10.6) + + +Prerequisites +------------- + +- [CMake][cmake] 2.8 (Visual Studio 2010 and 2012 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 + +- **CMAKE_INSTALL_PREFIX** + The installation path. +- **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 (advanced)** + 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. + +[cmake]: http://www.cmake.org diff --git a/Core/CppMicroServices/documentation/doxygen/standalone/MicroServices_GettingStarted.md b/Core/CppMicroServices/documentation/doxygen/standalone/MicroServices_GettingStarted.md new file mode 100644 index 0000000000..fec5a1105c --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/standalone/MicroServices_GettingStarted.md @@ -0,0 +1,49 @@ +Getting Started {#MicroServices_GettingStarted} +=============== + +Projects which want to make use of the capabilities provided by the C++ Micro Services +library need to set-up the correct include paths and link dependencies. Further, each +executable or shared library which needs a ModuleContext instance must contain specific +initialization code. + +The C++ Micro Services library provides \ref MicroServicesCMake "CMake utility functions" +for CMake based projects but there are no restrictions on the type of build system used +for a project. + +CMake based projects +-------------------- + +To easily set-up include paths and linker dependencies, use the common `find_package` +mechanism provided by CMake: + +\dontinclude examples/CMakeLists.txt +\skip project +\until include_directories + +The CMake code above sets up a basic project (called CppMicroServicesExamples) and tries +to find the CppMicroServices package and subsequently to set the necessary include +directories. Building a shared library might then look like this: + +\dontinclude examples/dictionaryservice/CMakeLists.txt +\until target_link + +The call to `#usFunctionGenerateModuleInit` generates the proper module initialization +code and provides access to the module specific ModuleContext instance. + +Makefile based projects +----------------------- + +The following Makefile is located at examples/makefile/Makefile and demonstrates a minimal +build script: + +\include makefile/Makefile + +The variable `CppMicroServices_ROOT` is an environment variable and must be set to the +CppMicroServices installation directory prior to invoking `make`. The module initialization +code for the `libmodule.so` shared library is generated by using the `#US_INITIALIZE_MODULE` +pre-processor macro at the end of the `module.cpp` source file (any source file compiled +into the module would do): + +\dontinclude makefile/module.cpp +\skip usModuleInitialization +\until US_INITIALIZE_MODULE diff --git a/Core/CppMicroServices/documentation/snippets/CMakeLists.txt b/Core/CppMicroServices/documentation/snippets/CMakeLists.txt new file mode 100644 index 0000000000..5540734bb9 --- /dev/null +++ b/Core/CppMicroServices/documentation/snippets/CMakeLists.txt @@ -0,0 +1,4 @@ + +include_directories(${US_INCLUDE_DIRS}) + +usFunctionCompileSnippets("${CMAKE_CURRENT_SOURCE_DIR}") diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-activator/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-activator/main.cpp similarity index 100% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-activator/main.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-activator/main.cpp diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp similarity index 90% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp index b46013fe89..a793f3b343 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp @@ -1,28 +1,28 @@ #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") +US_INITIALIZE_MODULE("My Module", "mylibname") //! [InitializeModule] int main(int /*argc*/, char* /*argv*/[]) { RetrieveModuleContext(); return 0; } diff --git a/Core/CppMicroServices/documentation/snippets/uServices-registration/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-registration/main.cpp new file mode 100644 index 0000000000..be9666e635 --- /dev/null +++ b/Core/CppMicroServices/documentation/snippets/uServices-registration/main.cpp @@ -0,0 +1,119 @@ +#include +#include +#include +#include + +US_USE_NAMESPACE + + +struct InterfaceA { virtual ~InterfaceA() {} }; +struct InterfaceB { virtual ~InterfaceB() {} }; +struct InterfaceC { virtual ~InterfaceC() {} }; + +US_DECLARE_SERVICE_INTERFACE(InterfaceA, "org.cppmicroservices.snippet.InterfaceA") +US_DECLARE_SERVICE_INTERFACE(InterfaceB, "org.cppmicroservices.snippet.InterfaceB") +US_DECLARE_SERVICE_INTERFACE(InterfaceC, "org.cppmicroservices.snippet.InterfaceC") + +//! [1-1] +class MyService : public InterfaceA +{}; +//! [1-1] + +//! [2-1] +class MyService2 : public InterfaceA, public InterfaceB +{}; +//! [2-1] + +class MyActivator : public ModuleActivator +{ + +public: + + void Load(ModuleContext* context) + { + Register1(context); + Register2(context); + RegisterFactory1(context); + RegisterFactory2(context); + } + + void Register1(ModuleContext* context) + { +//! [1-2] +MyService* myService = new MyService; +context->RegisterService(myService); +//! [1-2] + } + + void Register2(ModuleContext* context) + { +//! [2-2] +MyService2* myService = new MyService2; +context->RegisterService(myService); +//! [2-2] + } + + void RegisterFactory1(ModuleContext* context) + { +//! [f1] +class MyServiceFactory : public ServiceFactory +{ + virtual InterfaceMap GetService(Module* /*module*/, const ServiceRegistrationBase& /*registration*/) + { + MyService* myService = new MyService; + return MakeInterfaceMap(myService); + } + + virtual void UngetService(Module* /*module*/, const ServiceRegistrationBase& /*registration*/, + const InterfaceMap& service) + { + delete ExtractInterface(service); + } +}; + +MyServiceFactory* myServiceFactory = new MyServiceFactory; +context->RegisterService(myServiceFactory); +//! [f1] + } + + void RegisterFactory2(ModuleContext* context) + { +//! [f2] +class MyServiceFactory : public ServiceFactory +{ + virtual InterfaceMap GetService(Module* /*module*/, const ServiceRegistrationBase& /*registration*/) + { + MyService2* myService = new MyService2; + return MakeInterfaceMap(myService); + } + + virtual void UngetService(Module* /*module*/, const ServiceRegistrationBase& /*registration*/, + const InterfaceMap& service) + { + delete ExtractInterface(service); + } +}; + +MyServiceFactory* myServiceFactory = new MyServiceFactory; +context->RegisterService(static_cast(myServiceFactory)); +//! [f2] +// In the RegisterService call above, we could remove the static_cast because local types +// are not considered in template argument type deduction and hence the compiler choose +// the correct RegisterService(ServiceFactory*) overload. However, local types are +// usually the exception and using a non-local type for the service factory would make the +// compiler choose RegisterService(Impl*) instead, unless we use the static_cast. + } + + + void Unload(ModuleContext* /*context*/) + { /* cleanup */ } + +}; + +US_EXPORT_MODULE_ACTIVATOR(mylibname, MyActivator) + +int main(int /*argc*/, char* /*argv*/[]) +{ + MyActivator ma; + return 0; +} diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-resources/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-resources/main.cpp similarity index 95% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-resources/main.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-resources/main.cpp index 78674294d6..474c344374 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-resources/main.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-resources/main.cpp @@ -1,88 +1,86 @@ #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"); + std::string componentPath = module->GetProperty("service-component").ToString(); 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 +US_INITIALIZE_EXECUTABLE("uServices-snippet-resources") diff --git a/Core/CppMicroServices/documentation/snippets/uServices-servicetracker/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-servicetracker/main.cpp new file mode 100644 index 0000000000..0c1bc68bef --- /dev/null +++ b/Core/CppMicroServices/documentation/snippets/uServices-servicetracker/main.cpp @@ -0,0 +1,110 @@ +#include +#include + +US_USE_NAMESPACE + +struct IFooService {}; + +US_DECLARE_SERVICE_INTERFACE(IFooService, "org.cppmicroservices.snippets.IFooService") + +///! [tt] +struct MyTrackedClass { /* ... */ }; +//! [tt] + +//! [ttt] +struct MyTrackedClassTraits : public TrackedTypeTraitsBase +{ + static bool IsValid(const TrackedType&) + { + // Dummy implementation + return true; + } + + static void Dispose(TrackedType&) + {} + + static TrackedType DefaultValue() + { + return TrackedType(); + } +}; +//! [ttt] + +//! [customizer] +struct MyTrackingCustomizer : public ServiceTrackerCustomizer +{ + virtual MyTrackedClass AddingService(const ServiceReferenceT&) + { + return MyTrackedClass(); + } + + virtual void ModifiedService(const ServiceReferenceT&, MyTrackedClass) + { + } + + virtual void RemovedService(const ServiceReferenceT&, MyTrackedClass) + { + } +}; +//! [customizer] + +struct MyTrackingPointerCustomizer : public ServiceTrackerCustomizer +{ + virtual MyTrackedClass* AddingService(const ServiceReferenceT&) + { + return new MyTrackedClass(); + } + + virtual void ModifiedService(const ServiceReferenceT&, MyTrackedClass*) + { + } + + virtual void RemovedService(const ServiceReferenceT&, MyTrackedClass*) + { + } +}; + +// For compilation test purposes only +struct MyTrackingCustomizerVoid : public ServiceTrackerCustomizer +{ + virtual MyTrackedClass AddingService(const ServiceReferenceT&) + { + return MyTrackedClass(); + } + + virtual void ModifiedService(const ServiceReferenceT&, MyTrackedClass) + { + } + + virtual void RemovedService(const ServiceReferenceT&, MyTrackedClass) + { + } +}; + +int main(int /*argc*/, char* /*argv*/[]) +{ + { +//! [tracker] +MyTrackingCustomizer myCustomizer; +ServiceTracker tracker(GetModuleContext(), &myCustomizer); +//! [tracker] + } + + { +//! [tracker2] +MyTrackingPointerCustomizer myCustomizer; +ServiceTracker > tracker(GetModuleContext(), &myCustomizer); +//! [tracker2] + } + + // For compilation test purposes only + MyTrackingCustomizerVoid myCustomizer2; + ServiceTracker tracker2(GetModuleContext(), &myCustomizer2); + ServiceTracker > tracker3(GetModuleContext()); + + return 0; +} + +#include + +US_INITIALIZE_EXECUTABLE("uServices-modulecontext") diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp b/Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp similarity index 94% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp index 7b7e777626..9380cb316d 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp @@ -1,80 +1,80 @@ #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 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); + 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/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h similarity index 94% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h rename to Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h index a8aa153e56..62dbf89270 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h +++ b/Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h @@ -1,66 +1,64 @@ #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 +class SingletonOneService { 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/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp similarity index 93% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp index 84aeab43d5..db18f6ae01 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp @@ -1,64 +1,64 @@ #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 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); + 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/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h similarity index 91% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h rename to Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h index ab5444a2cc..9eb8e2b36b 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h +++ b/Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h @@ -1,49 +1,48 @@ #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 +class SingletonTwoService { 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/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake b/Core/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake new file mode 100644 index 0000000000..7de7f5c5ad --- /dev/null +++ b/Core/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake @@ -0,0 +1,10 @@ + +set(snippet_src_files + main.cpp + SingletonOne.cpp + SingletonTwo.cpp +) + +usFunctionGenerateExecutableInit(snippet_src_files + IDENTIFIER "uServices_singleton" + ) diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp similarity index 93% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp index 6d44cdab86..9980ee1f53 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp @@ -1,69 +1,69 @@ #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; + 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/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp similarity index 94% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp index f63af3272a..2984c93702 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp @@ -1,40 +1,39 @@ /*============================================================================= 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") - +US_INITIALIZE_MODULE("My Static Module", "MyStaticModule") diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/files.cmake b/Core/CppMicroServices/documentation/snippets/uServices-staticmodules/files.cmake similarity index 100% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/files.cmake rename to Core/CppMicroServices/documentation/snippets/uServices-staticmodules/files.cmake diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp similarity index 91% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp index 13364d4d34..e78d3a64c4 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp @@ -1,36 +1,34 @@ #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 +US_INITIALIZE_EXECUTABLE("MyExecutable") //! [InitializeExecutable] diff --git a/Core/CppMicroServices/examples/CMakeLists.txt b/Core/CppMicroServices/examples/CMakeLists.txt new file mode 100644 index 0000000000..745bd869c3 --- /dev/null +++ b/Core/CppMicroServices/examples/CMakeLists.txt @@ -0,0 +1,137 @@ +project(CppMicroServicesExamples) + +cmake_minimum_required(VERSION 2.8) + +find_package(CppMicroServices NO_MODULE REQUIRED) + +include_directories(${CppMicroServices_INCLUDE_DIRS}) + +#----------------------------------------------------------------------------- +# Set C/CXX flags +#----------------------------------------------------------------------------- + +if(${CMAKE_PROJECT_NAME} STREQUAL ${PROJECT_NAME}) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CppMicroServices_CXX_FLAGS}") + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${CppMicroServices_CXX_FLAGS_RELEASE}") + set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${CppMicroServices_CXX_FLAGS_DEBUG}") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CppMicroServices_C_FLAGS}") + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} ${CppMicroServices_C_FLAGS_RELEASE}") + set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${CppMicroServices_C_FLAGS_DEBUG}") +endif() + +#----------------------------------------------------------------------------- +# Init output directories +#----------------------------------------------------------------------------- + +set(CppMicroServicesExamples_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") +set(CppMicroServicesExamples_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") +set(CppMicroServicesExamples_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") + +foreach(_type ARCHIVE LIBRARY RUNTIME) + if(NOT CMAKE_${_type}_OUTPUT_DIRECTORY) + set(CMAKE_${_type}_OUTPUT_DIRECTORY ${CppMicroServicesExamples_${_type}_OUTPUT_DIRECTORY}) + endif() +endforeach() + + +function(CreateExample _name) + add_library(Example-${_name} SHARED ${ARGN}) + if(${_name}_DEPENDS) + foreach(_dep ${${_name}_DEPENDS}) + include_directories(${CppMicroServicesExamples_SOURCE_DIR}/${_dep}) + target_link_libraries(Example-${_name} Example-${_dep}) + endforeach() + endif() + target_link_libraries(Example-${_name} ${CppMicroServices_LIBRARIES}) + set_target_properties(Example-${_name} PROPERTIES + LABELS Examples + OUTPUT_NAME ${_name} + ) +endfunction() + +add_subdirectory(eventlistener) +add_subdirectory(dictionaryservice) +add_subdirectory(frenchdictionary) +add_subdirectory(dictionaryclient) +add_subdirectory(dictionaryclient2) +add_subdirectory(dictionaryclient3) +add_subdirectory(spellcheckservice) +add_subdirectory(spellcheckclient) +add_subdirectory(driver) + +#----------------------------------------------------------------------------- +# Test if examples compile against an install tree and if the +# Makefile example compiles +#----------------------------------------------------------------------------- + +if(US_BUILD_TESTING) + enable_testing() + + set(_example_tests ) + + set(_install_dir "${CppMicroServices_BINARY_DIR}/install_test/${CMAKE_INSTALL_PREFIX}") + + add_test(NAME usInstallCleanTest + COMMAND ${CMAKE_COMMAND} -E remove_directory "${_install_dir}") + + add_test(NAME usInstallTest + WORKING_DIRECTORY ${CppMicroServices_BINARY_DIR} + COMMAND ${CMAKE_COMMAND} --build ${CppMicroServices_BINARY_DIR} --target install) + set_tests_properties(usInstallTest PROPERTIES + ENVIRONMENT "DESTDIR=${CppMicroServices_BINARY_DIR}/install_test" + DEPENDS usInstallCleanTest) + + set(_examples_binary_dir "${CppMicroServices_BINARY_DIR}/examples_build") + + add_test(NAME usExamplesCleanTest + COMMAND ${CMAKE_COMMAND} -E remove_directory "${_examples_binary_dir}") + + add_test(NAME usExamplesCreateDirTest + COMMAND ${CMAKE_COMMAND} -E make_directory "${_examples_binary_dir}") + set_tests_properties(usExamplesCreateDirTest PROPERTIES + DEPENDS usExamplesCleanTest) + + add_test(NAME usExamplesConfigureTest + WORKING_DIRECTORY ${_examples_binary_dir} + COMMAND ${CMAKE_COMMAND} + -G ${CMAKE_GENERATOR} + -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} + "-DCppMicroServices_DIR:PATH=${_install_dir}/${CONFIG_CMAKE_DIR}" + "${CMAKE_CURRENT_LIST_DIR}") + set_tests_properties(usExamplesConfigureTest PROPERTIES + DEPENDS "usInstallTest;usExamplesCreateDirTest") + + add_test(NAME usExamplesBuildTest + WORKING_DIRECTORY ${_examples_binary_dir} + COMMAND ${CMAKE_COMMAND} --build .) + set_tests_properties(usExamplesBuildTest PROPERTIES + DEPENDS usExamplesConfigureTest) + + list(APPEND _example_tests usInstallCleanTest usInstallTest usExamplesCleanTest + usExamplesCreateDirTest usExamplesConfigureTest usExamplesBuildTest) + + # The makefile is Linux specific, so only try to build the Makefile example + # if we are on a proper system + if(UNIX AND NOT APPLE) + find_program(MAKE_COMMAND NAMES make gmake) + find_program(CXX_COMMAND NAMES g++) + mark_as_advanced(MAKE_COMMAND CXX_COMMAND) + if(MAKE_COMMAND AND CXX_COMMAND) + add_test(NAME usMakefileExampleCleanTest + WORKING_DIRECTORY ${CppMicroServices_SOURCE_DIR}/examples/makefile + COMMAND ${MAKE_COMMAND} clean) + add_test(NAME usMakefileExampleTest + WORKING_DIRECTORY ${CppMicroServices_SOURCE_DIR}/examples/makefile + COMMAND ${MAKE_COMMAND}) + set_tests_properties(usMakefileExampleTest PROPERTIES + DEPENDS "usMakefileExampleCleanTest;usInstallTest" + ENVIRONMENT "CppMicroServices_ROOT=${CppMicroServices_BINARY_DIR}/install_test${CMAKE_INSTALL_PREFIX};CppMicroServices_CXX_FLAGS=${CppMicroServices_CXX_FLAGS}") + list(APPEND _example_tests usMakefileExampleCleanTest usMakefileExampleTest) + endif() + endif() + + if(US_TEST_LABELS) + set_tests_properties(${_example_tests} PROPERTIES LABELS "${US_TEST_LABELS}") + endif() + +endif() diff --git a/Core/CppMicroServices/examples/dictionaryclient/Activator.cpp b/Core/CppMicroServices/examples/dictionaryclient/Activator.cpp new file mode 100644 index 0000000000..fc3d47f37d --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryclient/Activator.cpp @@ -0,0 +1,117 @@ +/*============================================================================= + + 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. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" + +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module activator that uses a dictionary service to check for + * the proper spelling of a word by check for its existence in the dictionary. + * This modules uses the first service that it finds and does not monitor the + * dynamic availability of the service (i.e., it does not listen for the arrival + * or departure of dictionary services). When loading this module, the thread + * calling the Load() method is used to read words from standard input. You can + * stop checking words by entering an empty line, but to start checking words + * again you must unload and then load the module again. + */ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +public: + + /** + * Implements ModuleActivator::Load(). Queries for all available dictionary + * services. If none are found it simply prints a message and returns, + * otherwise it reads words from standard input and checks for their + * existence from the first dictionary that it finds. + * + * \note It is very bad practice to use the calling thread to perform a lengthy + * process like this; this is only done for the purpose of the tutorial. + * + * @param context the module context for this module. + */ + void Load(ModuleContext *context) + { + // Query for all service references matching any language. + std::vector > refs = + context->GetServiceReferences("(Language=*)"); + + if (!refs.empty()) + { + std::cout << "Enter a blank line to exit." << std::endl; + + // Loop endlessly until the user enters a blank line + while (std::cin) + { + // Ask the user to enter a word. + std::cout << "Enter word: "; + + std::string word; + std::getline(std::cin, word); + + // If the user entered a blank line, then + // exit the loop. + if (word.empty()) + { + break; + } + + // First, get a dictionary service and then check + // if the word is correct. + IDictionaryService* dictionary = context->GetService(refs.front()); + if ( dictionary->CheckWord( word ) ) + { + std::cout << "Correct." << std::endl; + } + else + { + std::cout << "Incorrect." << std::endl; + } + + // Unget the dictionary service. + context->UngetService(refs.front()); + } + } + else + { + std::cout << "Couldn't find any dictionary service..." << std::endl; + } + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unget any used services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + // NOTE: The service is automatically released. + } + +}; + +US_EXPORT_MODULE_ACTIVATOR(dictionaryclient, Activator) +//![Activator] diff --git a/Core/CppMicroServices/examples/dictionaryclient/CMakeLists.txt b/Core/CppMicroServices/examples/dictionaryclient/CMakeLists.txt new file mode 100644 index 0000000000..bd610a3686 --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryclient/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Dictionary Client" + LIBRARY_NAME "dictionaryclient") + +set(dictionaryclient_DEPENDS dictionaryservice) +CreateExample(dictionaryclient ${_srcs}) diff --git a/Core/CppMicroServices/examples/dictionaryclient2/Activator.cpp b/Core/CppMicroServices/examples/dictionaryclient2/Activator.cpp new file mode 100644 index 0000000000..28d2e14276 --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryclient2/Activator.cpp @@ -0,0 +1,214 @@ +/*============================================================================= + + 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. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" + +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module activator that uses a dictionary service to check for + * the proper spelling of a word by checking for its existence in the + * dictionary. This module is more complex than the module in Example 3 because + * it monitors the dynamic availability of the dictionary services. In other + * words, if the service it is using departs, then it stops using it gracefully, + * or if it needs a service and one arrives, then it starts using it + * automatically. As before, the module uses the first service that it finds and + * uses the calling thread of the Load() method to read words from standard + * input. You can stop checking words by entering an empty line, but to start + * checking words again you must unload and then load the module again. + */ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +public: + + Activator() + : m_context(NULL) + , m_dictionary(NULL) + {} + + /** + * Implements ModuleActivator::Load(). Adds itself as a listener for service + * events, then queries for available dictionary services. If any + * dictionaries are found it gets a reference to the first one available and + * then starts its "word checking loop". If no dictionaries are found, then + * it just goes directly into its "word checking loop", but it will not be + * able to check any words until a dictionary service arrives; any arriving + * dictionary service will be automatically used by the client if a + * dictionary is not already in use. Once it has dictionary, it reads words + * from standard input and checks for their existence in the dictionary that + * it is using. + * + * \note It is very bad practice to use the calling thread to perform a + * lengthy process like this; this is only done for the purpose of + * the tutorial. + * + * @param context the module context for this module. + */ + void Load(ModuleContext *context) + { + m_context = context; + + { + // Use your favorite thread library to synchronize member + // variable access within this scope while registering + // the service listener and performing our initial + // dictionary service lookup since we + // don't want to receive service events when looking up the + // dictionary service, if one exists. + // MutexLocker lock(&m_mutex); + + // Listen for events pertaining to dictionary services. + m_context->AddServiceListener(this, &Activator::ServiceChanged, + std::string("(&(") + ServiceConstants::OBJECTCLASS() + "=" + + us_service_interface_iid() + ")" + "(Language=*))"); + + // Query for any service references matching any language. + std::vector > refs = + context->GetServiceReferences("(Language=*)"); + + // If we found any dictionary services, then just get + // a reference to the first one so we can use it. + if (!refs.empty()) + { + m_ref = refs.front(); + m_dictionary = m_context->GetService(m_ref); + } + } + + std::cout << "Enter a blank line to exit." << std::endl; + + // Loop endlessly until the user enters a blank line + while (std::cin) + { + // Ask the user to enter a word. + std::cout << "Enter word: "; + + std::string word; + std::getline(std::cin, word); + + // If the user entered a blank line, then + // exit the loop. + if (word.empty()) + { + break; + } + // If there is no dictionary, then say so. + else if (m_dictionary == NULL) + { + std::cout << "No dictionary available." << std::endl; + } + // Otherwise print whether the word is correct or not. + else if (m_dictionary->CheckWord( word )) + { + std::cout << "Correct." << std::endl; + } + else + { + std::cout << "Incorrect." << std::endl; + } + } + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unget any used services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + // NOTE: The service is automatically released. + } + + /** + * Implements ServiceListener.serviceChanged(). Checks to see if the service + * we are using is leaving or tries to get a service if we need one. + * + * @param event the fired service event. + */ + void ServiceChanged(const ServiceEvent event) + { + // Use your favorite thread library to synchronize this + // method with the Load() method. + // MutexLocker lock(&m_mutex); + + // If a dictionary service was registered, see if we + // need one. If so, get a reference to it. + if (event.GetType() == ServiceEvent::REGISTERED) + { + if (!m_ref) + { + // Get a reference to the service object. + m_ref = event.GetServiceReference(); + m_dictionary = m_context->GetService(m_ref); + } + } + // If a dictionary service was unregistered, see if it + // was the one we were using. If so, unget the service + // and try to query to get another one. + else if (event.GetType() == ServiceEvent::UNREGISTERING) + { + if (event.GetServiceReference() == m_ref) + { + // Unget service object and null references. + m_context->UngetService(m_ref); + m_ref = 0; + m_dictionary = NULL; + + // Query to see if we can get another service. + std::vector > refs; + try + { + refs = m_context->GetServiceReferences("(Language=*)"); + } + catch (const std::invalid_argument& e) + { + std::cout << e.what() << std::endl; + } + + if (!refs.empty()) + { + // Get a reference to the first service object. + m_ref = refs.front(); + m_dictionary = m_context->GetService(m_ref); + } + } + } + } + +private: + + // Module context + ModuleContext* m_context; + + // The service reference being used + ServiceReference m_ref; + + // The service object being used + IDictionaryService* m_dictionary; +}; + +US_EXPORT_MODULE_ACTIVATOR(dictionaryclient2, Activator) +//![Activator] diff --git a/Core/CppMicroServices/examples/dictionaryclient2/CMakeLists.txt b/Core/CppMicroServices/examples/dictionaryclient2/CMakeLists.txt new file mode 100644 index 0000000000..7e7524a088 --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryclient2/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Dictionary Client 2" + LIBRARY_NAME "dictionaryclient2") + +set(dictionaryclient2_DEPENDS dictionaryservice) +CreateExample(dictionaryclient2 ${_srcs}) diff --git a/Core/CppMicroServices/examples/dictionaryclient3/Activator.cpp b/Core/CppMicroServices/examples/dictionaryclient3/Activator.cpp new file mode 100644 index 0000000000..a97524435b --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryclient3/Activator.cpp @@ -0,0 +1,142 @@ +/*============================================================================= + + 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. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" + +#include +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module activator that uses a dictionary + * service to check for the proper spelling of a word by + * checking for its existence in the dictionary. This module + * uses a service tracker to dynamically monitor the availability + * of a dictionary service, instead of providing a custom service + * listener as in Example 4. The module uses the service returned + * by the service tracker, which is selected based on a ranking + * algorithm defined by the C++ Micro Services library. + * Again, the calling thread of the Load() method is used to read + * words from standard input, checking its existence in the dictionary. + * You can stop checking words by entering an empty line, but + * to start checking words again you must unload and then load + * the module again. + */ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +public: + + Activator() + : m_context(NULL) + , m_tracker(NULL) + {} + + /** + * Implements ModuleActivator::Load(). Creates a service + * tracker to monitor dictionary services and starts its "word + * checking loop". It will not be able to check any words until + * the service tracker finds a dictionary service; any discovered + * dictionary service will be automatically used by the client. + * It reads words from standard input and checks for their + * existence in the discovered dictionary. + * + * \note It is very bad practice to use the calling thread to perform a + * lengthy process like this; this is only done for the purpose of + * the tutorial. + * + * @param context the module context for this module. + */ + void Load(ModuleContext *context) + { + m_context = context; + + // Create a service tracker to monitor dictionary services. + m_tracker = new ServiceTracker( + m_context, LDAPFilter(std::string("(&(") + ServiceConstants::OBJECTCLASS() + "=" + + us_service_interface_iid() + ")" + + "(Language=*))") + ); + m_tracker->Open(); + + std::cout << "Enter a blank line to exit." << std::endl; + + // Loop endlessly until the user enters a blank line + while (std::cin) + { + // Ask the user to enter a word. + std::cout << "Enter word: "; + + std::string word; + std::getline(std::cin, word); + + // Get the selected dictionary, if available. + IDictionaryService* dictionary = m_tracker->GetService(); + + // If the user entered a blank line, then + // exit the loop. + if (word.empty()) + { + break; + } + // If there is no dictionary, then say so. + else if (dictionary == NULL) + { + std::cout << "No dictionary available." << std::endl; + } + // Otherwise print whether the word is correct or not. + else if (dictionary->CheckWord(word)) + { + std::cout << "Correct." << std::endl; + } + else + { + std::cout << "Incorrect." << std::endl; + } + } + + // This automatically closes the tracker + delete m_tracker; + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unget any used services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + } + +private: + + // Module context + ModuleContext* m_context; + + // The service tracker + ServiceTracker* m_tracker; +}; + +US_EXPORT_MODULE_ACTIVATOR(dictionaryclient3, Activator) +//![Activator] diff --git a/Core/CppMicroServices/examples/dictionaryclient3/CMakeLists.txt b/Core/CppMicroServices/examples/dictionaryclient3/CMakeLists.txt new file mode 100644 index 0000000000..44984fbd6e --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryclient3/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Dictionary Client 3" + LIBRARY_NAME "dictionaryclient3") + +set(dictionaryclient3_DEPENDS dictionaryservice) +CreateExample(dictionaryclient3 ${_srcs}) diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp b/Core/CppMicroServices/examples/dictionaryservice/Activator.cpp similarity index 63% copy from Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp copy to Core/CppMicroServices/examples/dictionaryservice/Activator.cpp index bd714f6d54..a7289f7a42 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp +++ b/Core/CppMicroServices/examples/dictionaryservice/Activator.cpp @@ -1,121 +1,116 @@ +/*============================================================================= + + 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. + +=============================================================================*/ //! [Activator] -#include "DictionaryService.h" +#include "IDictionaryService.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 +class US_ABI_LOCAL Activator : public ModuleActivator { private: /** * A private inner class that implements a dictionary service; - * see DictionaryService for details of the service. + * see IDictionaryService for details of the service. */ - class DictionaryImpl : public US_BASECLASS_NAME, public DictionaryService + class DictionaryImpl : public IDictionaryService { // 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 + * Implements IDictionaryService::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) + 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); + 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) +US_EXPORT_MODULE_ACTIVATOR(dictionaryservice, Activator) //![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/CppMicroServices/examples/dictionaryservice/CMakeLists.txt b/Core/CppMicroServices/examples/dictionaryservice/CMakeLists.txt new file mode 100644 index 0000000000..ae21e3b14c --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryservice/CMakeLists.txt @@ -0,0 +1,26 @@ +# The library name for the module +set(_lib_name dictionaryservice) + +# A list of source code files +set(_srcs + Activator.cpp + IDictionaryService.cpp +) + +# Generate module initialization code +usFunctionGenerateModuleInit(_srcs + NAME "Dictionary Service" + LIBRARY_NAME ${_lib_name}) + +# Create the library +add_library(Example-${_lib_name} SHARED ${_srcs}) + +# Link the CppMicroServices library +target_link_libraries(Example-${_lib_name} ${CppMicroServices_LIBRARIES}) + +set_target_properties(Example-${_lib_name} PROPERTIES + LABELS Examples + OUTPUT_NAME ${_lib_name} +) + +#CreateExample(dictionaryservice ${_srcs}) diff --git a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp b/Core/CppMicroServices/examples/dictionaryservice/IDictionaryService.cpp similarity index 90% copy from Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp copy to Core/CppMicroServices/examples/dictionaryservice/IDictionaryService.cpp index 9b0abf1b25..ef0ba43dcb 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp +++ b/Core/CppMicroServices/examples/dictionaryservice/IDictionaryService.cpp @@ -1,31 +1,25 @@ /*============================================================================= 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 +#include "IDictionaryService.h" +IDictionaryService::~IDictionaryService() +{} diff --git a/Core/Code/CppMicroServices/test/usServiceControlInterface.h b/Core/CppMicroServices/examples/dictionaryservice/IDictionaryService.h similarity index 50% copy from Core/Code/CppMicroServices/test/usServiceControlInterface.h copy to Core/CppMicroServices/examples/dictionaryservice/IDictionaryService.h index 129832ff12..df806d843f 100644 --- a/Core/Code/CppMicroServices/test/usServiceControlInterface.h +++ b/Core/CppMicroServices/examples/dictionaryservice/IDictionaryService.h @@ -1,45 +1,58 @@ /*============================================================================= 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 IDICTIONARYSERVICE_H +#define IDICTIONARYSERVICE_H -#ifndef USSERVICECONTROLINTERFACE_H -#define USSERVICECONTROLINTERFACE_H - -#include +//! [service] #include #include -US_BEGIN_NAMESPACE - -struct ServiceControlInterface +#ifdef Example_dictionaryservice_EXPORTS + #define DICTIONAYSERVICE_EXPORT US_ABI_EXPORT +#else + #define DICTIONAYSERVICE_EXPORT US_ABI_IMPORT +#endif + +/** + * A simple service interface that defines a dictionary service. + * A dictionary service simply verifies the existence of a word. + **/ +struct DICTIONAYSERVICE_EXPORT IDictionaryService { - - virtual ~ServiceControlInterface() {} - - virtual void ServiceControl(int service, const std::string& operation, int ranking) = 0; + // Out-of-line virtual desctructor for proper dynamic cast + // support with older versions of gcc. + virtual ~IDictionaryService(); + + /** + * 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_END_NAMESPACE - -US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(ServiceControlInterface), "org.us.testing.ServiceControlInterface") +US_DECLARE_SERVICE_INTERFACE(IDictionaryService, "IDictionaryService/1.0") +//! [service] -#endif // USSERVICECONTROLINTERFACE_H +#endif // DICTIONARYSERVICE_H diff --git a/Core/CppMicroServices/examples/driver/CMakeLists.txt b/Core/CppMicroServices/examples/driver/CMakeLists.txt new file mode 100644 index 0000000000..f37d796a46 --- /dev/null +++ b/Core/CppMicroServices/examples/driver/CMakeLists.txt @@ -0,0 +1,16 @@ + +if(WIN32) + string(REPLACE "/" "\\\\" CMAKE_LIBRARY_OUTPUT_DIRECTORY_NATIVE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) + string(REPLACE "/" "\\\\" CMAKE_RUNTIME_OUTPUT_DIRECTORY_NATIVE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +else() + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_NATIVE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_NATIVE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +endif() + +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/usCppMicroServicesExampleDriverConfig.h.in + ${CMAKE_CURRENT_BINARY_DIR}/usCppMicroServicesExampleDriverConfig.h) + +include_directories(${CMAKE_CURRENT_BINARY_DIR}) + +add_executable(CppMicroServicesExampleDriver main.cpp) +target_link_libraries(CppMicroServicesExampleDriver ${CppMicroServices_LIBRARIES}) diff --git a/Core/CppMicroServices/examples/driver/main.cpp b/Core/CppMicroServices/examples/driver/main.cpp new file mode 100644 index 0000000000..f4dcfa7649 --- /dev/null +++ b/Core/CppMicroServices/examples/driver/main.cpp @@ -0,0 +1,300 @@ +/*============================================================================= + + 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 "usCppMicroServicesExampleDriverConfig.h" + +#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 + +#include +#include +#include +#include +#include +#include +#include + +US_USE_NAMESPACE + +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + +std::map GetExampleModules() +{ + std::map names; + names.insert(std::make_pair("Event Listener", "eventlistener")); + names.insert(std::make_pair("Dictionary Service", "dictionaryservice")); + names.insert(std::make_pair("French Dictionary", "frenchdictionary")); + names.insert(std::make_pair("Dictionary Client", "dictionaryclient")); + names.insert(std::make_pair("Dictionary Client 2", "dictionaryclient2")); + names.insert(std::make_pair("Dictionary Client 3", "dictionaryclient3")); + names.insert(std::make_pair("Spell Check Service", "spellcheckservice")); + names.insert(std::make_pair("Spell Check Client", "spellcheckclient")); + return names; +} + +int main(int /*argc*/, char** /*argv*/) +{ + char cmd[256]; + + std::map availableModules = GetExampleModules(); + + /* module path -> lib handle */ + std::map libraryHandles; + + SharedLibrary sharedLib(LIB_PATH, ""); + + std::cout << "> "; + while(std::cin.getline(cmd, sizeof(cmd))) + { + std::string strCmd(cmd); + if (strCmd == "q") + { + break; + } + else if (strCmd == "h") + { + std::cout << std::left << std::setw(15) << "h" << " This help text\n" + << std::setw(15) << "l " << " Load the module with id or name \n" + << std::setw(15) << "u " << " Unload the module with id \n" + << std::setw(15) << "s" << " Print status information\n" + << std::setw(15) << "q" << " Quit\n" << std::flush; + } + else if (strCmd.find("l ") != std::string::npos) + { + std::string idOrName; + idOrName.assign(strCmd.begin()+2, strCmd.end()); + std::stringstream ss(idOrName); + + long int id = -1; + ss >> id; + if (id > 0) + { + Module* module = ModuleRegistry::GetModule(id); + if (!module) + { + std::cout << "Error: unknown id" << std::endl; + } + else if (module->IsLoaded()) + { + std::cout << "Info: module already loaded" << std::endl; + } + else + { + try + { + std::map::iterator libIter = + libraryHandles.find(module->GetLocation()); + if (libIter != libraryHandles.end()) + { + libIter->second.Load(); + } + else + { + // The module has been loaded previously due to a + // linker dependency + SharedLibrary libHandle(module->GetLocation()); + libHandle.Load(); + libraryHandles.insert(std::make_pair(libHandle.GetFilePath(), libHandle)); + } + } + catch (const std::exception& e) + { + std::cout << e.what() << std::endl; + } + } + } + else + { + Module* module = ModuleRegistry::GetModule(idOrName); + if (!module) + { + try + { + std::map::iterator libIter = + libraryHandles.find(sharedLib.GetFilePath(idOrName)); + if (libIter != libraryHandles.end()) + { + libIter->second.Load(); + } + else + { + bool libFound = false; + for (std::map::const_iterator availableModuleIter = availableModules.begin(); + availableModuleIter != availableModules.end(); ++availableModuleIter) + { + if (availableModuleIter->second == idOrName) + { + libFound = true; + } + } + if (!libFound) + { + std::cout << "Error: unknown example module" << std::endl; + } + else + { + SharedLibrary libHandle(LIB_PATH, idOrName); + libHandle.Load(); + libraryHandles.insert(std::make_pair(libHandle.GetFilePath(), libHandle)); + } + } + + std::vector modules; + ModuleRegistry::GetModules(modules); + for (std::vector::const_iterator moduleIter = modules.begin(); + moduleIter != modules.end(); ++moduleIter) + { + availableModules.erase((*moduleIter)->GetName()); + } + + } + catch (const std::exception& e) + { + std::cout << e.what() << std::endl; + } + } + else if (!module->IsLoaded()) + { + try + { + const std::string modulePath = module->GetLocation(); + std::map::iterator libIter = + libraryHandles.find(modulePath); + if (libIter != libraryHandles.end()) + { + libIter->second.Load(); + } + else + { + SharedLibrary libHandle(LIB_PATH, idOrName); + libHandle.Load(); + libraryHandles.insert(std::make_pair(libHandle.GetFilePath(), libHandle)); + } + } + catch (const std::exception& e) + { + std::cout << e.what() << std::endl; + } + } + else if (module) + { + std::cout << "Info: module already loaded" << std::endl; + } + } + } + else if (strCmd.find("u ") != std::string::npos) + { + std::stringstream ss(strCmd); + ss.ignore(2); + + long int id = -1; + ss >> id; + + if (id == 1) + { + std::cout << "Info: Unloading not possible" << std::endl; + } + else + { + Module* const module = ModuleRegistry::GetModule(id); + if (module) + { + std::map::iterator libIter = + libraryHandles.find(module->GetLocation()); + if (libIter == libraryHandles.end()) + { + std::cout << "Info: Unloading not possible. The module was loaded by a dependent module." << std::endl; + } + else + { + try + { + libIter->second.Unload(); + + // Check if it has really been unloaded + if (module->IsLoaded()) + { + std::cout << "Info: The module is still referenced by another loaded module. It will be unloaded when all dependent modules are unloaded." << std::endl; + } + } + catch (const std::exception& e) + { + std::cout << e.what() << std::endl; + } + } + } + else + { + std::cout << "Error: unknown id" << std::endl; + } + } + } + else if (strCmd == "s") + { + std::vector modules; + ModuleRegistry::GetModules(modules); + + std::cout << std::left; + + std::cout << "Id | " << std::setw(20) << "Name" << " | " << std::setw(9) << "Status" << std::endl; + std::cout << "-----------------------------------\n"; + + for (std::map::const_iterator nameIter = availableModules.begin(); + nameIter != availableModules.end(); ++nameIter) + { + std::cout << " - | " << std::setw(20) << nameIter->second << " | " << std::setw(9) << "-" << std::endl; + } + + for (std::vector::const_iterator moduleIter = modules.begin(); + moduleIter != modules.end(); ++moduleIter) + { + std::cout << std::right << std::setw(2) << (*moduleIter)->GetModuleId() << std::left << " | "; + std::cout << std::setw(20) << (*moduleIter)->GetName() << " | "; + std::cout << std::setw(9) << ((*moduleIter)->IsLoaded() ? "LOADED" : "UNLOADED"); + std::cout << std::endl; + } + } + else + { + std::cout << "Unknown command: " << strCmd << " (type 'h' for help)" << std::endl; + } + std::cout << "> "; + } + + return 0; +} diff --git a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.h b/Core/CppMicroServices/examples/driver/usCppMicroServicesExampleDriverConfig.h.in similarity index 59% copy from Core/Code/CppMicroServices/src/util/usUncompressResourceData.h copy to Core/CppMicroServices/examples/driver/usCppMicroServicesExampleDriverConfig.h.in index a3e82f3679..880a0cfa25 100644 --- a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.h +++ b/Core/CppMicroServices/examples/driver/usCppMicroServicesExampleDriverConfig.h.in @@ -1,33 +1,41 @@ /*============================================================================= 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 +#ifndef USEXAMPLEDRIVERCONFIG_H +#define USEXAMPLEDRIVERCONFIG_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 +#ifdef US_PLATFORM_POSIX +#define PATH_SEPARATOR "/" +#else +#define PATH_SEPARATOR "\\" +#endif + +#ifdef CMAKE_INTDIR +#define US_LIBRARY_OUTPUT_DIRECTORY "@CMAKE_LIBRARY_OUTPUT_DIRECTORY_NATIVE@" PATH_SEPARATOR CMAKE_INTDIR +#define US_RUNTIME_OUTPUT_DIRECTORY "@CMAKE_RUNTIME_OUTPUT_DIRECTORY_NATIVE@" PATH_SEPARATOR CMAKE_INTDIR +#else +#define US_LIBRARY_OUTPUT_DIRECTORY "@CMAKE_LIBRARY_OUTPUT_DIRECTORY_NATIVE@" +#define US_RUNTIME_OUTPUT_DIRECTORY "@CMAKE_RUNTIME_OUTPUT_DIRECTORY_NATIVE@" +#endif + +#endif // USEXAMPLEDRIVERCONFIG_H diff --git a/Core/CppMicroServices/examples/eventlistener/Activator.cpp b/Core/CppMicroServices/examples/eventlistener/Activator.cpp new file mode 100644 index 0000000000..d7b9ae245f --- /dev/null +++ b/Core/CppMicroServices/examples/eventlistener/Activator.cpp @@ -0,0 +1,90 @@ +/*============================================================================= + + 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. + +=============================================================================*/ + +//! [Activator] +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a simple module that utilizes the CppMicroServices's + * event mechanism to listen for service events. Upon receiving a service event, + * it prints out the event's details. + */ +class Activator : public ModuleActivator +{ + +private: + + /** + * Implements ModuleActivator::Load(). Prints a message and adds a member + * function to the module context as a service listener. + * + * @param context the framework context for the module. + */ + void Load(ModuleContext* context) + { + std::cout << "Starting to listen for service events." << std::endl; + context->AddServiceListener(this, &Activator::ServiceChanged); + } + + /** + * Implements ModuleActivator::Unload(). Prints a message and removes the + * member function from the module context as a service listener. + * + * @param context the framework context for the module. + */ + void Unload(ModuleContext* context) + { + context->RemoveServiceListener(this, &Activator::ServiceChanged); + std::cout << "Stopped listening for service events." << std::endl; + + // Note: It is not required that we remove the listener here, + // since the framework will do it automatically anyway. + } + + /** + * Prints the details of any service event from the framework. + * + * @param event the fired service event. + */ + void ServiceChanged(const ServiceEvent event) + { + std::string objectClass = ref_any_cast >(event.GetServiceReference().GetProperty(ServiceConstants::OBJECTCLASS())).front(); + + if (event.GetType() == ServiceEvent::REGISTERED) + { + std::cout << "Ex1: Service of type " << objectClass << " registered." << std::endl; + } + else if (event.GetType() == ServiceEvent::UNREGISTERING) + { + std::cout << "Ex1: Service of type " << objectClass << " unregistered." << std::endl; + } + else if (event.GetType() == ServiceEvent::MODIFIED) + { + std::cout << "Ex1: Service of type " << objectClass << " modified." << std::endl; + } + } +}; + +US_EXPORT_MODULE_ACTIVATOR(eventlistener, Activator) +//! [Activator] diff --git a/Core/CppMicroServices/examples/eventlistener/CMakeLists.txt b/Core/CppMicroServices/examples/eventlistener/CMakeLists.txt new file mode 100644 index 0000000000..2c6dce49be --- /dev/null +++ b/Core/CppMicroServices/examples/eventlistener/CMakeLists.txt @@ -0,0 +1,7 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Event Listener" + LIBRARY_NAME "eventlistener") + +CreateExample(eventlistener ${_srcs}) diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp b/Core/CppMicroServices/examples/frenchdictionary/Activator.cpp similarity index 56% copy from Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp copy to Core/CppMicroServices/examples/frenchdictionary/Activator.cpp index bd714f6d54..cb70512826 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp +++ b/Core/CppMicroServices/examples/frenchdictionary/Activator.cpp @@ -1,121 +1,119 @@ +/*============================================================================= + + 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. + +=============================================================================*/ //! [Activator] -#include "DictionaryService.h" +#include "IDictionaryService.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 + * context to register a French 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. + * defined in Example 2 (dictionaryservice) and is implemented by a + * nested class. This class is identical to the class in Example 2, + * except that the dictionary contains French words. */ -class US_ABI_LOCAL MyActivator : public ModuleActivator +class US_ABI_LOCAL Activator : 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 + class DictionaryImpl : public IDictionaryService { // 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("bienvenue"); + m_dictionary.insert("au"); + m_dictionary.insert("tutoriel"); 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) + 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); + props["Language"] = std::string("French"); + 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) +US_EXPORT_MODULE_ACTIVATOR(frenchdictionary, Activator) //![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/CppMicroServices/examples/frenchdictionary/CMakeLists.txt b/Core/CppMicroServices/examples/frenchdictionary/CMakeLists.txt new file mode 100644 index 0000000000..d5c0a649dd --- /dev/null +++ b/Core/CppMicroServices/examples/frenchdictionary/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "French Dictionary" + LIBRARY_NAME "frenchdictionary") + +set(frenchdictionary_DEPENDS dictionaryservice) +CreateExample(frenchdictionary ${_srcs}) diff --git a/Core/CppMicroServices/examples/makefile/IDictionaryService.cpp b/Core/CppMicroServices/examples/makefile/IDictionaryService.cpp new file mode 100644 index 0000000000..47e5097506 --- /dev/null +++ b/Core/CppMicroServices/examples/makefile/IDictionaryService.cpp @@ -0,0 +1,5 @@ +#include "IDictionaryService.h" + +IDictionaryService::~IDictionaryService() +{ +} diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/DictionaryService.h b/Core/CppMicroServices/examples/makefile/IDictionaryService.h similarity index 52% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/DictionaryService.h rename to Core/CppMicroServices/examples/makefile/IDictionaryService.h index 304d76c6c3..1f003f955d 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/DictionaryService.h +++ b/Core/CppMicroServices/examples/makefile/IDictionaryService.h @@ -1,27 +1,33 @@ -#ifndef DICTIONARYSERVICE_H -#define DICTIONARYSERVICE_H +#ifndef IDICTIONARYSERVICE_H +#define IDICTIONARYSERVICE_H #include #include +#ifdef MODULE_EXPORTS + #define MODULE_EXPORT US_ABI_EXPORT +#else + #define MODULE_EXPORT US_ABI_IMPORT +#endif + /** * A simple service interface that defines a dictionary service. * A dictionary service simply verifies the existence of a word. **/ -struct DictionaryService +struct MODULE_EXPORT IDictionaryService { - virtual ~DictionaryService() {} + virtual ~IDictionaryService(); /** * 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; + virtual bool CheckWord(const std::string& word) = 0; }; -US_DECLARE_SERVICE_INTERFACE(DictionaryService, "DictionaryService/1.0") +US_DECLARE_SERVICE_INTERFACE(IDictionaryService, "IDictionaryService/1.0") #endif // DICTIONARYSERVICE_H diff --git a/Core/CppMicroServices/examples/makefile/Makefile b/Core/CppMicroServices/examples/makefile/Makefile new file mode 100644 index 0000000000..0e4d21a6d2 --- /dev/null +++ b/Core/CppMicroServices/examples/makefile/Makefile @@ -0,0 +1,26 @@ +CXX = g++ +CXXFLAGS = -g -Wall -Wno-unused -pedantic -fPIC $(CppMicroServices_CXX_FLAGS) +LDFLAGS = -Wl,-rpath=$(CppMicroServices_ROOT)/lib -Wl,-rpath=. +LDLIBS = -lCppMicroServices + +INCLUDEDIRS = -I$(CppMicroServices_ROOT)/include/CppMicroServices +LIBDIRS = -L$(CppMicroServices_ROOT)/lib/CppMicroServices -L. + +all : main libmodule.so + +main: libmodule.so main.o + $(CXX) -o $@ $^ $(CXXFLAGS) $(LDFLAGS) $(INCLUDEDIRS) $(LIBDIRS) $(LDLIBS) -lmodule + +libmodule.so: module.o IDictionaryService.o + $(CXX) -shared -o $@ $^ $(CXXFLAGS) $(LDFLAGS) $(INCLUDEDIRS) $(LIBDIRS) $(LDLIBS) + +main.o: main.cpp + $(CXX) $(CXXFLAGS) $(INCLUDEDIRS) -c $< -o $@ + +%.o: %.cpp + $(CXX) $(CXXFLAGS) -DMODULE_EXPORTS $(INCLUDEDIRS) -c $< -o $@ + +.PHONY : clean + +clean: + rm -f *.o diff --git a/Core/CppMicroServices/examples/makefile/main.cpp b/Core/CppMicroServices/examples/makefile/main.cpp new file mode 100644 index 0000000000..fe66aa18b3 --- /dev/null +++ b/Core/CppMicroServices/examples/makefile/main.cpp @@ -0,0 +1,25 @@ +#include +#include +#include + +#include "IDictionaryService.h" + +US_USE_NAMESPACE + +int main(int /*argc*/, char* /*argv*/[]) +{ + ServiceReference dictionaryServiceRef = + GetModuleContext()->GetServiceReference(); + if (dictionaryServiceRef) + { + IDictionaryService* dictionaryService = GetModuleContext()->GetService(dictionaryServiceRef); + if (dictionaryService) + { + std::cout << "Dictionary contains 'Tutorial': " << dictionaryService->CheckWord("Tutorial") << std::endl; + } + } +} + +#include + +US_INITIALIZE_EXECUTABLE("main") diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp b/Core/CppMicroServices/examples/makefile/module.cpp similarity index 56% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp rename to Core/CppMicroServices/examples/makefile/module.cpp index bd714f6d54..e5260d7720 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp +++ b/Core/CppMicroServices/examples/makefile/module.cpp @@ -1,121 +1,102 @@ - -//! [Activator] -#include "DictionaryService.h" - #include #include #include #include -// Replace that include with your own base class declaration -#include US_BASECLASS_HEADER +#include "IDictionaryService.h" #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 + class DictionaryImpl : public IDictionaryService { // The set of words contained in the dictionary. - std::set m_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"); + 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 + * Implements IDictionaryService::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) + 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(); + return m_Dictionary.find(lword) != m_Dictionary.end(); } }; - std::auto_ptr m_dictionaryService; + 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); + m_DictionaryService.reset(new DictionaryImpl); ServiceProperties props; props["Language"] = std::string("English"); - context->RegisterService(m_dictionaryService.get(), props); + 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] +US_EXPORT_MODULE_ACTIVATOR(module, MyActivator) #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; -} +US_INITIALIZE_MODULE("My Module", "module") diff --git a/Core/CppMicroServices/examples/spellcheckclient/Activator.cpp b/Core/CppMicroServices/examples/spellcheckclient/Activator.cpp new file mode 100644 index 0000000000..7014fe46fa --- /dev/null +++ b/Core/CppMicroServices/examples/spellcheckclient/Activator.cpp @@ -0,0 +1,143 @@ +/*============================================================================= + + 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. + +=============================================================================*/ + +//! [Activator] +#include "ISpellCheckService.h" + +#include +#include +#include + +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module that uses a spell checker + * service to check the spelling of a passage. This module + * is essentially identical to Example 5, in that it uses the + * Service Tracker to monitor the dynamic availability of the + * spell checker service. When loading this module, the thread + * calling the Load() method is used to read passages from + * standard input. You can stop spell checking passages by + * entering an empty line, but to start spell checking again + * you must un-load and then load the module again. +**/ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +public: + + Activator() + : m_context(NULL) + , m_tracker(NULL) + {} + + /** + * Implements ModuleActivator::Load(). Creates a service + * tracker object to monitor spell checker services. Enters + * a spell check loop where it reads passages from standard + * input and checks their spelling using the spell checker service. + * + * \note It is very bad practice to use the calling thread to perform a + * lengthy process like this; this is only done for the purpose of + * the tutorial. + * + * @param context the module context for this module. + */ + void Load(ModuleContext *context) + { + m_context = context; + + // Create a service tracker to monitor spell check services. + m_tracker = new ServiceTracker(m_context); + m_tracker->Open(); + + std::cout << "Enter a blank line to exit." << std::endl; + + // Loop endlessly until the user enters a blank line + while (std::cin) + { + // Ask the user to enter a passage. + std::cout << "Enter passage: "; + + std::string passage; + std::getline(std::cin, passage); + + // Get the selected spell check service, if available. + ISpellCheckService* checker = m_tracker->GetService(); + + // If the user entered a blank line, then + // exit the loop. + if (passage.empty()) + { + break; + } + // If there is no spell checker, then say so. + else if (checker == NULL) + { + std::cout << "No spell checker available." << std::endl; + } + // Otherwise check passage and print misspelled words. + else + { + std::vector errors = checker->Check(passage); + + if (errors.empty()) + { + std::cout << "Passage is correct." << std::endl; + } + else + { + std::cout << "Incorrect word(s):" << std::endl; + for (std::size_t i = 0; i < errors.size(); ++i) + { + std::cout << " " << errors[i] << std::endl; + } + } + } + } + + // This automatically closes the tracker + delete m_tracker; + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unget any used services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + } + +private: + + // Module context + ModuleContext* m_context; + + // The service tracker + ServiceTracker* m_tracker; +}; + +US_EXPORT_MODULE_ACTIVATOR(spellcheckclient, Activator) +//![Activator] diff --git a/Core/CppMicroServices/examples/spellcheckclient/CMakeLists.txt b/Core/CppMicroServices/examples/spellcheckclient/CMakeLists.txt new file mode 100644 index 0000000000..7e28ef4b12 --- /dev/null +++ b/Core/CppMicroServices/examples/spellcheckclient/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Spell Check Client" + LIBRARY_NAME "spellcheckclient") + +set(spellcheckclient_DEPENDS spellcheckservice) +CreateExample(spellcheckclient ${_srcs}) diff --git a/Core/CppMicroServices/examples/spellcheckservice/Activator.cpp b/Core/CppMicroServices/examples/spellcheckservice/Activator.cpp new file mode 100644 index 0000000000..9ad3d882e4 --- /dev/null +++ b/Core/CppMicroServices/examples/spellcheckservice/Activator.cpp @@ -0,0 +1,225 @@ +/*============================================================================= + + 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. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" +#include "ISpellCheckService.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module that implements a spell + * checker service. The spell checker service uses all available + * dictionary services to check for the existence of words in + * a given sentence. This module uses a ServiceTracker to + * monitors the dynamic availability of dictionary services, + * and to aggregate all available dictionary services as they + * arrive and depart. The spell checker service is only registered + * if there are dictionary services available, thus the spell + * checker service will appear and disappear as dictionary + * services appear and disappear, respectively. +**/ +class US_ABI_LOCAL Activator : public ModuleActivator, public ServiceTrackerCustomizer +{ + +private: + + /** + * A private inner class that implements a spell check service; see + * ISpellCheckService for details of the service. + */ + class SpellCheckImpl : public ISpellCheckService + { + + private: + + typedef std::map, IDictionaryService*> RefToServiceType; + RefToServiceType m_refToSvcMap; + + public: + + /** + * Implements ISpellCheckService::Check(). Checks the given passage for + * misspelled words. + * + * @param passage the passage to spell check. + * @return A list of misspelled words. + */ + std::vector Check(const std::string& passage) + { + std::vector errorList; + + // No misspelled words for an empty string. + if (passage.empty()) + { + return errorList; + } + + // Tokenize the passage using spaces and punctuation. + const char* delimiters = " ,.!?;:"; + char* passageCopy = new char[passage.size()+1]; + std::memcpy(passageCopy, passage.c_str(), passage.size()+1); + char* pch = std::strtok(passageCopy, delimiters); + + { + // Lock the m_refToSvcMap member using your favorite thread library here... + // MutexLocker lock(&m_refToSvcMapMutex) + + // Loop through each word in the passage. + while (pch) + { + std::string word(pch); + + bool correct = false; + + // Check each available dictionary for the current word. + for (RefToServiceType::const_iterator i = m_refToSvcMap.begin(); + (!correct) && (i != m_refToSvcMap.end()); ++i) + { + IDictionaryService* dictionary = i->second; + + if (dictionary->CheckWord(word)) + { + correct = true; + } + } + + // If the word is not correct, then add it + // to the incorrect word list. + if (!correct) + { + errorList.push_back(word); + } + + pch = std::strtok(NULL, delimiters); + } + } + + delete[] passageCopy; + + return errorList; + } + + int AddDictionary(const ServiceReference& ref, IDictionaryService* dictionary) + { + // Lock the m_refToSvcMap member using your favorite thread library here... + // MutexLocker lock(&m_refToSvcMapMutex) + + m_refToSvcMap.insert(std::make_pair(ref, dictionary)); + + return m_refToSvcMap.size(); + } + + int RemoveDictionary(const ServiceReference& ref) + { + // Lock the m_refToSvcMap member using your favorite thread library here... + // MutexLocker lock(&m_refToSvcMapMutex) + + m_refToSvcMap.erase(ref); + + return m_refToSvcMap.size(); + } + }; + + virtual IDictionaryService* AddingService(const ServiceReference& reference) + { + IDictionaryService* dictionary = m_context->GetService(reference); + int count = m_spellCheckService->AddDictionary(reference, dictionary); + if (!m_spellCheckReg && count > 1) + { + m_spellCheckReg = m_context->RegisterService(m_spellCheckService.get()); + } + return dictionary; + } + + virtual void ModifiedService(const ServiceReference& /*reference*/, + IDictionaryService* /*service*/) + { + // do nothing + } + + virtual void RemovedService(const ServiceReference& reference, + IDictionaryService* /*service*/) + { + if (m_spellCheckService->RemoveDictionary(reference) < 2 && m_spellCheckReg) + { + m_spellCheckReg.Unregister(); + m_spellCheckReg = 0; + } + } + + std::auto_ptr m_spellCheckService; + ServiceRegistration m_spellCheckReg; + + ModuleContext* m_context; + std::auto_ptr > m_tracker; + +public: + + Activator() + : m_context(NULL) + {} + + /** + * 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_context = context; + + m_spellCheckService.reset(new SpellCheckImpl); + m_tracker.reset(new ServiceTracker(context, this)); + m_tracker->Open(); + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unregister any registered services + * and release any used services. + * + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + // NOTE: The service is automatically unregistered + + m_tracker->Close(); + } + +}; + +US_EXPORT_MODULE_ACTIVATOR(spellcheckservice, Activator) +//![Activator] diff --git a/Core/CppMicroServices/examples/spellcheckservice/CMakeLists.txt b/Core/CppMicroServices/examples/spellcheckservice/CMakeLists.txt new file mode 100644 index 0000000000..a86d8153a6 --- /dev/null +++ b/Core/CppMicroServices/examples/spellcheckservice/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp ISpellCheckService.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Spell Check Service" + LIBRARY_NAME "spellcheckservice") + +set(spellcheckservice_DEPENDS dictionaryservice) +CreateExample(spellcheckservice ${_srcs}) diff --git a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp b/Core/CppMicroServices/examples/spellcheckservice/ISpellCheckService.cpp similarity index 90% copy from Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp copy to Core/CppMicroServices/examples/spellcheckservice/ISpellCheckService.cpp index 9b0abf1b25..4a2d238a38 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp +++ b/Core/CppMicroServices/examples/spellcheckservice/ISpellCheckService.cpp @@ -1,31 +1,25 @@ /*============================================================================= 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 +#include "ISpellCheckService.h" +ISpellCheckService::~ISpellCheckService() +{} diff --git a/Core/CppMicroServices/examples/spellcheckservice/ISpellCheckService.h b/Core/CppMicroServices/examples/spellcheckservice/ISpellCheckService.h new file mode 100644 index 0000000000..679235801b --- /dev/null +++ b/Core/CppMicroServices/examples/spellcheckservice/ISpellCheckService.h @@ -0,0 +1,64 @@ +/*============================================================================= + + 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 ISPELLCHECKSERVICE_H +#define ISPELLCHECKSERVICE_H + +//! [service] +#include + +#include +#include + +#ifdef Example_spellcheckservice_EXPORTS + #define SPELLCHECKSERVICE_EXPORT US_ABI_EXPORT +#else + #define SPELLCHECKSERVICE_EXPORT US_ABI_IMPORT +#endif + +/** + * A simple service interface that defines a spell check service. A spell check + * service checks the spelling of all words in a given passage. A passage is any + * number of words separated by a space character and the following punctuation + * marks: comma, period, exclamation mark, question mark, semi-colon, and colon. + */ +struct SPELLCHECKSERVICE_EXPORT ISpellCheckService +{ + // Out-of-line virtual desctructor for proper dynamic cast + // support with older versions of gcc. + virtual ~ISpellCheckService(); + + /** + * Checks a given passage for spelling errors. A passage is any number of + * words separated by a space and any of the following punctuation marks: + * comma (,), period (.), exclamation mark (!), question mark (?), + * semi-colon (;), and colon(:). + * + * @param passage the passage to spell check. + * @return A list of misspelled words. + */ + virtual std::vector Check(const std::string& passage) = 0; +}; + +US_DECLARE_SERVICE_INTERFACE(ISpellCheckService, "ISpellCheckService/1.0") +//! [service] +//! +#endif // ISPELLCHECKSERVICE_H diff --git a/Core/Code/CppMicroServices/src/CMakeLists.txt b/Core/CppMicroServices/src/CMakeLists.txt similarity index 78% rename from Core/Code/CppMicroServices/src/CMakeLists.txt rename to Core/CppMicroServices/src/CMakeLists.txt index 45a9814854..5244cbb638 100644 --- a/Core/Code/CppMicroServices/src/CMakeLists.txt +++ b/Core/CppMicroServices/src/CMakeLists.txt @@ -1,184 +1,190 @@ #----------------------------------------------------------------------------- # US source files #----------------------------------------------------------------------------- set(_srcs util/usAny.cpp + util/jsoncpp.cpp + util/usSharedLibrary.cpp + util/usThreads.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/usServiceObjects.cpp service/usServiceProperties.cpp - service/usServiceReference.cpp - service/usServiceReferencePrivate.cpp - service/usServiceRegistration.cpp - service/usServiceRegistrationPrivate.cpp + service/usServicePropertiesImpl.cpp + service/usServiceReferenceBase.cpp + service/usServiceReferenceBasePrivate.cpp + service/usServiceRegistrationBase.cpp + service/usServiceRegistrationBasePrivate.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/usModuleManifest.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/usServicePropertiesImpl_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/usSharedLibrary.h util/usUncompressResourceData.h service/usLDAPFilter.h + service/usPrototypeServiceFactory.h service/usServiceEvent.h service/usServiceException.h + service/usServiceFactory.h service/usServiceInterface.h + service/usServiceObjects.h service/usServiceProperties.h service/usServiceReference.h + service/usServiceReferenceBase.h service/usServiceRegistration.h + service/usServiceRegistrationBase.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") + usFunctionGenerateModuleInit(_srcs NAME ${PROJECT_NAME}) + usFunctionEmbedResources(_srcs LIBRARY_NAME ${PROJECT_NAME} + ROOT_DIR resources + FILES manifest.json) add_library(${PROJECT_NAME} ${_srcs} ${_public_headers} ${_private_headers} ${us_config_h_file}) - if(NOT US_IS_EMBEDDED AND US_LINK_FLAGS) + if(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) + set_target_properties(${PROJECT_NAME} PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + ) if(US_LINK_LIBRARIES) - target_link_libraries(${PROJECT_NAME} ${_link_libraries}) + target_link_libraries(${PROJECT_NAME} ${US_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) + install(TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME}Targets + RUNTIME DESTINATION ${RUNTIME_INSTALL_DIR} COMPONENT sdk + LIBRARY DESTINATION ${LIBRARY_INSTALL_DIR} COMPONENT sdk + ARCHIVE DESTINATION ${ARCHIVE_INSTALL_DIR} COMPONENT sdk + PUBLIC_HEADER DESTINATION ${HEADER_INSTALL_DIR} COMPONENT sdk + PRIVATE_HEADER DESTINATION ${HEADER_INSTALL_DIR} COMPONENT sdk) endif() - diff --git a/Core/Code/CppMicroServices/src/module/usCoreModuleContext.cpp b/Core/CppMicroServices/src/module/usCoreModuleContext.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usCoreModuleContext.cpp rename to Core/CppMicroServices/src/module/usCoreModuleContext.cpp diff --git a/Core/Code/CppMicroServices/src/module/usCoreModuleContext_p.h b/Core/CppMicroServices/src/module/usCoreModuleContext_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usCoreModuleContext_p.h rename to Core/CppMicroServices/src/module/usCoreModuleContext_p.h diff --git a/Core/Code/CppMicroServices/src/module/usGetModuleContext.h b/Core/CppMicroServices/src/module/usGetModuleContext.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usGetModuleContext.h rename to Core/CppMicroServices/src/module/usGetModuleContext.h diff --git a/Core/Code/CppMicroServices/src/module/usModule.cpp b/Core/CppMicroServices/src/module/usModule.cpp similarity index 82% rename from Core/Code/CppMicroServices/src/module/usModule.cpp rename to Core/CppMicroServices/src/module/usModule.cpp index dbe528c288..f12b12b6e4 100644 --- a/Core/Code/CppMicroServices/src/module/usModule.cpp +++ b/Core/CppMicroServices/src/module/usModule.cpp @@ -1,281 +1,319 @@ /*============================================================================= 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() +const std::string& Module::PROP_VERSION() { - static const std::string s("module.module_depends"); + static const std::string s("module.version"); return s; } -const std::string& Module::PROP_LIB_DEPENDS() + +const std::string&Module::PROP_VENDOR() { - static const std::string s("module.lib_depends"); + static const std::string s("module.vendor"); return s; } -const std::string& Module::PROP_VERSION() + +const std::string&Module::PROP_DESCRIPTION() { - static const std::string s("module.version"); + static const std::string s("module.description"); + return s; +} + +const std::string&Module::PROP_AUTOLOAD_DIR() +{ + static const std::string s("module.autoload_dir"); 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 +Any Module::GetProperty(const std::string& key) const { - if (d->properties.count(key) == 0) return ""; - return d->properties[key]; + return d->moduleManifest.GetValue(key); +} + +std::vector Module::GetPropertyKeys() const +{ + return d->moduleManifest.GetKeys(); +} + +std::vector Module::GetRegisteredServices() const +{ + std::vector sr; + std::vector res; + d->coreCtx->services.GetRegisteredByModule(d, sr); + for (std::vector::const_iterator i = sr.begin(); + i != sr.end(); ++i) + { + res.push_back(i->GetReference()); + } + return res; +} + +std::vector Module::GetServicesInUse() const +{ + std::vector sr; + std::vector res; + d->coreCtx->services.GetUsedByModule(const_cast(this), sr); + for (std::vector::const_iterator i = sr.begin(); + i != sr.end(); ++i) + { + res.push_back(i->GetReference()); + } + return res; } 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/CppMicroServices/src/module/usModule.h similarity index 72% rename from Core/Code/CppMicroServices/src/module/usModule.h rename to Core/CppMicroServices/src/module/usModule.h index de8aede10f..b92e2239cb 100644 --- a/Core/Code/CppMicroServices/src/module/usModule.h +++ b/Core/CppMicroServices/src/module/usModule.h @@ -1,267 +1,368 @@ /*============================================================================= 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 Any; class CoreModuleContext; struct ModuleInfo; class ModuleContext; class ModuleResource; class ModulePrivate; +template +class ServiceReference; + +typedef ServiceReference ServiceReferenceU; + /** * \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: + /** + * Returns the property key for looking up this module's id. + * The property value is of type \c long. + * + * @return The id property key. + */ static const std::string& PROP_ID(); + + /** + * Returns the property key for looking up this module's name. + * The property value is of type \c std::string. + * + * @return The name property key. + */ static const std::string& PROP_NAME(); + + /** + * Returns the property key for looking up this module's + * location the file system. + * The property value is of type \c std::string. + * + * @return The location property key. + */ static const std::string& PROP_LOCATION(); - static const std::string& PROP_MODULE_DEPENDS(); - static const std::string& PROP_LIB_DEPENDS(); + + /** + * Returns the property key with a value of \c module.version for looking + * up this module's version identifier. + * The property value is of type \c std::string. + * + * @return The version property key. + */ static const std::string& PROP_VERSION(); + /** + * Returns the property key with a value of \c module.vendor for looking + * up this module's vendor information. + * The property value is of type \c std::string. + * + * @return The version property key. + */ + static const std::string& PROP_VENDOR(); + + /** + * Returns the property key with a value of \c module.description for looking + * up this module's description. + * The property value is of type \c std::string. + * + * @return The version property key. + */ + static const std::string& PROP_DESCRIPTION(); + + /** + * Returns the property key with a value of \c module.autoload_dir for looking + * up this module's auto-load directory. + * The property value is of type \c std::string. + * + * @return The version property key. + */ + static const std::string& PROP_AUTOLOAD_DIR(); + ~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. + * method returns an empty Any 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. + * + * @sa GetPropertyKeys() + * @sa \ref MicroServices_ModuleProperties + */ + Any GetProperty(const std::string& key) const; + + /** + * Returns a list of top-level property keys for this module. + * + * @return A list of available property keys. + * + * @sa \ref MicroServices_ModuleProperties + */ + std::vector GetPropertyKeys() const; + + /** + * Returns this module's ServiceReference list for all services it + * has registered or an empty list if this module has no registered + * services. + * + * The list is valid at the time of the call to this method, however, + * as the framework is a very dynamic environment, services can be + * modified or unregistered at anytime. + * + * @return A list of ServiceReference objects for services this + * module has registered. + */ + std::vector GetRegisteredServices() const; + + /** + * Returns this module's ServiceReference list for all services it is + * using or returns an empty list if this module is not using any + * services. A module is considered to be using a service if its use + * count for that service is greater than zero. + * + * The list is valid at the time of the call to this method, however, + * as the framework is a very dynamic environment, services can be + * modified or unregistered at anytime. + * + * @return A list of ServiceReference objects for all services this + * module is using. */ - std::string GetProperty(const std::string& key) const; + std::vector GetServicesInUse() 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/CppMicroServices/src/module/usModuleAbstractTracked.tpp similarity index 73% rename from Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.tpp rename to Core/CppMicroServices/src/module/usModuleAbstractTracked.tpp index d344538f03..66187162a2 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.tpp +++ b/Core/CppMicroServices/src/module/usModuleAbstractTracked.tpp @@ -1,314 +1,315 @@ /*============================================================================= 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 +const bool ModuleAbstractTracked::DEBUG_OUTPUT = false; -template -ModuleAbstractTracked::ModuleAbstractTracked() +template +ModuleAbstractTracked::ModuleAbstractTracked() { closed = false; } -template -ModuleAbstractTracked::~ModuleAbstractTracked() +template +ModuleAbstractTracked::~ModuleAbstractTracked() { } -template -void ModuleAbstractTracked::SetInitial(const std::list& initiallist) +template +void ModuleAbstractTracked::SetInitial(const std::vector& initiallist) { - initial = initiallist; + std::copy(initiallist.begin(), initiallist.end(), std::back_inserter(initial)); if (DEBUG_OUTPUT) { - for(typename std::list::const_iterator item = initiallist.begin(); - item != initiallist.end(); ++item) + for(typename std::list::const_iterator item = initial.begin(); + item != initial.end(); ++item) { US_DEBUG << "ModuleAbstractTracked::setInitial: " << (*item); } } } -template -void ModuleAbstractTracked::TrackInitial() +template +void ModuleAbstractTracked::TrackInitial() { while (true) { - S item(0); + S item; { 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 (TTT::IsValid(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() +template +void ModuleAbstractTracked::Close() { closed = true; } -template -void ModuleAbstractTracked::Track(S item, R related) +template +void ModuleAbstractTracked::Track(S item, R related) { - T object(0); + T object = TTT::DefaultValue(); { typename Self::Lock l(this); if (closed) { return; } object = tracked[item]; - if (!object) + if (!TTT::IsValid(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) + if (!TTT::IsValid(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) +template +void ModuleAbstractTracked::Untrack(S item, R related) { - T object(0); + T object = TTT::DefaultValue(); { 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) + if (!TTT::IsValid(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 +template +std::size_t ModuleAbstractTracked::Size() const { return tracked.size(); } -template -bool ModuleAbstractTracked::IsEmpty() const +template +bool ModuleAbstractTracked::IsEmpty() const { return tracked.empty(); } -template -T ModuleAbstractTracked::GetCustomizedObject(S item) const +template +typename ModuleAbstractTracked::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 +template +void ModuleAbstractTracked::GetTracked(std::vector& items) const { for (typename TrackingMap::const_iterator i = tracked.begin(); i != tracked.end(); ++i) { items.push_back(i->first); } } -template -void ModuleAbstractTracked::Modified() +template +void ModuleAbstractTracked::Modified() { trackingCount.Ref(); } -template -int ModuleAbstractTracked::GetTrackingCount() const +template +int ModuleAbstractTracked::GetTrackingCount() const { return trackingCount; } -template -void ModuleAbstractTracked::CopyEntries(TrackingMap& map) const +template +void ModuleAbstractTracked::CopyEntries(TrackingMap& map) const { map.insert(tracked.begin(), tracked.end()); } -template -bool ModuleAbstractTracked::CustomizerAddingFinal(S item, const T& custom) +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) + if (TTT::IsValid(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) +template +void ModuleAbstractTracked::TrackAdding(S item, R related) { US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::trackAdding:" << item; - T object(0); + T object = TTT::DefaultValue(); 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) + if (becameUntracked && TTT::IsValid(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/CppMicroServices/src/module/usModuleAbstractTracked_p.h similarity index 96% rename from Core/Code/CppMicroServices/src/module/usModuleAbstractTracked_p.h rename to Core/CppMicroServices/src/module/usModuleAbstractTracked_p.h index ccdc3627d4..9bdb4f157b 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked_p.h +++ b/Core/CppMicroServices/src/module/usModuleAbstractTracked_p.h @@ -1,291 +1,293 @@ /*============================================================================= 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 #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 > +template +class ModuleAbstractTracked : public US_DEFAULT_THREADING > { public: + typedef typename TTT::TrackedType T; + /* 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); + void SetInitial(const std::vector& 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; + void GetTracked(std::vector& 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; + 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/CppMicroServices/src/module/usModuleActivator.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleActivator.h rename to Core/CppMicroServices/src/module/usModuleActivator.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleContext.cpp b/Core/CppMicroServices/src/module/usModuleContext.cpp similarity index 72% rename from Core/Code/CppMicroServices/src/module/usModuleContext.cpp rename to Core/CppMicroServices/src/module/usModuleContext.cpp index 2164370632..de01d5658e 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleContext.cpp +++ b/Core/CppMicroServices/src/module/usModuleContext.cpp @@ -1,157 +1,161 @@ /*============================================================================= 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" +#include "usServiceReferenceBasePrivate.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) +ServiceRegistrationU ModuleContext::RegisterService(const InterfaceMap& service, + const ServiceProperties& properties) { - return d->module->coreCtx->services.RegisterService(d->module, clazzes, service, properties); + return d->module->coreCtx->services.RegisterService(d->module, service, properties); } -ServiceRegistration ModuleContext::RegisterService(const char* clazz, US_BASECLASS_NAME* service, - const ServiceProperties& properties) +std::vector ModuleContext::GetServiceReferences(const std::string& clazz, + const std::string& filter) { - std::list clazzes; - clazzes.push_back(clazz); - return d->module->coreCtx->services.RegisterService(d->module, clazzes, service, properties); + std::vector result; + std::vector refs; + d->module->coreCtx->services.Get(clazz, filter, d->module, refs); + for (std::vector::const_iterator iter = refs.begin(); + iter != refs.end(); ++iter) + { + result.push_back(ServiceReferenceU(*iter)); + } + return result; } -std::list ModuleContext::GetServiceReferences(const std::string& clazz, - const std::string& filter) +ServiceReferenceU ModuleContext::GetServiceReference(const std::string& clazz) { - std::list result; - d->module->coreCtx->services.Get(clazz, filter, 0, result); - return result; + return d->module->coreCtx->services.Get(d->module, clazz); } -ServiceReference ModuleContext::GetServiceReference(const std::string& clazz) +void* ModuleContext::GetService(const ServiceReferenceBase& reference) { - return d->module->coreCtx->services.Get(d->module, clazz); + if (!reference) + { + throw std::invalid_argument("Default constructed ServiceReference is not a valid input to GetService()"); + } + return reference.d->GetService(d->module->q); } -US_BASECLASS_NAME* ModuleContext::GetService(const ServiceReference& reference) +InterfaceMap ModuleContext::GetService(const ServiceReferenceU& reference) { if (!reference) { - throw std::invalid_argument("Default constructed ServiceReference is not a valid input to getService()"); + throw std::invalid_argument("Default constructed ServiceReference is not a valid input to GetService()"); } - ServiceReference internalRef(reference); - return internalRef.d->GetService(d->module->q); + return reference.d->GetServiceInterfaceMap(d->module->q); } -bool ModuleContext::UngetService(const ServiceReference& reference) +bool ModuleContext::UngetService(const ServiceReferenceBase& reference) { - ServiceReference ref = reference; + ServiceReferenceBase 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/CppMicroServices/src/module/usModuleContext.h similarity index 67% rename from Core/Code/CppMicroServices/src/module/usModuleContext.h rename to Core/CppMicroServices/src/module/usModuleContext.h index 0138a27842..0ec6aaaabb 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleContext.h +++ b/Core/CppMicroServices/src/module/usModuleContext.h @@ -1,649 +1,831 @@ /*============================================================================= 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_ +// TODO: Replace includes with forward directives! + #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; +class ServiceFactory; + +template class ServiceObjects; /** * \ingroup MicroServices * * A module's execution context within the framework. The context is used to * grant access to other methods so that this module can interact with the * Micro Services Framework. * *

* ModuleContext methods allow a module to: *

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

* A ModuleContext object will be created and provided to the * module associated with this context when it is loaded using the * {@link ModuleActivator::Load} method. The same ModuleContext * 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. + * ServiceFactory or PrototypeServiceFactory interface to have more + * flexibility in providing service objects to other modules. * *

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

    *
  1. The framework adds the following service properties to the service * properties from the specified ServiceProperties (which may be * omitted):
    * A property named ServiceConstants#SERVICE_ID() identifying the * registration number of the service
    * A property named ServiceConstants#OBJECTCLASS() containing all the * specified classes.
    + * A property named ServiceConstants#SERVICE_SCOPE() identifying the scope + * of the service.
    * Properties with these names in the specified ServiceProperties will * be ignored. *
  2. The service is added to the framework service registry and may now be * used by other modules. *
  3. A service event of type ServiceEvent#REGISTERED is fired. *
  4. A ServiceRegistration object for this registration is * returned. *
* - * @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. + * @note This is a low-level method and should normally not be used directly. + * Use one of the templated RegisterService methods instead. + * + * @param service The service object, which is a map of interface identifiers + * to raw service pointers. * @param properties The properties for this service. The keys in the * properties object must all be std::string objects. See * {@link ServiceConstants} for a list of standard service property keys. * 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 + * @see PrototypeServiceFactory */ - ServiceRegistration RegisterService(const std::list& clazzes, - US_BASECLASS_NAME* service, - const ServiceProperties& properties = ServiceProperties()); + ServiceRegistrationU RegisterService(const InterfaceMap& service, + const ServiceProperties& properties = ServiceProperties()); /** * Registers the specified service object with the specified properties - * under the specified class name with the framework. + * using the specified template argument 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. + * This method is provided as a convenience when service will only be registered under + * a single class name whose type is available to the caller. It is otherwise identical to + * RegisterService(const InterfaceMap&, const ServiceProperties&) but should be preferred + * since it avoids errors in the string literal identifying the class name or interface identifier. + * + * Example usage: + * \snippet uServices-registration/main.cpp 1-1 + * \snippet uServices-registration/main.cpp 1-2 * - * @param clazz The class name under which the service can be located. + * @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 std:list<std::string>&, us::Base*, const ServiceProperties&) + * @throws ServiceException If the service type \c S is invalid or the + * \c service object is NULL. + * + * @see RegisterService(const InterfaceMap&, const ServiceProperties&) */ - ServiceRegistration RegisterService(const char* clazz, US_BASECLASS_NAME* service, - const ServiceProperties& properties = ServiceProperties()); + template + ServiceRegistration RegisterService(S* service, const ServiceProperties& properties = ServiceProperties()) + { + InterfaceMap servicePointers = MakeInterfaceMap(service); + return RegisterService(servicePointers, properties); + } /** * Registers the specified service object with the specified properties * using the specified template argument with the framework. * *

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

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

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

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

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

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

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

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

    *
  • If the specified class name, clazz, is not * empty, the service must have been registered with the * specified class name. The complete list of class names with which a * service was registered is available from the service's * {@link ServiceConstants#OBJECTCLASS() objectClass} property. *
  • 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()); + std::vector GetServiceReferences(const std::string& clazz, const std::string& filter = std::string()); /** * Returns a list of ServiceReference objects. The returned * list contains services that * were registered under the interface id of the template argument S * and match the specified filter expression. * *

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

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

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

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

* 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); + ServiceReferenceU GetServiceReference(const std::string& clazz); /** * Returns a ServiceReference object for a service that * implements and was registered under the specified template class argument. * *

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

* A module's use of a service is tracked by the module's use count of that * service. Each time a service's service object is returned by - * {@link #GetService(const ServiceReference&)} the context module's use count for + * {@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 + * {@link #UngetService(const ServiceReferenceBase&)} the context module's use count * for that service is decremented by one. *

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

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

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

    *
  1. If the service has been unregistered, 0 is returned. *
  2. The context module's use count for this service is incremented by * one. *
  3. If the context module's use count for the service is currently one * and the service was registered with an object implementing the * ServiceFactory interface, the * {@link ServiceFactory::GetService} method is * 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&) + * ServiceReferenceBase is invalid (default constructed). + * @see #UngetService(const ServiceReferenceBase&) * @see ServiceFactory */ - US_BASECLASS_NAME* GetService(const ServiceReference& reference); + void* GetService(const ServiceReferenceBase& reference); + + InterfaceMap GetService(const ServiceReferenceU& reference); /** * Returns the service object referenced by the specified * ServiceReference object. *

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

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

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

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

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

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

* The callback is called if the filter criteria is met. To filter based * upon the class of the service, the filter should reference the * ServiceConstants#OBJECTCLASS() property. If filter is * 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/CppMicroServices/src/module/usModuleEvent.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleEvent.cpp rename to Core/CppMicroServices/src/module/usModuleEvent.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleEvent.h b/Core/CppMicroServices/src/module/usModuleEvent.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleEvent.h rename to Core/CppMicroServices/src/module/usModuleEvent.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleImport.h b/Core/CppMicroServices/src/module/usModuleImport.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleImport.h rename to Core/CppMicroServices/src/module/usModuleImport.h diff --git a/Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp b/Core/CppMicroServices/src/module/usModuleInfo.cpp similarity index 83% copy from Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp copy to Core/CppMicroServices/src/module/usModuleInfo.cpp index 6f81242b11..804c133c8a 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp +++ b/Core/CppMicroServices/src/module/usModuleInfo.cpp @@ -1,31 +1,34 @@ /*============================================================================= 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 "usModuleInfo.h" US_BEGIN_NAMESPACE -struct TestModuleAL2_Dummy -{ -}; +ModuleInfo::ModuleInfo(const std::string& name, const std::string& libName) + : name(name) + , libName(libName) + , id(0) + , activatorHook(NULL) +{} US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/src/module/usModuleInfo.h b/Core/CppMicroServices/src/module/usModuleInfo.h similarity index 92% rename from Core/Code/CppMicroServices/src/module/usModuleInfo.h rename to Core/CppMicroServices/src/module/usModuleInfo.h index da9da07803..6d73321982 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleInfo.h +++ b/Core/CppMicroServices/src/module/usModuleInfo.h @@ -1,80 +1,77 @@ /*============================================================================= 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); + ModuleInfo(const std::string& name, const std::string& libName); 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/CppMicroServices/src/module/usModuleInitialization.h similarity index 74% rename from Core/Code/CppMicroServices/src/module/usModuleInitialization.h rename to Core/CppMicroServices/src/module/usModuleInitialization.h index 96b9a60b8f..b0df114839 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleInitialization.h +++ b/Core/CppMicroServices/src/module/usModuleInitialization.h @@ -1,170 +1,170 @@ /*============================================================================= 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. + * has to put a call to this macro in one of its source files. * - * Example call for a module with file-name "libmylibname.so". + * Example call for a module with file-name "libmylibname.so": * \code - * US_INITIALIZE_MODULE("My Service Implementation", "mylibname", "", "1.0.0") + * US_INITIALIZE_MODULE("My Service Implementation", "mylibname") * \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 + * \sa MicroServices_AutoLoading * * \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. * + * \note If you want to create initialization code for an executable, see + * #US_INITIALIZE_EXECUTABLE. */ -#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) \ +#define US_INITIALIZE_MODULE(_module_name, _module_libname) \ 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)) \ +US_GLOBAL_STATIC_WITH_ARGS(ModuleInfo, moduleInfo, (_module_name, _module_libname)) \ \ /* 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() \ { \ + ModuleInfo*(*moduleInfoPtr)() = moduleInfo; \ std::string location = ModuleUtils::GetLibraryPath(moduleInfo()->libName, \ - reinterpret_cast(moduleInfo)); \ + *reinterpret_cast(&moduleInfoPtr)); \ 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())); \ + *reinterpret_cast(&moduleInfo()->activatorHook) = 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; +/** + * \ingroup MicroServices + * + * \brief Creates initialization code for an executable. + * + * Each executable which wants to register itself with the CppMicroServices library + * has to put a call to this macro in one of its source files. This ensures that the + * executable will get its own ModuleContext instance and can access the service registry. + * + * Example call for an executable: + * \code + * US_INITIALIZE_EXECUTABLE("my_executable") + * \endcode + * + * This will initialize the executable for use with the CppMicroServices library, using a default + * auto-load directory named after the provided executable id in \c _executable_id. + * + * \sa MicroServices_AutoLoading + * + * \remarks If you are using CMake, consider using the provided CMake macro + * usFunctionGenerateExecutableInit(). + * + * \param _executable_id A valid C identifier for the executable (no spaces etc.). + */ +#define US_INITIALIZE_EXECUTABLE(_executable_id) \ + US_INITIALIZE_MODULE(_executable_id, "") + +// If the CppMicroServices library was statically build, executables will share the +// initialization code with the CppMicroServices library. +#ifndef US_BUILD_SHARED_LIBS +#undef US_INITIALIZE_EXECUTABLE +#define US_INITIALIZE_EXECUTABLE(_a) +#endif + // 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) +#undef US_INITIALIZE_MODULE +#define US_INITIALIZE_MODULE(_a,_b) #endif #endif // USMODULEINITIALIZATION_H diff --git a/Core/CppMicroServices/src/module/usModuleManifest.cpp b/Core/CppMicroServices/src/module/usModuleManifest.cpp new file mode 100644 index 0000000000..7a2dde83c2 --- /dev/null +++ b/Core/CppMicroServices/src/module/usModuleManifest.cpp @@ -0,0 +1,142 @@ +/*============================================================================= + + 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 "usModuleManifest_p.h" + +#include + +US_BEGIN_NAMESPACE + +ModuleManifest::ModuleManifest() +{ +} + +void ModuleManifest::Parse(std::istream& is) +{ + Json::Value root; + Json::Reader jsonReader(Json::Features::strictMode()); + if (!jsonReader.parse(is, root, false)) + { + throw std::runtime_error(jsonReader.getFormattedErrorMessages()); + } + + if (!root.isObject()) + { + throw std::runtime_error("The Json root element must be an object."); + } + + ParseJsonObject(root, m_Properties); +} + +Any ModuleManifest::ParseJsonValue(const Json::Value& jsonValue) +{ + if (jsonValue.isObject()) + { + Any any = AnyMap(); + ParseJsonObject(jsonValue, ref_any_cast(any)); + return any; + } + else if (jsonValue.isArray()) + { + Any any = AnyVector(); + ParseJsonArray(jsonValue, ref_any_cast(any)); + return any; + } + else if (jsonValue.isString()) + { + return Any(jsonValue.asString()); + } + else if (jsonValue.isBool()) + { + return Any(jsonValue.asBool()); + } + else if (jsonValue.isDouble()) + { + return Any(jsonValue.asDouble()); + } + else if (jsonValue.isIntegral()) + { + return Any(jsonValue.asInt()); + } + + return Any(); +} + +void ModuleManifest::ParseJsonObject(const Json::Value& jsonObject, std::map& anyMap) +{ + for (Json::Value::const_iterator it = jsonObject.begin(); + it != jsonObject.end(); ++it) + { + const Json::Value& jsonValue = *it; + Any anyValue = ParseJsonValue(jsonValue); + if (!anyValue.Empty()) + { + anyMap.insert(std::make_pair(it.memberName(), anyValue)); + } + } +} + +void ModuleManifest::ParseJsonArray(const Json::Value& jsonArray, ModuleManifest::AnyVector& anyVector) +{ + for (Json::Value::const_iterator it = jsonArray.begin(); + it != jsonArray.end(); ++it) + { + const Json::Value& jsonValue = *it; + Any anyValue = ParseJsonValue(jsonValue); + if (!anyValue.Empty()) + { + anyVector.push_back(anyValue); + } + } +} + +bool ModuleManifest::Contains(const std::string& key) const +{ + return m_Properties.count(key) > 0; +} + +Any ModuleManifest::GetValue(const std::string& key) const +{ + AnyMap::const_iterator iter = m_Properties.find(key); + if (iter != m_Properties.end()) + { + return iter->second; + } + return Any(); +} + +std::vector ModuleManifest::GetKeys() const +{ + std::vector keys; + for (AnyMap::const_iterator iter = m_Properties.begin(); + iter != m_Properties.end(); ++iter) + { + keys.push_back(iter->first); + } + return keys; +} + +void ModuleManifest::SetValue(const std::string& key, const Any& value) +{ + m_Properties[key] = value; +} + +US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.h b/Core/CppMicroServices/src/module/usModuleManifest_p.h similarity index 56% rename from Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.h rename to Core/CppMicroServices/src/module/usModuleManifest_p.h index 80b1faa73b..670094b070 100644 --- a/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.h +++ b/Core/CppMicroServices/src/module/usModuleManifest_p.h @@ -1,68 +1,62 @@ /*============================================================================= 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 +#ifndef USMODULEMANIFEST_P_H +#define USMODULEMANIFEST_P_H -#include "usConfig.h" +#include "usAny.h" -#include +#include "json_p.h" US_BEGIN_NAMESPACE -class SharedLibraryHandle +class ModuleManifest { public: - SharedLibraryHandle(); + ModuleManifest(); - SharedLibraryHandle(const std::string& name); + void Parse(std::istream& is); - virtual ~SharedLibraryHandle(); + bool Contains(const std::string& key) const; - void Load(); + Any GetValue(const std::string& key) const; - void Load(const std::string& name); + std::vector GetKeys() const; - void Unload(); + void SetValue(const std::string& key, const Any& value); - std::string GetAbsolutePath(const std::string& name); - - std::string GetAbsolutePath(); - - static std::string GetLibraryPath(); - - static std::string Suffix(); +private: - static std::string Prefix(); + typedef std::map AnyMap; + typedef std::vector AnyVector; -private: + Any ParseJsonValue(const Json::Value& jsonValue); - SharedLibraryHandle(const SharedLibraryHandle&); - SharedLibraryHandle& operator = (const SharedLibraryHandle&); + void ParseJsonObject(const Json::Value& jsonObject, AnyMap& anyMap); + void ParseJsonArray(const Json::Value& jsonArray, AnyVector& anyVector); - std::string m_Name; - void* m_Handle; + AnyMap m_Properties; }; US_END_NAMESPACE -#endif // USTESTUTILSHAREDLIBRARY_H +#endif // USMODULEMANIFEST_P_H diff --git a/Core/Code/CppMicroServices/src/module/usModulePrivate.cpp b/Core/CppMicroServices/src/module/usModulePrivate.cpp similarity index 70% rename from Core/Code/CppMicroServices/src/module/usModulePrivate.cpp rename to Core/CppMicroServices/src/module/usModulePrivate.cpp index 77e10d4464..6c99393e4a 100644 --- a/Core/Code/CppMicroServices/src/module/usModulePrivate.cpp +++ b/Core/CppMicroServices/src/module/usModulePrivate.cpp @@ -1,248 +1,267 @@ /*============================================================================= 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 "usModuleResource.h" +#include "usModuleResourceStream.h" #include "usCoreModuleContext_p.h" #include "usServiceRegistration.h" -#include "usServiceReferencePrivate.h" +#include "usServiceReferenceBasePrivate.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) + // Check if the module provides a manifest.json file and if yes, parse it. + ModuleResource manifestRes; + std::map::iterator resourceTreeIter = mapLibNameToResourceTrees.find(this->info.libName); + if (resourceTreeIter != mapLibNameToResourceTrees.end() && resourceTreeIter->second->IsValid()) { - std::string moduleDep; - ss >> moduleDep; - if (!moduleDep.empty()) + manifestRes = ModuleResource("/manifest.json", resourceTreeIter->second, resourceTreePtrs); + if (manifestRes) { - Module* dep = ModuleRegistry::GetModule(moduleDep); - if (dep) + ModuleResourceStream manifestStream(manifestRes); + try { - requiresIds.push_back(dep->GetModuleId()); - if (counter > 0) propModuleDepends << ", "; - propModuleDepends << moduleDep; - ++counter; + moduleManifest.Parse(manifestStream); } - else + catch (const std::exception& e) { - requiresLibs.push_back(moduleDep); - if (counter2 > 0) propLibDepends << ", "; - propLibDepends << moduleDep; - ++counter2; + US_ERROR << "Parsing of manifest.json for module " << info->location << " failed: " << e.what(); } } } - properties[Module::PROP_MODULE_DEPENDS()] = propModuleDepends.str(); - properties[Module::PROP_LIB_DEPENDS()] = propLibDepends.str(); - - if (!this->info.version.empty()) + // Check if we got version information and validate the version identifier + if (moduleManifest.Contains(Module::PROP_VERSION())) { + Any versionAny = moduleManifest.GetValue(Module::PROP_VERSION()); + std::string errMsg; + if (versionAny.Type() != typeid(std::string)) + { + errMsg = std::string("The version identifier must be a string"); + } try { - version = ModuleVersion(this->info.version); - properties[Module::PROP_VERSION()] = this->info.version; + version = ModuleVersion(versionAny.ToString()); } catch (const std::exception& e) { - throw std::invalid_argument(std::string("CppMicroServices module does not specify a valid version identifier. Got exception: ") + e.what()); + errMsg = std::string("The version identifier is invalid: ") + e.what(); + } + + if (!errMsg.empty()) + { + throw std::invalid_argument(std::string("The Json value for ") + Module::PROP_VERSION() + " for module " + + info->location + " is not valid: " + errMsg); } } - properties[Module::PROP_LOCATION()] = this->info.location; - properties[Module::PROP_NAME()] = this->info.name; + std::stringstream propId; + propId << this->info.id; + moduleManifest.SetValue(Module::PROP_ID(), propId.str()); + moduleManifest.SetValue(Module::PROP_LOCATION(), this->info.location); + moduleManifest.SetValue(Module::PROP_NAME(), this->info.name); + + if (moduleManifest.Contains(Module::PROP_AUTOLOAD_DIR())) + { + this->info.autoLoadDir = moduleManifest.GetValue(Module::PROP_AUTOLOAD_DIR()).ToString(); + } + else + { + // default to the library name or a special name for executables + if (!this->info.libName.empty()) + { + this->info.autoLoadDir = this->info.libName; + moduleManifest.SetValue(Module::PROP_AUTOLOAD_DIR(), Any(this->info.autoLoadDir)); + } + else + { + this->info.autoLoadDir = "main"; + moduleManifest.SetValue(Module::PROP_AUTOLOAD_DIR(), Any(this->info.autoLoadDir)); + } + } } 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; + std::vector srs; coreCtx->services.GetRegisteredByModule(this, srs); - for (std::list::iterator i = srs.begin(); + for (std::vector::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(); + for (std::vector::const_iterator i = srs.begin(); i != srs.end(); ++i) { - i->GetReference().d->UngetService(q, false); + i->GetReference(std::string()).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])); + mapLibNameToResourceTrees[moduleLibNames[i]] = resourceTreePtrs.back(); } } US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/src/module/usModulePrivate.h b/Core/CppMicroServices/src/module/usModulePrivate.h similarity index 94% rename from Core/Code/CppMicroServices/src/module/usModulePrivate.h rename to Core/CppMicroServices/src/module/usModulePrivate.h index 6d1f4e4a07..62af04b714 100644 --- a/Core/Code/CppMicroServices/src/module/usModulePrivate.h +++ b/Core/CppMicroServices/src/module/usModulePrivate.h @@ -1,105 +1,103 @@ /*============================================================================= 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 "usModuleManifest_p.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; + std::map mapLibNameToResourceTrees; /** * ModuleContext for the module */ ModuleContext* moduleContext; ModuleActivator* moduleActivator; - std::map properties; + ModuleManifest moduleManifest; 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/CppMicroServices/src/module/usModuleRegistry.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleRegistry.cpp rename to Core/CppMicroServices/src/module/usModuleRegistry.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleRegistry.h b/Core/CppMicroServices/src/module/usModuleRegistry.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleRegistry.h rename to Core/CppMicroServices/src/module/usModuleRegistry.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleResource.cpp b/Core/CppMicroServices/src/module/usModuleResource.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResource.cpp rename to Core/CppMicroServices/src/module/usModuleResource.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleResource.h b/Core/CppMicroServices/src/module/usModuleResource.h similarity index 98% rename from Core/Code/CppMicroServices/src/module/usModuleResource.h rename to Core/CppMicroServices/src/module/usModuleResource.h index 9c6f4e9ec9..abfe1370a7 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleResource.h +++ b/Core/CppMicroServices/src/module/usModuleResource.h @@ -1,304 +1,305 @@ /*============================================================================= 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. + * Returns the resource path including the file name. * - * @return The resource path include the name. + * @return The resource path including the file 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; + friend class ModulePrivate; 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/CppMicroServices/src/module/usModuleResourceBuffer.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResourceBuffer.cpp rename to Core/CppMicroServices/src/module/usModuleResourceBuffer.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceBuffer_p.h b/Core/CppMicroServices/src/module/usModuleResourceBuffer_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResourceBuffer_p.h rename to Core/CppMicroServices/src/module/usModuleResourceBuffer_p.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceStream.cpp b/Core/CppMicroServices/src/module/usModuleResourceStream.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResourceStream.cpp rename to Core/CppMicroServices/src/module/usModuleResourceStream.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceStream.h b/Core/CppMicroServices/src/module/usModuleResourceStream.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResourceStream.h rename to Core/CppMicroServices/src/module/usModuleResourceStream.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceTree.cpp b/Core/CppMicroServices/src/module/usModuleResourceTree.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResourceTree.cpp rename to Core/CppMicroServices/src/module/usModuleResourceTree.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceTree_p.h b/Core/CppMicroServices/src/module/usModuleResourceTree_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResourceTree_p.h rename to Core/CppMicroServices/src/module/usModuleResourceTree_p.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleSettings.cpp b/Core/CppMicroServices/src/module/usModuleSettings.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleSettings.cpp rename to Core/CppMicroServices/src/module/usModuleSettings.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleSettings.h b/Core/CppMicroServices/src/module/usModuleSettings.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleSettings.h rename to Core/CppMicroServices/src/module/usModuleSettings.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleUtils.cpp b/Core/CppMicroServices/src/module/usModuleUtils.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleUtils.cpp rename to Core/CppMicroServices/src/module/usModuleUtils.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleUtils_p.h b/Core/CppMicroServices/src/module/usModuleUtils_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleUtils_p.h rename to Core/CppMicroServices/src/module/usModuleUtils_p.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleVersion.cpp b/Core/CppMicroServices/src/module/usModuleVersion.cpp similarity index 98% rename from Core/Code/CppMicroServices/src/module/usModuleVersion.cpp rename to Core/CppMicroServices/src/module/usModuleVersion.cpp index 53550b3ea2..f27640943b 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleVersion.cpp +++ b/Core/CppMicroServices/src/module/usModuleVersion.cpp @@ -1,276 +1,275 @@ /*============================================================================= 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); + std::stringstream ss; ss << majorVersion << SEPARATOR << minorVersion << SEPARATOR << microVersion; if (!qualifier.empty()) { ss << SEPARATOR << qualifier; } - return result; + return ss.str(); } 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/CppMicroServices/src/module/usModuleVersion.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleVersion.h rename to Core/CppMicroServices/src/module/usModuleVersion.h diff --git a/Core/CppMicroServices/src/resources/manifest.json b/Core/CppMicroServices/src/resources/manifest.json new file mode 100644 index 0000000000..b2359aec43 --- /dev/null +++ b/Core/CppMicroServices/src/resources/manifest.json @@ -0,0 +1 @@ +{ "module.version" : "1.99.0" } diff --git a/Core/Code/CppMicroServices/src/service/usLDAPExpr.cpp b/Core/CppMicroServices/src/service/usLDAPExpr.cpp similarity index 85% rename from Core/Code/CppMicroServices/src/service/usLDAPExpr.cpp rename to Core/CppMicroServices/src/service/usLDAPExpr.cpp index 42ffde8884..9d304b8328 100644 --- a/Core/Code/CppMicroServices/src/service/usLDAPExpr.cpp +++ b/Core/CppMicroServices/src/service/usLDAPExpr.cpp @@ -1,777 +1,822 @@ /*============================================================================= 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 "usAny.h" +#include "usServicePropertiesImpl_p.h" + #include #include #include #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 (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 ) +bool LDAPExpr::Query( const std::string& filter, const ServicePropertiesImpl& pd) { return LDAPExpr(filter).Evaluate(pd, false); } -bool LDAPExpr::Evaluate( const ServiceProperties& p, bool matchCase ) const +bool LDAPExpr::Evaluate( const ServicePropertiesImpl& 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); + // try case sensitive match first + int index = p.FindCaseSensitive(d->m_attrName); + if (index < 0 && !matchCase) index = p.Find(d->m_attrName); + return index < 0 ? false : Compare(p.Value(index), 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)) + else if (objType == typeid(short)) { - 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; - } + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(int)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(long int)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(long long int)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(unsigned char)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(unsigned short)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(unsigned int)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(unsigned long int)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(unsigned long long int)) + { + return CompareIntegralType(obj, op, s); } else if (objType == typeid(float)) { - float sFloat; - std::stringstream ss(s); - ss >> sFloat; - float floatVal = any_cast(obj); + errno = 0; + char* endptr = 0; + double sFloat = strtod(s.c_str(), &endptr); + if ((errno == ERANGE && (sFloat == 0 || sFloat == HUGE_VAL || sFloat == -HUGE_VAL)) || + (errno != 0 && sFloat == 0) || endptr == s.c_str()) + { + return false; + } + + double floatVal = static_cast(any_cast(obj)); switch(op) { case LE: return floatVal <= sFloat; case GE: return floatVal >= sFloat; default: /*APPROX and EQ*/ - float diff = floatVal - sFloat; + double 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; + errno = 0; + char* endptr = 0; + double sDouble = strtod(s.c_str(), &endptr); + if ((errno == ERANGE && (sDouble == 0 || sDouble == HUGE_VAL || sDouble == -HUGE_VAL)) || + (errno != 0 && sDouble == 0) || endptr == s.c_str()) + { + return false; + } + 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; } +template +bool LDAPExpr::CompareIntegralType(const Any& obj, const int op, const std::string& s) const +{ + errno = 0; + char* endptr = 0; + long longInt = strtol(s.c_str(), &endptr, 10); + if ((errno == ERANGE && (longInt == std::numeric_limits::max() || longInt == std::numeric_limits::min())) || + (errno != 0 && longInt == 0) || endptr == s.c_str()) + { + return false; + } + + T sInt = static_cast(longInt); + T intVal = any_cast(obj); + + switch(op) + { + case LE: + return intVal <= sInt; + case GE: + return intVal >= sInt; + default: /*APPROX and EQ*/ + return intVal == sInt; + } +} + 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; + sb.reserve(s.size()); 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/CppMicroServices/src/service/usLDAPExpr_p.h similarity index 95% rename from Core/Code/CppMicroServices/src/service/usLDAPExpr_p.h rename to Core/CppMicroServices/src/service/usLDAPExpr_p.h index d6dcb67d10..2791c08a2d 100644 --- a/Core/Code/CppMicroServices/src/service/usLDAPExpr_p.h +++ b/Core/CppMicroServices/src/service/usLDAPExpr_p.h @@ -1,183 +1,188 @@ /*============================================================================= 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 Any; class LDAPExprData; +class ServicePropertiesImpl; /** * 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); + static bool Query(const std::string& filter, const ServicePropertiesImpl& pd); //! Evaluate this LDAP filter. - bool Evaluate(const ServiceProperties& p, bool matchCase) const; + bool Evaluate(const ServicePropertiesImpl& 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; + //! + template + bool CompareIntegralType(const Any& obj, const 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/CppMicroServices/src/service/usLDAPFilter.cpp similarity index 87% rename from Core/Code/CppMicroServices/src/service/usLDAPFilter.cpp rename to Core/CppMicroServices/src/service/usLDAPFilter.cpp index c8a94d656e..36d124e656 100644 --- a/Core/Code/CppMicroServices/src/service/usLDAPFilter.cpp +++ b/Core/CppMicroServices/src/service/usLDAPFilter.cpp @@ -1,119 +1,121 @@ /*============================================================================= 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 "usServicePropertiesImpl_p.h" +#include "usServiceReference.h" +#include "usServiceReferenceBasePrivate.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 +bool LDAPFilter::Match(const ServiceReferenceBase& reference) const { return d->ldapExpr.Evaluate(reference.d->GetProperties(), true); } bool LDAPFilter::Match(const ServiceProperties& dictionary) const { - return d->ldapExpr.Evaluate(dictionary, false); + return d->ldapExpr.Evaluate(ServicePropertiesImpl(dictionary), false); } bool LDAPFilter::MatchCase(const ServiceProperties& dictionary) const { - return d->ldapExpr.Evaluate(dictionary, true); + return d->ldapExpr.Evaluate(ServicePropertiesImpl(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/CppMicroServices/src/service/usLDAPFilter.h similarity index 98% rename from Core/Code/CppMicroServices/src/service/usLDAPFilter.h rename to Core/CppMicroServices/src/service/usLDAPFilter.h index c8355fc3be..d8df499a70 100644 --- a/Core/Code/CppMicroServices/src/service/usLDAPFilter.h +++ b/Core/CppMicroServices/src/service/usLDAPFilter.h @@ -1,174 +1,174 @@ /*============================================================================= 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; +class ServiceReferenceBase; /** * \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; + bool Match(const ServiceReferenceBase& 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/CppMicroServices/src/service/usPrototypeServiceFactory.h b/Core/CppMicroServices/src/service/usPrototypeServiceFactory.h new file mode 100644 index 0000000000..080f1fe286 --- /dev/null +++ b/Core/CppMicroServices/src/service/usPrototypeServiceFactory.h @@ -0,0 +1,102 @@ +/*============================================================================= + + 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 USPROTOTYPESERVICEFACTORY_H +#define USPROTOTYPESERVICEFACTORY_H + +#include + +US_BEGIN_NAMESPACE + +/** + * @ingroup MicroServices + * + * A factory for \link ServiceConstants::SCOPE_PROTOTYPE prototype scope\endlink services. + * The factory can provide multiple, unique service objects. + * + * When registering a service, a PrototypeServiceFactory object can be used + * instead of a service object, so that the module developer can create a + * unique service object for each caller that is using the service. + * When a caller uses a ServiceObjects to request a service instance, the + * framework calls the GetService method to return a service object specifically + * for the requesting caller. The caller can release the returned service object + * and the framework will call the UngetService method with the service object. + * When a module uses the ModuleContext::GetService(const ServiceReferenceBase&) + * method to obtain a service object, the framework acts as if the service + * has module scope. That is, the framework will call the GetService method to + * obtain a module-scoped instance which will be cached and have a use count. + * See ServiceFactory. + * + * A module can use both ServiceObjects and ModuleContext::GetService(const ServiceReferenceBase&) + * to obtain a service object for a service. ServiceObjects::GetService() will always + * return an instance provided by a call to GetService(Module*, const ServiceRegistrationBase&) + * and ModuleContext::GetService(const ServiceReferenceBase&) will always + * return the module-scoped instance. + * PrototypeServiceFactory objects are only used by the framework and are not made + * available to other modules. The framework may concurrently call a PrototypeServiceFactory. + * + * @see ModuleContext::GetServiceObjects() + * @see ServiceObjects + */ +struct PrototypeServiceFactory : public ServiceFactory +{ + + /** + * Returns a service object for a caller. + * + * The framework invokes this method for each caller requesting a service object using + * ServiceObjects::GetService(). The factory can then return a specific service object for the caller. + * The framework checks that the returned service object is valid. If the returned service + * object is empty or does not contain entries for all the interfaces named when the service + * was registered, a warning is issued and NULL is returned to the caller. If this + * method throws an exception, a warning is issued and NULL is returned to the caller. + * + * @param module The module requesting the service. + * @param registration The ServiceRegistrationBase object for the requested service. + * @return A service object that must contain entries for all the interfaces named when + * the service was registered. + * + * @see ServiceObjects#GetService() + * @see InterfaceMap + */ + virtual InterfaceMap GetService(Module* module, const ServiceRegistrationBase& registration) = 0; + + /** + * Releases a service object created for a caller. + * + * The framework invokes this method when a service has been released by a modules such as + * by calling ServiceObjects::UngetService(). The service object may then be destroyed. + * If this method throws an exception, a warning is issued. + * + * @param module The module releasing the service. + * @param registration The ServiceRegistrationBase object for the service being released. + * @param service The service object returned by a previous call to the GetService method. + * + * @see ServiceObjects::UngetService() + */ + virtual void UngetService(Module* module, const ServiceRegistrationBase& registration, + const InterfaceMap& service) = 0; + +}; + +US_END_NAMESPACE + +#endif // USPROTOTYPESERVICEFACTORY_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceEvent.cpp b/Core/CppMicroServices/src/service/usServiceEvent.cpp similarity index 89% rename from Core/Code/CppMicroServices/src/service/usServiceEvent.cpp rename to Core/CppMicroServices/src/service/usServiceEvent.cpp index 7582409df8..e1b88f64f4 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceEvent.cpp +++ b/Core/CppMicroServices/src/service/usServiceEvent.cpp @@ -1,132 +1,132 @@ /*============================================================================= 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) + ServiceEventData(const ServiceEvent::Type& type, const ServiceReferenceBase& reference) : type(type), reference(reference) { } ServiceEventData(const ServiceEventData& other) : SharedData(other), type(other.type), reference(other.reference) { } const ServiceEvent::Type type; - const ServiceReference reference; + const ServiceReferenceBase 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) +ServiceEvent::ServiceEvent(Type type, const ServiceReferenceBase& 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 +ServiceReferenceU 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(); + ServiceReferenceU 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 << ")"; + os << " objectClass=" << classes.ToString() << ")"; } return os; } diff --git a/Core/Code/CppMicroServices/src/service/usServiceEvent.h b/Core/CppMicroServices/src/service/usServiceEvent.h similarity index 95% rename from Core/Code/CppMicroServices/src/service/usServiceEvent.h rename to Core/CppMicroServices/src/service/usServiceEvent.h index 1d181deed2..f5e2d45b17 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceEvent.h +++ b/Core/CppMicroServices/src/service/usServiceEvent.h @@ -1,191 +1,197 @@ /*============================================================================= 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(Type type, const ServiceReferenceBase& 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; + ServiceReferenceU GetServiceReference() const; + + template + ServiceReference GetServiceReference(InterfaceT) const + { + return GetServiceReference(); + } /** * 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/CppMicroServices/src/service/usServiceException.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/service/usServiceException.cpp rename to Core/CppMicroServices/src/service/usServiceException.cpp diff --git a/Core/Code/CppMicroServices/src/service/usServiceException.h b/Core/CppMicroServices/src/service/usServiceException.h similarity index 100% rename from Core/Code/CppMicroServices/src/service/usServiceException.h rename to Core/CppMicroServices/src/service/usServiceException.h diff --git a/Core/Code/CppMicroServices/src/service/usServiceFactory.h b/Core/CppMicroServices/src/service/usServiceFactory.h similarity index 76% rename from Core/Code/CppMicroServices/src/service/usServiceFactory.h rename to Core/CppMicroServices/src/service/usServiceFactory.h index 84c589e768..0d8076ae6d 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceFactory.h +++ b/Core/CppMicroServices/src/service/usServiceFactory.h @@ -1,111 +1,119 @@ /*============================================================================= 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 USSERVICEFACTORY_H +#define USSERVICEFACTORY_H +#include "usServiceInterface.h" #include "usServiceRegistration.h" US_BEGIN_NAMESPACE /** * \ingroup MicroServices * - * Allows services to provide customized service objects in the module - * environment. + * A factory for \link ServiceConstants::SCOPE_MODULE module scope\endlink services. + * The factory can provide service objects unique to each module. * *

* 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 + * @see PrototypeServiceFactory * @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 + * ModuleContext::GetService(const ServiceReferenceBase&) method. The * service factory can then return a specific service object for each * module. * *

- * The framework caches the value returned (unless it is 0), + * The framework caches the value returned (unless the InterfaceMap is empty), * 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 + * framework does 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 + * @param registration The ServiceRegistrationBase object for the * service. - * @return A service object that must be an instance of all - * the classes named when the service was registered. + * @return A service object that must contain entries for all + * the interfaces named when the service was registered. * @see ModuleContext#GetService + * @see InterfaceMap */ - virtual US_BASECLASS_NAME* GetService(Module* module, const ServiceRegistration& registration) = 0; + virtual InterfaceMap GetService(Module* module, const ServiceRegistrationBase& 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 + * @see InterfaceMap */ - virtual void UngetService(Module* module, const ServiceRegistration& registration, - US_BASECLASS_NAME* service) = 0; + virtual void UngetService(Module* module, const ServiceRegistrationBase& registration, + const InterfaceMap& service) = 0; }; US_END_NAMESPACE + +#endif // USSERVICEFACTORY_H diff --git a/Core/CppMicroServices/src/service/usServiceInterface.h b/Core/CppMicroServices/src/service/usServiceInterface.h new file mode 100644 index 0000000000..91efe207ff --- /dev/null +++ b/Core/CppMicroServices/src/service/usServiceInterface.h @@ -0,0 +1,342 @@ +/*============================================================================= + + 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 +#include + +#include +#include +#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(); + +/// \cond +template<> inline const char* us_service_interface_iid() { return ""; } +/// \endcond + +#if defined(QT_DEBUG) || defined(QT_NO_DEBUG) +#include + +#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 reinterpret_cast<_service_interface_type*>(object ? object->qt_metacast(_service_interface_id) : 0); } \ + template<> inline _service_interface_type* qobject_cast<_service_interface_type*>(const QObject* object) \ + { return reinterpret_cast<_service_interface_type*>(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 + +US_BEGIN_NAMESPACE + +class ServiceFactory; + +/** + * @ingroup MicroServices + * + * A helper type used in several methods to get proper + * method overload resolutions. + */ +template +struct InterfaceT {}; + +/** + * @ingroup MicroServices + * + * A map containing interfaces ids and their corresponding service object + * pointers. InterfaceMap instances represent a complete service object + * which implementes one or more service interfaces. For each implemented + * service interface, there is an entry in the map with the key being + * the service interface id and the value a pointer to the service + * interface implementation. + * + * To create InterfaceMap instances, use the MakeInterfaceMap helper class. + * + * @note This is a low-level type and should only rarely be used. + * + * @see MakeInterfaceMap + */ +typedef std::map InterfaceMap; + + +template +bool InsertInterfaceType(InterfaceMap& im, I* i) +{ + if (us_service_interface_iid() == NULL) + { + throw ServiceException(std::string("The interface class ") + typeid(I).name() + + " uses an invalid id in its US_DECLARE_SERVICE_INTERFACE macro call."); + } + im.insert(std::make_pair(std::string(us_service_interface_iid()), + static_cast(static_cast(i)))); + return true; +} + +template<> +inline bool InsertInterfaceType(InterfaceMap&, void*) +{ + return false; +} + + +/** + * @ingroup MicroServices + * + * Helper class for constructing InterfaceMap instances based + * on service implementations or service factories. + * + * Example usage: + * \code + * MyService service; // implementes I1 and I2 + * InterfaceMap im = MakeInterfaceMap(&service); + * \endcode + * + * The MakeInterfaceMap supports service implementations with + * up to three service interfaces. + * + * @see InterfaceMap + */ +template +struct MakeInterfaceMap +{ + ServiceFactory* m_factory; + I1* m_interface1; + I2* m_interface2; + I3* m_interface3; + + /** + * Constructor taking a service implementation pointer. + * + * @param impl A service implementation pointer, which must + * be castable to a all specified service interfaces. + */ + template + MakeInterfaceMap(Impl* impl) + : m_factory(NULL) + , m_interface1(static_cast(impl)) + , m_interface2(static_cast(impl)) + , m_interface3(static_cast(impl)) + {} + + /** + * Constructor taking a service factory. + * + * @param factory A service factory. + */ + MakeInterfaceMap(ServiceFactory* factory) + : m_factory(factory) + , m_interface1(NULL) + , m_interface2(NULL) + , m_interface3(NULL) + { + if (factory == NULL) + { + throw ServiceException("The service factory argument must not be NULL."); + } + } + + operator InterfaceMap () + { + InterfaceMap sim; + InsertInterfaceType(sim, m_interface1); + InsertInterfaceType(sim, m_interface2); + InsertInterfaceType(sim, m_interface3); + + if (m_factory) + { + sim.insert(std::make_pair(std::string("org.cppmicroservices.factory"), + static_cast(m_factory))); + } + + return sim; + } +}; + +/// \cond +template +struct MakeInterfaceMap +{ + ServiceFactory* m_factory; + I1* m_interface1; + I2* m_interface2; + + template + MakeInterfaceMap(Impl* impl) + : m_factory(NULL) + , m_interface1(static_cast(impl)) + , m_interface2(static_cast(impl)) + {} + + MakeInterfaceMap(ServiceFactory* factory) + : m_factory(factory) + , m_interface1(NULL) + , m_interface2(NULL) + { + if (factory == NULL) + { + throw ServiceException("The service factory argument must not be NULL."); + } + } + + operator InterfaceMap () + { + InterfaceMap sim; + InsertInterfaceType(sim, m_interface1); + InsertInterfaceType(sim, m_interface2); + + if (m_factory) + { + sim.insert(std::make_pair(std::string("org.cppmicroservices.factory"), + static_cast(m_factory))); + } + + return sim; + } +}; + +template +struct MakeInterfaceMap +{ + ServiceFactory* m_factory; + I1* m_interface1; + + template + MakeInterfaceMap(Impl* impl) + : m_factory(NULL) + , m_interface1(static_cast(impl)) + {} + + MakeInterfaceMap(ServiceFactory* factory) + : m_factory(factory) + , m_interface1(NULL) + { + if (factory == NULL) + { + throw ServiceException("The service factory argument must not be NULL."); + } + } + + operator InterfaceMap () + { + InterfaceMap sim; + InsertInterfaceType(sim, m_interface1); + + if (m_factory) + { + sim.insert(std::make_pair(std::string("org.cppmicroservices.factory"), + static_cast(m_factory))); + } + + return sim; + } +}; + +template<> +struct MakeInterfaceMap; +/// \endcond + +/** + * @ingroup MicroServices + * + * Extract a service interface pointer from a given InterfaceMap instance. + * + * @param map a InterfaceMap instance. + * @return The service interface pointer for the service interface id of the + * \c I1 interface type or NULL if \c map does not contain an entry + * for the given type. + * + * @see MakeInterfaceMap + */ +template +I1* ExtractInterface(const InterfaceMap& map) +{ + InterfaceMap::const_iterator iter = map.find(us_service_interface_iid()); + if (iter != map.end()) + { + return reinterpret_cast(iter->second); + } + return NULL; +} + +US_END_NAMESPACE + + +#endif // USSERVICEINTERFACE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceListenerEntry.cpp b/Core/CppMicroServices/src/service/usServiceListenerEntry.cpp similarity index 98% rename from Core/Code/CppMicroServices/src/service/usServiceListenerEntry.cpp rename to Core/CppMicroServices/src/service/usServiceListenerEntry.cpp index 9dab41cd6b..6dcb178ba0 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceListenerEntry.cpp +++ b/Core/CppMicroServices/src/service/usServiceListenerEntry.cpp @@ -1,150 +1,150 @@ /*============================================================================= 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 +const 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/CppMicroServices/src/service/usServiceListenerEntry_p.h similarity index 98% rename from Core/Code/CppMicroServices/src/service/usServiceListenerEntry_p.h rename to Core/CppMicroServices/src/service/usServiceListenerEntry_p.h index ebcf167272..8bedffe193 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceListenerEntry_p.h +++ b/Core/CppMicroServices/src/service/usServiceListenerEntry_p.h @@ -1,97 +1,97 @@ /*============================================================================= 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; + 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/CppMicroServices/src/service/usServiceListeners.cpp similarity index 95% rename from Core/Code/CppMicroServices/src/service/usServiceListeners.cpp rename to Core/CppMicroServices/src/service/usServiceListeners.cpp index c9036c83db..85df22931b 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceListeners.cpp +++ b/Core/CppMicroServices/src/service/usServiceListeners.cpp @@ -1,290 +1,290 @@ /*============================================================================= 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 "usServiceReferenceBasePrivate.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, +void ServiceListeners::GetMatchingServiceListeners(const ServiceReferenceBase& 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)) + const LDAPExpr& ldapExpr = sse->GetLDAPExpr(); + if (ldapExpr.IsNull() || + ldapExpr.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 > + const std::vector c(any_cast > (sr.d->GetProperty(ServiceConstants::OBJECTCLASS(), lockProps))); - for (std::list::const_iterator objClass = c.begin(); + for (std::vector::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/CppMicroServices/src/service/usServiceListeners_p.h similarity index 98% rename from Core/Code/CppMicroServices/src/service/usServiceListeners_p.h rename to Core/CppMicroServices/src/service/usServiceListeners_p.h index 771f45bc0c..0544b58ee3 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceListeners_p.h +++ b/Core/CppMicroServices/src/service/usServiceListeners_p.h @@ -1,176 +1,176 @@ /*============================================================================= 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, + void GetMatchingServiceListeners(const ServiceReferenceBase& 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/CppMicroServices/src/service/usServiceObjects.cpp b/Core/CppMicroServices/src/service/usServiceObjects.cpp new file mode 100644 index 0000000000..1595ec283d --- /dev/null +++ b/Core/CppMicroServices/src/service/usServiceObjects.cpp @@ -0,0 +1,209 @@ +/*============================================================================= + + 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 "usServiceObjects.h" + +#include "usServiceReferenceBasePrivate.h" + +#include + +US_BEGIN_NAMESPACE + +class ServiceObjectsBasePrivate +{ +public: + + AtomicInt ref; + + ModuleContext* m_context; + ServiceReferenceBase m_reference; + + // This is used by all ServiceObjects instances with S != void + std::map m_serviceInstances; + // This is used by ServiceObjects + std::set m_serviceInterfaceMaps; + + ServiceObjectsBasePrivate(ModuleContext* context, const ServiceReferenceBase& reference) + : m_context(context) + , m_reference(reference) + {} + + InterfaceMap GetServiceInterfaceMap() + { + InterfaceMap result; + + bool isPrototypeScope = m_reference.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == + ServiceConstants::SCOPE_PROTOTYPE(); + + if (isPrototypeScope) + { + result = m_reference.d->GetPrototypeService(m_context->GetModule()); + } + else + { + result = m_reference.d->GetServiceInterfaceMap(m_context->GetModule()); + } + + return result; + } +}; + +ServiceObjectsBase::ServiceObjectsBase(ModuleContext* context, const ServiceReferenceBase& reference) + : d(new ServiceObjectsBasePrivate(context, reference)) +{ + if (!reference) + { + delete d; + throw std::invalid_argument("The service reference is invalid"); + } +} + +void* ServiceObjectsBase::GetService() const +{ + if (!d->m_reference) + { + return NULL; + } + + InterfaceMap im = d->GetServiceInterfaceMap(); + void* result = im.find(d->m_reference.GetInterfaceId())->second; + + if (result) + { + d->m_serviceInstances.insert(std::make_pair(result, im)); + } + return result; +} + +InterfaceMap ServiceObjectsBase::GetServiceInterfaceMap() const +{ + InterfaceMap result; + if (!d->m_reference) + { + return result; + } + + result = d->GetServiceInterfaceMap(); + + if (!result.empty()) + { + d->m_serviceInterfaceMaps.insert(result); + } + return result; +} + +void ServiceObjectsBase::UngetService(void* service) +{ + if (service == NULL) + { + return; + } + + std::map::iterator serviceIter = d->m_serviceInstances.find(service); + if (serviceIter == d->m_serviceInstances.end()) + { + throw std::invalid_argument("The provided service has not been retrieved via this ServiceObjects instance"); + } + + if (!d->m_reference.d->UngetPrototypeService(d->m_context->GetModule(), serviceIter->second)) + { + US_WARN << "Ungetting service unsuccessful"; + } + else + { + d->m_serviceInstances.erase(serviceIter); + } +} + +void ServiceObjectsBase::UngetService(const InterfaceMap& interfaceMap) +{ + if (interfaceMap.empty()) + { + return; + } + + std::set::iterator serviceIter = d->m_serviceInterfaceMaps.find(interfaceMap); + if (serviceIter == d->m_serviceInterfaceMaps.end()) + { + throw std::invalid_argument("The provided service has not been retrieved via this ServiceObjects instance"); + } + + if (!d->m_reference.d->UngetPrototypeService(d->m_context->GetModule(), interfaceMap)) + { + US_WARN << "Ungetting service unsuccessful"; + } + else + { + d->m_serviceInterfaceMaps.erase(serviceIter); + } +} + +ServiceReferenceBase ServiceObjectsBase::GetReference() const +{ + return d->m_reference; +} + +ServiceObjectsBase::ServiceObjectsBase(const ServiceObjectsBase& other) + : d(other.d) +{ + d->ref.Ref(); +} + +ServiceObjectsBase::~ServiceObjectsBase() +{ + if (!d->ref.Deref()) + { + delete d; + } +} + +ServiceObjectsBase& ServiceObjectsBase::operator =(const ServiceObjectsBase& other) +{ + ServiceObjectsBasePrivate* curr_d = d; + d = other.d; + d->ref.Ref(); + + if (!curr_d->ref.Deref()) + delete curr_d; + + return *this; +} + +InterfaceMap ServiceObjects::GetService() const +{ + return this->ServiceObjectsBase::GetServiceInterfaceMap(); +} + +void ServiceObjects::UngetService(const InterfaceMap& service) +{ + this->ServiceObjectsBase::UngetService(service); +} + +ServiceReferenceU ServiceObjects::GetServiceReference() const +{ + return this->ServiceObjectsBase::GetReference(); +} + +ServiceObjects::ServiceObjects(ModuleContext* context, const ServiceReferenceU& reference) + : ServiceObjectsBase(context, reference) +{} + +US_END_NAMESPACE diff --git a/Core/CppMicroServices/src/service/usServiceObjects.h b/Core/CppMicroServices/src/service/usServiceObjects.h new file mode 100644 index 0000000000..f0db27accd --- /dev/null +++ b/Core/CppMicroServices/src/service/usServiceObjects.h @@ -0,0 +1,259 @@ +/*============================================================================= + + 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 USSERVICEOBJECTS_H +#define USSERVICEOBJECTS_H + +#include + +#include +#include +#include +#include + +US_BEGIN_NAMESPACE + +class ServiceObjectsBasePrivate; + +class US_EXPORT ServiceObjectsBase +{ + +private: + + ServiceObjectsBasePrivate* d; + +protected: + + ServiceObjectsBase(ModuleContext* context, const ServiceReferenceBase& reference); + + ServiceObjectsBase(const ServiceObjectsBase& other); + + ~ServiceObjectsBase(); + + ServiceObjectsBase& operator=(const ServiceObjectsBase& other); + + // Called by ServiceObjects with S != void + void* GetService() const; + + // Called by the ServiceObjects specialization + InterfaceMap GetServiceInterfaceMap() const; + + // Called by ServiceObjects with S != void + void UngetService(void* service); + + // Called by the ServiceObjects specialization + void UngetService(const InterfaceMap& interfaceMap); + + ServiceReferenceBase GetReference() const; + +}; + +/** + * @ingroup MicroServices + * + * Allows multiple service objects for a service to be obtained. + * + * For services with \link ServiceConstants::SCOPE_PROTOTYPE prototype\endlink scope, + * multiple service objects for the service can be obtained. For services with + * \link ServiceConstants::SCOPE_SINGLETON singleton\endlink or + * \link ServiceConstants::SCOPE_MODULE module \endlink scope, only one, use-counted + * service object is available. Any unreleased service objects obtained from this + * ServiceObjects object are automatically released by the framework when the modules + * associated with the ModuleContext used to create this ServiceObjects object is + * stopped. + * + * @tparam S Type of Service. + */ +template +class ServiceObjects : private ServiceObjectsBase +{ + +public: + + /** + * Returns a service object for the referenced service. + * + * This ServiceObjects object can be used to obtain multiple service objects for + * the referenced service if the service has \link ServiceConstants::SCOPE_PROTOTYPE prototype\endlink + * scope. If the referenced service has \link ServiceConstants::SCOPE_SINGLETON singleton\endlink + * or \link ServiceConstants::SCOPE_MODULE module\endlink scope, this method + * behaves the same as calling the ModuleContext::GetService(const ServiceReferenceBase&) + * method for the referenced service. That is, only one, use-counted service object + * is available from this ServiceObjects object. + * + * This method will always return \c NULL when the referenced service has been unregistered. + * + * For a prototype scope service, the following steps are taken to get the service object: + * + *

    + *
  1. If the referenced service has been unregistered, \c NULL is returned.
  2. + *
  3. The PrototypeServiceFactory::GetService(Module*, const ServiceRegistrationBase&) + * method is called to create a service object for the caller.
  4. + *
  5. If the service object (an instance of InterfaceMap) returned by the + * PrototypeServiceFactory object is empty, does not contain all the interfaces + * named when the service was registered or the PrototypeServiceFactory object + * throws an exception, \c NULL is returned and a warning message is issued.
  6. + *
  7. The service object is returned.
  8. + *
+ * + * @return A service object for the referenced service or \c NULL if the service is not + * registered, the service object returned by a ServiceFactory does not contain + * all the classes under which it was registered or the ServiceFactory threw an + * exception. + * + * @throw std::logic_error If the ModuleContext used to create this ServiceObjects object + * is no longer valid. + * + * @see UngetService() + */ + S* GetService() const + { + return reinterpret_cast(this->ServiceObjectsBase::GetService()); + } + + /** + * Releases a service object for the referenced service. + * + * This ServiceObjects object can be used to obtain multiple service objects for + * the referenced service if the service has \link ServiceConstants::SCOPE_PROTOTYPE prototype\endlink + * scope. If the referenced service has \link ServiceConstants::SCOPE_SINGLETON singleton\endlink + * or \link ServiceConstants::SCOPE_MODULE module\endlink scope, this method + * behaves the same as calling the ModuleContext::UngetService(const ServiceReferenceBase&) + * method for the referenced service. That is, only one, use-counted service object + * is available from this ServiceObjects object. + * + * For a prototype scope service, the following steps are take to release the service object: + * + *
    + *
  1. If the referenced service has been unregistered, this method returns without + * doing anything.
  2. + *
  3. The PrototypeServiceFactory::UngetService(Module*, const ServiceRegistrationBase&, const InterfaceMap&) + * method is called to release the specified service object.
  4. + *
  5. The specified service object must no longer be used and all references to it + * should be destroyed after calling this method.
  6. + *
+ * + * @param service A service object previously provided by this ServiceObjects object. + * + * @throw std::logic_error If the ModuleContext used to create this ServiceObjects + * object is no longer valid. + * @throw std::invalid_argument If the specified service was not provided by this + * ServiceObjects object. + * + * @see GetService() + */ + void UngetService(S* service) + { + this->ServiceObjectsBase::UngetService(service); + } + + /** + * Returns the ServiceReference for this ServiceObjects object. + * + * @return The ServiceReference for this ServiceObjects object. + */ + ServiceReference GetServiceReference() const + { + return this->ServiceObjectsBase::GetReference(); + } + +private: + + friend class ModuleContext; + + ServiceObjects(ModuleContext* context, const ServiceReference& reference) + : ServiceObjectsBase(context, reference) + {} + +}; + +/** + * @ingroup MicroServices + * + * Allows multiple service objects for a service to be obtained. + * + * This is a specialization of the ServiceObjects class template for + * "void", which maps to all service interface types. + * + * @see ServiceObjects + */ +template<> +class US_EXPORT ServiceObjects : private ServiceObjectsBase +{ + +public: + + /** + * Returns a service object as a InterfaceMap instance for the referenced service. + * + * This method is the same as ServiceObjects::GetService() except for the + * return type. Further, this method will always return an empty InterfaeMap + * object when the referenced service has been unregistered. + * + * @return A InterfaceMap object for the referenced service, which is empty if the + * service is not registered, the InterfaceMap returned by a ServiceFactory + * does not contain all the classes under which the service object was + * registered or the ServiceFactory threw an exception. + * + * @throw std::logic_error If the ModuleContext used to create this ServiceObjects object + * is no longer valid. + * + * @see ServiceObjects::GetService() + * @see UngetService() + */ + InterfaceMap GetService() const; + + /** + * Releases a service object for the referenced service. + * + * This method is the same as ServiceObjects::UngetService() except for the + * parameter type. + * + * @param service An InterfaceMap object previously provided by this ServiceObjects object. + * + * @throw std::logic_error If the ModuleContext used to create this ServiceObjects + * object is no longer valid. + * @throw std::invalid_argument If the specified service was not provided by this + * ServiceObjects object. + * + * @see ServiceObjects::UngetService() + * @see GetService() + */ + void UngetService(const InterfaceMap& service); + + /** + * Returns the ServiceReference for this ServiceObjects object. + * + * @return The ServiceReference for this ServiceObjects object. + */ + ServiceReferenceU GetServiceReference() const; + +private: + + friend class ModuleContext; + + ServiceObjects(ModuleContext* context, const ServiceReferenceU& reference); + +}; + +US_END_NAMESPACE + +#endif // USSERVICEOBJECTS_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceProperties.cpp b/Core/CppMicroServices/src/service/usServiceProperties.cpp similarity index 70% rename from Core/Code/CppMicroServices/src/service/usServiceProperties.cpp rename to Core/CppMicroServices/src/service/usServiceProperties.cpp index 61ee48daf9..d23acc7712 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceProperties.cpp +++ b/Core/CppMicroServices/src/service/usServiceProperties.cpp @@ -1,55 +1,83 @@ /*============================================================================= 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; } +const std::string& ServiceConstants::SERVICE_SCOPE() +{ + static const std::string s("service.scope"); + return s; +} + +const std::string& ServiceConstants::SCOPE_SINGLETON() +{ + static const std::string s("singleton"); + return s; +} + +const std::string& ServiceConstants::SCOPE_MODULE() +{ + static const std::string s("module"); + return s; +} + +const std::string& ServiceConstants::SCOPE_PROTOTYPE() +{ + static const std::string s("prototype"); + 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(); +std::string tmp4 = ServiceConstants::SERVICE_SCOPE(); +std::string tmp5 = ServiceConstants::SCOPE_SINGLETON(); +std::string tmp6 = ServiceConstants::SCOPE_MODULE(); +std::string tmp7 = ServiceConstants::SCOPE_PROTOTYPE(); diff --git a/Core/Code/CppMicroServices/src/service/usServiceProperties.h b/Core/CppMicroServices/src/service/usServiceProperties.h similarity index 55% rename from Core/Code/CppMicroServices/src/service/usServiceProperties.h rename to Core/CppMicroServices/src/service/usServiceProperties.h index a2d4a4a472..208d84ea77 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceProperties.h +++ b/Core/CppMicroServices/src/service/usServiceProperties.h @@ -1,199 +1,138 @@ /*============================================================================= 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. + * A hash table with std::string as the key type and Any as the value + * type. It is typically used for passing service properties to + * ModuleContext::RegisterService. */ -typedef US_UNORDERED_MAP_TYPE ServiceProperties; +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>. + * type std::vector<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" +/** + * Service property identifying a service's scope. + * This property is set by the framework when a service is registered. If the + * registered object implements PrototypeServiceFactory, then the value of this + * service property will be SCOPE_PROTOTYPE(). Otherwise, if the registered + * object implements ServiceFactory, then the value of this service property will + * be SCOPE_MODULE(). Otherwise, the value of this service property will be + * SCOPE_SINGLETON(). + */ +US_EXPORT const std::string& SERVICE_SCOPE(); // = "service.scope" + +/** + * Service scope is singleton. All modules using the service receive the same + * service object. + * + * @see SERVICE_SCOPE() + */ +US_EXPORT const std::string& SCOPE_SINGLETON(); // = "singleton" + +/** + * Service scope is module. Each module using the service receives a distinct + * service object. + * + * @see SERVICE_SCOPE() + */ +US_EXPORT const std::string& SCOPE_MODULE(); // = "module" + +/** + * Service scope is prototype. Each module using the service receives either + * a distinct service object or can request multiple distinct service objects + * via ServiceObjects. + * + * @see SERVICE_SCOPE() + */ +US_EXPORT const std::string& SCOPE_PROTOTYPE(); // = "prototype" + } US_END_NAMESPACE #endif // US_SERVICE_PROPERTIES_H diff --git a/Core/CppMicroServices/src/service/usServicePropertiesImpl.cpp b/Core/CppMicroServices/src/service/usServicePropertiesImpl.cpp new file mode 100644 index 0000000000..beca29c558 --- /dev/null +++ b/Core/CppMicroServices/src/service/usServicePropertiesImpl.cpp @@ -0,0 +1,99 @@ +/*============================================================================= + + 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 "usServicePropertiesImpl_p.h" + +#include +#ifdef US_PLATFORM_WINDOWS +#include +#define ci_compare strnicmp +#else +#include +#define ci_compare strncasecmp +#endif + +US_BEGIN_NAMESPACE + +Any ServicePropertiesImpl::emptyAny; + +ServicePropertiesImpl::ServicePropertiesImpl(const ServiceProperties& p) +{ + keys.reserve(p.size()); + values.reserve(p.size()); + + for (ServiceProperties::const_iterator iter = p.begin(); + iter != p.end(); ++iter) + { + if (Find(iter->first) > -1) + { + std::string msg = "ServiceProperties object contains case variants of the key: "; + msg += iter->first; + throw std::runtime_error(msg.c_str()); + } + keys.push_back(iter->first); + values.push_back(iter->second); + } +} + +const Any& ServicePropertiesImpl::Value(const std::string& key) const +{ + int i = Find(key); + if (i < 0) return emptyAny; + return values[i]; +} + +const Any& ServicePropertiesImpl::Value(int index) const +{ + if (index < 0 || static_cast(index) >= values.size()) + return emptyAny; + return values[index]; +} + +int ServicePropertiesImpl::Find(const std::string& key) const +{ + for (std::size_t i = 0; i < keys.size(); ++i) + { + if (ci_compare(key.c_str(), keys[i].c_str(), key.size()) == 0) + { + return i; + } + } + return -1; +} + +int ServicePropertiesImpl::FindCaseSensitive(const std::string& key) const +{ + for (std::size_t i = 0; i < keys.size(); ++i) + { + if (key == keys[i]) + { + return i; + } + } + return -1; +} + +const std::vector& ServicePropertiesImpl::Keys() const +{ + return keys; +} + +US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/util/usBase.h b/Core/CppMicroServices/src/service/usServicePropertiesImpl_p.h similarity index 61% rename from Core/Code/CppMicroServices/src/util/usBase.h rename to Core/CppMicroServices/src/service/usServicePropertiesImpl_p.h index ba57661d3f..4012d1042e 100644 --- a/Core/Code/CppMicroServices/src/util/usBase.h +++ b/Core/CppMicroServices/src/service/usServicePropertiesImpl_p.h @@ -1,45 +1,55 @@ /*============================================================================= 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 USSERVICEPROPERTIESIMPL_P_H +#define USSERVICEPROPERTIESIMPL_P_H -#ifndef USBASE_H -#define USBASE_H - -#include -#include +#include "usServiceProperties.h" US_BEGIN_NAMESPACE -class Base +class ServicePropertiesImpl { public: - virtual ~Base() {} - virtual const char* GetNameOfClass() const { return "US_PREPEND_NAMESPACE(Base)"; } + explicit ServicePropertiesImpl(const ServiceProperties& props); + + const Any& Value(const std::string& key) const; + const Any& Value(int index) const; + + int Find(const std::string& key) const; + int FindCaseSensitive(const std::string& key) const; + + const std::vector& Keys() const; + +private: + + std::vector keys; + std::vector values; + + static Any emptyAny; + }; US_END_NAMESPACE -template<> inline const char* us_service_impl_name(US_PREPEND_NAMESPACE(Base)* impl) -{ return impl->GetNameOfClass(); } - -#endif // USBASE_H +#endif // USSERVICEPROPERTIESIMPL_P_H diff --git a/Core/CppMicroServices/src/service/usServiceReference.h b/Core/CppMicroServices/src/service/usServiceReference.h new file mode 100644 index 0000000000..ff9bfc6cd0 --- /dev/null +++ b/Core/CppMicroServices/src/service/usServiceReference.h @@ -0,0 +1,146 @@ +/*============================================================================= + + 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 +#include + +//US_MSVC_PUSH_DISABLE_WARNING(4396) + +US_BEGIN_NAMESPACE + +/** + * \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. + * + * @tparam S The class type of the service interface + * @see ModuleContext::GetServiceReference + * @see ModuleContext::GetServiceReferences + * @see ModuleContext::GetService + * @remarks This class is thread safe. + */ +template +class ServiceReference : public ServiceReferenceBase { + +public: + + typedef S ServiceT; + + /** + * Creates an invalid ServiceReference object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceReference() : ServiceReferenceBase() + { + } + + ServiceReference(const ServiceReferenceBase& base) + : ServiceReferenceBase(base) + { + const std::string interfaceId(us_service_interface_iid()); + if (GetInterfaceId() != interfaceId) + { + if (this->IsConvertibleTo(interfaceId)) + { + this->SetInterfaceId(interfaceId); + } + else + { + this->operator =(0); + } + } + } + + using ServiceReferenceBase::operator=; + +}; + +/** + * \cond + * + * Specialization for void, representing a generic service + * reference not bound to any interface identifier. + * + */ +template<> +class ServiceReference : public ServiceReferenceBase +{ + +public: + + /** + * Creates an invalid ServiceReference object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceReference() : ServiceReferenceBase() + { + } + + ServiceReference(const ServiceReferenceBase& base) + : ServiceReferenceBase(base) + { + } + + using ServiceReferenceBase::operator=; + + typedef void ServiceType; +}; +/// \endcond + +/** + * \ingroup MicroServices + * + * A service reference of unknown type, which is not bound to any + * interface identifier. + */ +typedef ServiceReference ServiceReferenceU; + +US_END_NAMESPACE + +//US_MSVC_POP_WARNING + +#endif // USSERVICEREFERENCE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceReference.cpp b/Core/CppMicroServices/src/service/usServiceReferenceBase.cpp similarity index 55% rename from Core/Code/CppMicroServices/src/service/usServiceReference.cpp rename to Core/CppMicroServices/src/service/usServiceReferenceBase.cpp index 68d5c696ec..0ccd9d6559 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceReference.cpp +++ b/Core/CppMicroServices/src/service/usServiceReferenceBase.cpp @@ -1,189 +1,201 @@ /*============================================================================= 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 "usServiceReferenceBase.h" +#include "usServiceReferenceBasePrivate.h" +#include "usServiceRegistrationBasePrivate.h" #include "usModule.h" #include "usModulePrivate.h" US_BEGIN_NAMESPACE -typedef ServiceRegistrationPrivate::MutexType MutexType; +typedef ServiceRegistrationBasePrivate::MutexType MutexType; typedef MutexLock MutexLocker; -ServiceReference::ServiceReference() - : d(new ServiceReferencePrivate(0)) +ServiceReferenceBase::ServiceReferenceBase() + : d(new ServiceReferenceBasePrivate(0)) { } -ServiceReference::ServiceReference(const ServiceReference& ref) +ServiceReferenceBase::ServiceReferenceBase(const ServiceReferenceBase& ref) : d(ref.d) { d->ref.Ref(); } -ServiceReference::ServiceReference(ServiceRegistrationPrivate* reg) - : d(new ServiceReferencePrivate(reg)) +ServiceReferenceBase::ServiceReferenceBase(ServiceRegistrationBasePrivate* reg) + : d(new ServiceReferenceBasePrivate(reg)) { +} +void ServiceReferenceBase::SetInterfaceId(const std::string& interfaceId) +{ + if (d->ref > 1) + { + // detach + d->ref.Deref(); + d = new ServiceReferenceBasePrivate(d->registration); + } + d->interfaceId = interfaceId; } -ServiceReference::operator bool() const +ServiceReferenceBase::operator bool() const { return GetModule() != 0; } -ServiceReference& ServiceReference::operator=(int null) +ServiceReferenceBase& ServiceReferenceBase::operator=(int null) { if (null == 0) { if (!d->ref.Deref()) delete d; - d = new ServiceReferencePrivate(0); + d = new ServiceReferenceBasePrivate(0); } return *this; } -ServiceReference::~ServiceReference() +ServiceReferenceBase::~ServiceReferenceBase() { if (!d->ref.Deref()) delete d; } -Any ServiceReference::GetProperty(const std::string& key) const +Any ServiceReferenceBase::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(); + return d->registration->properties.Value(key); } -void ServiceReference::GetPropertyKeys(std::vector& keys) const +void ServiceReferenceBase::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); - } + const std::vector& ks = d->registration->properties.Keys(); + keys.assign(ks.begin(), ks.end()); } -Module* ServiceReference::GetModule() const +Module* ServiceReferenceBase::GetModule() const { if (d->registration == 0 || d->registration->module == 0) { return 0; } return d->registration->module->q; } -void ServiceReference::GetUsingModules(std::vector& modules) const +void ServiceReferenceBase::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(); + ServiceRegistrationBasePrivate::ModuleToRefsMap::const_iterator end = d->registration->dependents.end(); + for (ServiceRegistrationBasePrivate::ModuleToRefsMap::const_iterator iter = d->registration->dependents.begin(); iter != end; ++iter) { modules.push_back(iter->first); } } -bool ServiceReference::operator<(const ServiceReference& reference) const +bool ServiceReferenceBase::operator<(const ServiceReferenceBase& 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 +bool ServiceReferenceBase::operator==(const ServiceReferenceBase& reference) const { return d->registration == reference.d->registration; } -ServiceReference& ServiceReference::operator=(const ServiceReference& reference) +ServiceReferenceBase& ServiceReferenceBase::operator=(const ServiceReferenceBase& reference) { - ServiceReferencePrivate* curr_d = d; + ServiceReferenceBasePrivate* 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 +bool ServiceReferenceBase::IsConvertibleTo(const std::string& interfaceId) const +{ + return d->IsConvertibleTo(interfaceId); +} + +std::string ServiceReferenceBase::GetInterfaceId() const +{ + return d->interfaceId; +} + +std::size_t ServiceReferenceBase::Hash() const { using namespace US_HASH_FUNCTION_NAMESPACE; - return US_HASH_FUNCTION(ServiceRegistrationPrivate*, this->d->registration); + return US_HASH_FUNCTION(ServiceRegistrationBasePrivate*, this->d->registration); } US_END_NAMESPACE US_USE_NAMESPACE -std::ostream& operator<<(std::ostream& os, const ServiceReference& serviceRef) +std::ostream& operator<<(std::ostream& os, const ServiceReferenceBase& 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]); + os << keys[i] << "=" << serviceRef.GetProperty(keys[i]).ToString(); if (i < keySize-1) os << ","; } os << ")"; return os; } - diff --git a/Core/Code/CppMicroServices/src/service/usServiceReference.h b/Core/CppMicroServices/src/service/usServiceReferenceBase.h similarity index 53% rename from Core/Code/CppMicroServices/src/service/usServiceReference.h rename to Core/CppMicroServices/src/service/usServiceReferenceBase.h index c692f80cb7..9b132920d3 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceReference.h +++ b/Core/CppMicroServices/src/service/usServiceReferenceBase.h @@ -1,223 +1,228 @@ /*============================================================================= 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 +#ifndef USSERVICEREFERENCEBASE_H +#define USSERVICEREFERENCEBASE_H #include US_MSVC_PUSH_DISABLE_WARNING(4396) US_BEGIN_NAMESPACE class Module; -class ServiceRegistrationPrivate; -class ServiceReferencePrivate; +class ServiceRegistrationBasePrivate; +class ServiceReferenceBasePrivate; /** * \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. + * \note This class is provided as public API for low-level service queries only. + * In almost all cases you should use the template ServiceReference instead. */ -class US_EXPORT ServiceReference { +class US_EXPORT ServiceReferenceBase { 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); + ServiceReferenceBase(const ServiceReferenceBase& ref); /** - * Converts this ServiceReference instance into a boolean + * Converts this ServiceReferenceBase 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. + * ServiceReferenceBase and renders it invalid. */ - ServiceReference& operator=(int null); + ServiceReferenceBase& operator=(int null); - ~ServiceReference(); + ~ServiceReferenceBase(); /** * 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. + * referenced by this ServiceReferenceBase 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 of the service referenced by this ServiceReferenceBase * 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. + * ServiceReferenceBase 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 + * ServiceReferenceBase object; 0 if that * service has already been unregistered. - * @see ModuleContext::RegisterService(const std::vector&, US_BASECLASS_NAME*, const ServiceProperties&) + * @see ModuleContext::RegisterService(const InterfaceMap&, const ServiceProperties&) */ Module* GetModule() const; /** * Returns the modules that are using the service referenced by this - * ServiceReference object. Specifically, this method returns + * ServiceReferenceBase 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 + * by this ServiceReferenceBase object is greater than * zero. */ void GetUsingModules(std::vector& modules) const; /** - * Compares this ServiceReference with the specified - * ServiceReference for order. + * Returns the interface identifier this ServiceReferenceBase object + * is bound to. + * + * A default constructed ServiceReferenceBase object is not bound to + * any interface identifier and calling this method will return an + * empty string. + * + * @return The interface identifier for this ServiceReferenceBase object. + */ + std::string GetInterfaceId() const; + + /** + * Checks wether this ServiceReferenceBase object can be converted to + * another ServiceReferenceBase object, which will be bound to the + * given interface identifier. + * + * ServiceReferenceBase objects can be converted if the underlying service + * implementation was registered under multiple service interfaces. + * + * @param interfaceid + * @return \c true if this ServiceReferenceBase object can be converted, + * \c false otherwise. + */ + bool IsConvertibleTo(const std::string& interfaceid) const; + + /** + * Compares this ServiceReferenceBase with the specified + * ServiceReferenceBase 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 + * If this ServiceReferenceBase and the specified + * ServiceReferenceBase have the same \link ServiceConstants::SERVICE_ID() + * service id\endlink they are equal. This ServiceReferenceBase is less + * than the specified ServiceReferenceBase 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 + * higher service ranking. Otherwise, if this ServiceReferenceBase + * and the specified ServiceReferenceBase have the same * {@link ServiceConstants::SERVICE_RANKING service ranking}, this - * ServiceReference is less than the specified - * ServiceReference if it has a higher + * ServiceReferenceBase is less than the specified + * ServiceReferenceBase 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. + * @param reference The ServiceReferenceBase to be compared. * @return Returns a false or true if this - * ServiceReference is less than or greater - * than the specified ServiceReference. + * ServiceReferenceBase is less than or greater + * than the specified ServiceReferenceBase. */ - bool operator<(const ServiceReference& reference) const; - - bool operator==(const ServiceReference& reference) const; + bool operator<(const ServiceReferenceBase& reference) const; - ServiceReference& operator=(const ServiceReference& reference); + bool operator==(const ServiceReferenceBase& reference) const; + ServiceReferenceBase& operator=(const ServiceReferenceBase& reference); private: friend class ModulePrivate; friend class ModuleContext; - friend class ServiceFilter; - friend class ServiceRegistrationPrivate; + friend class ServiceObjectsBase; + friend class ServiceObjectsBasePrivate; + friend class ServiceRegistrationBase; + friend class ServiceRegistrationBasePrivate; friend class ServiceListeners; + friend class ServiceRegistry; friend class LDAPFilter; - template friend class ServiceTracker; - template friend class ServiceTrackerPrivate; - template friend class ModuleAbstractTracked; + template friend class ServiceReference; - US_HASH_FUNCTION_FRIEND(ServiceReference); + US_HASH_FUNCTION_FRIEND(ServiceReferenceBase); std::size_t Hash() const; - ServiceReference(ServiceRegistrationPrivate* reg); + /** + * Creates an invalid ServiceReferenceBase object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceReferenceBase(); + + ServiceReferenceBase(ServiceRegistrationBasePrivate* reg); + + void SetInterfaceId(const std::string& interfaceId); - ServiceReferencePrivate* d; + ServiceReferenceBasePrivate* 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_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceReferenceBase)& serviceRef); US_HASH_FUNCTION_NAMESPACE_BEGIN -US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceReference)) +US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceReferenceBase)) return arg.Hash(); US_HASH_FUNCTION_END US_HASH_FUNCTION_NAMESPACE_END -#endif // USSERVICEREFERENCE_H +#endif // USSERVICEREFERENCEBASE_H diff --git a/Core/CppMicroServices/src/service/usServiceReferenceBasePrivate.cpp b/Core/CppMicroServices/src/service/usServiceReferenceBasePrivate.cpp new file mode 100644 index 0000000000..505fdc4cc0 --- /dev/null +++ b/Core/CppMicroServices/src/service/usServiceReferenceBasePrivate.cpp @@ -0,0 +1,324 @@ +/*============================================================================= + + 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 "usServiceReferenceBasePrivate.h" + +#include "usServiceFactory.h" +#include "usServiceException.h" +#include "usServiceRegistry_p.h" +#include "usServiceRegistrationBasePrivate.h" + +#include "usModule.h" +#include "usModulePrivate.h" + +#include + +#include + +#ifdef _MSC_VER +#pragma warning(disable:4503) // decorated name length exceeded, name was truncated +#endif + +US_BEGIN_NAMESPACE + +typedef ServiceRegistrationBasePrivate::MutexLocker MutexLocker; + +ServiceReferenceBasePrivate::ServiceReferenceBasePrivate(ServiceRegistrationBasePrivate* reg) + : ref(1), registration(reg) +{ + if(registration) registration->ref.Ref(); +} + +ServiceReferenceBasePrivate::~ServiceReferenceBasePrivate() +{ + if (registration && !registration->ref.Deref()) + delete registration; +} + +InterfaceMap ServiceReferenceBasePrivate::GetServiceFromFactory(Module* module, + ServiceFactory* factory, + bool isModuleScope) +{ + assert(factory && "Factory service pointer is NULL"); + InterfaceMap s; + try + { + InterfaceMap smap = factory->GetService(module, + ServiceRegistrationBase(registration)); + if (smap.empty()) + { + US_WARN << "ServiceFactory produced null"; + return smap; + } + const std::vector& classes = + ref_any_cast >(registration->properties.Value(ServiceConstants::OBJECTCLASS())); + for (std::vector::const_iterator i = classes.begin(); + i != classes.end(); ++i) + { + if (smap.find(*i) == smap.end() && *i != "org.cppmicroservices.factory") + { + US_WARN << "ServiceFactory produced an object " + "that did not implement: " << (*i); + smap.clear(); + return smap; + } + } + s = smap; + + if (isModuleScope) + { + registration->moduleServiceInstance.insert(std::make_pair(module, smap)); + } + else + { + registration->prototypeServiceInstances[module].push_back(smap); + } + } + catch (...) + { + US_WARN << "ServiceFactory threw an exception"; + s.clear(); + } + return s; +} + +InterfaceMap ServiceReferenceBasePrivate::GetPrototypeService(Module* module) +{ + InterfaceMap s; + { + MutexLocker lock(registration->propsLock); + if (registration->available) + { + ServiceFactory* factory = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + s = GetServiceFromFactory(module, factory, false); + } + } + return s; +} + +void* ServiceReferenceBasePrivate::GetService(Module* module) +{ + void* s = NULL; + { + MutexLocker lock(registration->propsLock); + if (registration->available) + { + ServiceFactory* serviceFactory = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + + const int count = registration->dependents[module]; + if (count == 0) + { + if (serviceFactory) + { + const InterfaceMap im = GetServiceFromFactory(module, serviceFactory, true); + s = im.find(interfaceId)->second; + } + else + { + s = registration->GetService(interfaceId); + } + } + else + { + if (serviceFactory) + { + // return the already produced instance + s = registration->moduleServiceInstance[module][interfaceId]; + } + else + { + s = registration->GetService(interfaceId); + } + } + + if (s) + { + registration->dependents[module] = count + 1; + } + } + } + return s; +} + +InterfaceMap ServiceReferenceBasePrivate::GetServiceInterfaceMap(Module* module) +{ + InterfaceMap s; + { + MutexLocker lock(registration->propsLock); + if (registration->available) + { + ServiceFactory* serviceFactory = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + + const int count = registration->dependents[module]; + if (count == 0) + { + if (serviceFactory) + { + s = GetServiceFromFactory(module, serviceFactory, true); + } + else + { + s = registration->service; + } + } + else + { + if (serviceFactory) + { + // return the already produced instance + s = registration->moduleServiceInstance[module]; + } + else + { + s = registration->service; + } + } + + if (!s.empty()) + { + registration->dependents[module] = count + 1; + } + } + } + return s; +} + +bool ServiceReferenceBasePrivate::UngetPrototypeService(Module* module, const InterfaceMap& service) +{ + MutexLocker lock(registration->propsLock); + + ServiceRegistrationBasePrivate::ModuleToServicesMap::iterator iter = + registration->prototypeServiceInstances.find(module); + if (iter == registration->prototypeServiceInstances.end()) + { + return false; + } + + std::list& prototypeServiceMaps = iter->second; + + for (std::list::iterator imIter = prototypeServiceMaps.begin(); + imIter != prototypeServiceMaps.end(); ++imIter) + { + if (service == *imIter) + { + try + { + ServiceFactory* sf = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + sf->UngetService(module, ServiceRegistrationBase(registration), service); + } + catch (const std::exception& /*e*/) + { + US_WARN << "ServiceFactory threw an exception"; + } + prototypeServiceMaps.erase(imIter); + if (prototypeServiceMaps.empty()) + { + registration->prototypeServiceInstances.erase(iter); + } + return true; + } + } + + return false; +} + +bool ServiceReferenceBasePrivate::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) + { + InterfaceMap sfi = registration->moduleServiceInstance[module]; + registration->moduleServiceInstance.erase(module); + if (!sfi.empty()) + { + try + { + ServiceFactory* sf = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + sf->UngetService(module, ServiceRegistrationBase(registration), sfi); + } + catch (const std::exception& /*e*/) + { + US_WARN << "ServiceFactory threw an exception"; + } + } + registration->dependents.erase(module); + } + + return hadReferences && removeService; +} + +const ServicePropertiesImpl& ServiceReferenceBasePrivate::GetProperties() const +{ + return registration->properties; +} + +Any ServiceReferenceBasePrivate::GetProperty(const std::string& key, bool lock) const +{ + if (lock) + { + MutexLocker lock(registration->propsLock); + return registration->properties.Value(key); + } + else + { + return registration->properties.Value(key); + } +} + +bool ServiceReferenceBasePrivate::IsConvertibleTo(const std::string& interfaceId) const +{ + return registration ? registration->service.find(interfaceId) != registration->service.end() : false; +} + +US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.h b/Core/CppMicroServices/src/service/usServiceReferenceBasePrivate.h similarity index 61% rename from Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.h rename to Core/CppMicroServices/src/service/usServiceReferenceBasePrivate.h index 5dfc241a84..39f9951435 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.h +++ b/Core/CppMicroServices/src/service/usServiceReferenceBasePrivate.h @@ -1,118 +1,152 @@ /*============================================================================= 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 +#ifndef USSERVICEREFERENCEBASEPRIVATE_H +#define USSERVICEREFERENCEBASEPRIVATE_H #include "usAtomicInt_p.h" -#include "usServiceProperties.h" +#include "usServiceInterface.h" +#include US_BEGIN_NAMESPACE +class Any; class Module; -class ServiceRegistrationPrivate; -class ServiceReferencePrivate; +class ServicePropertiesImpl; +class ServiceRegistrationBasePrivate; +class ServiceReferenceBasePrivate; /** * \ingroup MicroServices */ -class ServiceReferencePrivate +class ServiceReferenceBasePrivate { public: - ServiceReferencePrivate(ServiceRegistrationPrivate* reg); + ServiceReferenceBasePrivate(ServiceRegistrationBasePrivate* reg); - ~ServiceReferencePrivate(); + ~ServiceReferenceBasePrivate(); /** * Get the service object. * * @param module requester of service. * @return Service requested or null in case of failure. */ - US_BASECLASS_NAME* GetService(Module* module); + void* GetService(Module* module); + + InterfaceMap GetServiceInterfaceMap(Module* module); + + /** + * Get new service instance. + * + * @param module requester of service. + * @return Service requested or null in case of failure. + */ + InterfaceMap GetPrototypeService(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 + * @return True if service was removed or false if only reference counter was * decremented. */ bool UngetService(Module* module, bool checkRefCounter); + /** + * Unget prototype scope service objects. + * + * @param module Module who wants to remove a prototype scope service. + * @param service The prototype scope service pointer. + * @return \c true if the service was removed, \c false otherwise. + */ + bool UngetPrototypeService(Module* module, void* service); + + bool UngetPrototypeService(Module* module, const InterfaceMap& service); + /** * Get all properties registered with this service. * * @return A ServiceProperties object containing properties or being empty * if service has been removed. */ - ServiceProperties GetProperties() const; + const ServicePropertiesImpl& 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; + bool IsConvertibleTo(const std::string& interfaceId) const; + /** * Reference count for implicitly shared private implementation. */ AtomicInt ref; /** * Link to registration object for this reference. */ - ServiceRegistrationPrivate* const registration; + ServiceRegistrationBasePrivate* const registration; + + /** + * The service interface id for this reference. + */ + std::string interfaceId; private: + InterfaceMap GetServiceFromFactory(Module* module, ServiceFactory* factory, + bool isModuleScope); + // purposely not implemented - ServiceReferencePrivate(const ServiceReferencePrivate&); - ServiceReferencePrivate& operator=(const ServiceReferencePrivate&); + ServiceReferenceBasePrivate(const ServiceReferenceBasePrivate&); + ServiceReferenceBasePrivate& operator=(const ServiceReferenceBasePrivate&); }; US_END_NAMESPACE -#endif // USSERVICEREFERENCEPRIVATE_H +#endif // USSERVICEREFERENCEBASEPRIVATE_H diff --git a/Core/CppMicroServices/src/service/usServiceRegistration.h b/Core/CppMicroServices/src/service/usServiceRegistration.h new file mode 100644 index 0000000000..d604ee8a41 --- /dev/null +++ b/Core/CppMicroServices/src/service/usServiceRegistration.h @@ -0,0 +1,203 @@ +/*============================================================================= + + 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 "usServiceRegistrationBase.h" + +US_BEGIN_NAMESPACE + +/** + * \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. + * + * @tparam S Class tyoe of the service interface + * @see ModuleContext#RegisterService() + * @remarks This class is thread safe. + */ +template +class ServiceRegistration : public ServiceRegistrationBase +{ + +public: + + /** + * Creates an invalid ServiceRegistration object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceRegistration() : ServiceRegistrationBase() + { + } + + ///@{ + /** + * 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(InterfaceT) const + { + return this->ServiceRegistrationBase::GetReference(us_service_interface_iid()); + } + ServiceReference GetReference(InterfaceT) const + { + return this->ServiceRegistrationBase::GetReference(us_service_interface_iid()); + } + ServiceReference GetReference(InterfaceT) const + { + return this->ServiceRegistrationBase::GetReference(us_service_interface_iid()); + } + ///@} + + using ServiceRegistrationBase::operator=; + + +private: + + friend class ModuleContext; + + ServiceRegistration(const ServiceRegistrationBase& base) + : ServiceRegistrationBase(base) + { + } + +}; + +/// \cond +template +class ServiceRegistration : public ServiceRegistrationBase +{ + +public: + + ServiceRegistration() : ServiceRegistrationBase() + { + } + + ServiceReference GetReference(InterfaceT) const + { + return ServiceReference(this->ServiceRegistrationBase::GetReference(us_service_interface_iid())); + } + + ServiceReference GetReference(InterfaceT) const + { + return ServiceReference(this->ServiceRegistrationBase::GetReference(us_service_interface_iid())); + } + + using ServiceRegistrationBase::operator=; + + +private: + + friend class ModuleContext; + + ServiceRegistration(const ServiceRegistrationBase& base) + : ServiceRegistrationBase(base) + { + } + +}; + +template +class ServiceRegistration : public ServiceRegistrationBase +{ + +public: + + ServiceRegistration() : ServiceRegistrationBase() + { + } + + ServiceReference GetReference() const + { + return this->GetReference(InterfaceT()); + } + + ServiceReference GetReference(InterfaceT) const + { + return ServiceReference(this->ServiceRegistrationBase::GetReference(us_service_interface_iid())); + } + + using ServiceRegistrationBase::operator=; + +private: + + friend class ModuleContext; + + ServiceRegistration(const ServiceRegistrationBase& base) + : ServiceRegistrationBase(base) + { + } + +}; + +template<> +class ServiceRegistration : public ServiceRegistrationBase +{ +public: + + /** + * Creates an invalid ServiceReference object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceRegistration() : ServiceRegistrationBase() + { + } + + ServiceRegistration(const ServiceRegistrationBase& base) + : ServiceRegistrationBase(base) + { + } + + using ServiceRegistrationBase::operator=; +}; +/// \endcond + +/** + * \ingroup MicroServices + * + * A service registration object of unknown type. + */ +typedef ServiceRegistration ServiceRegistrationU; + +US_END_NAMESPACE + +#endif // USSERVICEREGISTRATION_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistration.cpp b/Core/CppMicroServices/src/service/usServiceRegistrationBase.cpp similarity index 52% rename from Core/Code/CppMicroServices/src/service/usServiceRegistration.cpp rename to Core/CppMicroServices/src/service/usServiceRegistrationBase.cpp index 6884c9e1c4..b121bb0a60 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistration.cpp +++ b/Core/CppMicroServices/src/service/usServiceRegistrationBase.cpp @@ -1,247 +1,272 @@ /*============================================================================= 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 "usServiceRegistrationBase.h" +#include "usServiceRegistrationBasePrivate.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; +typedef ServiceRegistrationBasePrivate::MutexLocker MutexLocker; -ServiceRegistration::ServiceRegistration() +ServiceRegistrationBase::ServiceRegistrationBase() : d(0) { } -ServiceRegistration::ServiceRegistration(const ServiceRegistration& reg) +ServiceRegistrationBase::ServiceRegistrationBase(const ServiceRegistrationBase& reg) : d(reg.d) { if (d) d->ref.Ref(); } -ServiceRegistration::ServiceRegistration(ServiceRegistrationPrivate* registrationPrivate) +ServiceRegistrationBase::ServiceRegistrationBase(ServiceRegistrationBasePrivate* 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)) +ServiceRegistrationBase::ServiceRegistrationBase(ModulePrivate* module, const InterfaceMap& service, + const ServicePropertiesImpl& props) + : d(new ServiceRegistrationBasePrivate(module, service, props)) { } -ServiceRegistration::operator bool() const +ServiceRegistrationBase::operator bool() const { return d != 0; } -ServiceRegistration& ServiceRegistration::operator=(int null) +ServiceRegistrationBase& ServiceRegistrationBase::operator=(int null) { if (null == 0) { if (d && !d->ref.Deref()) { delete d; } d = 0; } return *this; } -ServiceRegistration::~ServiceRegistration() +ServiceRegistrationBase::~ServiceRegistrationBase() { if (d && !d->ref.Deref()) delete d; } -ServiceReference ServiceRegistration::GetReference() const +ServiceReferenceBase ServiceRegistrationBase::GetReference(const std::string& interfaceId) const { - if (!d) throw std::logic_error("ServiceRegistration object invalid"); + if (!d) throw std::logic_error("ServiceRegistrationBase object invalid"); if (!d->available) throw std::logic_error("Service is unregistered"); - return d->reference; + ServiceReferenceBase ref = d->reference; + ref.SetInterfaceId(interfaceId); + return ref; } -void ServiceRegistration::SetProperties(const ServiceProperties& props) +void ServiceRegistrationBase::SetProperties(const ServiceProperties& props) { - if (!d) throw std::logic_error("ServiceRegistration object invalid"); + if (!d) throw std::logic_error("ServiceRegistrationBase 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; + std::vector classes; { MutexLocker lock3(d->propsLock); - Any any = d->properties[ServiceConstants::SERVICE_RANKING()]; - if (any.Type() == typeid(int)) old_rank = any_cast(any); + { + const Any& any = d->properties.Value(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); + classes = ref_any_cast >(d->properties.Value(ServiceConstants::OBJECTCLASS())); + long int sid = any_cast(d->properties.Value(ServiceConstants::SERVICE_ID())); + d->properties = ServiceRegistry::CreateServiceProperties(props, classes, false, false, sid); - any = d->properties[ServiceConstants::SERVICE_RANKING()]; - if (any.Type() == typeid(int)) new_rank = any_cast(any); + { + const Any& any = d->properties.Value(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() +void ServiceRegistrationBase::Unregister() { - if (!d) throw std::logic_error("ServiceRegistration object invalid"); + if (!d) throw std::logic_error("ServiceRegistrationBase 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) + InterfaceMap::const_iterator factoryIter = d->service.find("org.cppmicroservices.factory"); + if (d->module && factoryIter != d->service.end()) { - ServiceRegistrationPrivate::ModuleToServicesMap::const_iterator end = d->serviceInstances.end(); - for (ServiceRegistrationPrivate::ModuleToServicesMap::const_iterator i = d->serviceInstances.begin(); + ServiceFactory* serviceFactory = reinterpret_cast(factoryIter->second); + ServiceRegistrationBasePrivate::ModuleToServicesMap::const_iterator end = d->prototypeServiceInstances.end(); + + // unget all prototype services + for (ServiceRegistrationBasePrivate::ModuleToServicesMap::const_iterator i = d->prototypeServiceInstances.begin(); i != end; ++i) { - US_BASECLASS_NAME* obj = i->second; + for (std::list::const_iterator listIter = i->second.begin(); + listIter != i->second.end(); ++listIter) + { + const InterfaceMap& service = *listIter; + try + { + // NYI, don't call inside lock + serviceFactory->UngetService(i->first, *this, service); + } + catch (const std::exception& /*ue*/) + { + US_WARN << "ServiceFactory UngetService implementation threw an exception"; + } + } + } + + // unget module scope services + ServiceRegistrationBasePrivate::ModuleToServiceMap::const_iterator moduleEnd = d->moduleServiceInstance.end(); + for (ServiceRegistrationBasePrivate::ModuleToServiceMap::const_iterator i = d->moduleServiceInstance.begin(); + i != moduleEnd; ++i) + { try { // NYI, don't call inside lock - dynamic_cast(d->service)->UngetService(i->first, - *this, - obj); + serviceFactory->UngetService(i->first, *this, i->second); } 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(); + d->service.clear(); + d->prototypeServiceInstances.clear(); + d->moduleServiceInstance.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 +bool ServiceRegistrationBase::operator<(const ServiceRegistrationBase& o) const { + if ((!d && !o.d) || !o.d) return false; if (!d) return true; return d->reference <(o.d->reference); } -bool ServiceRegistration::operator==(const ServiceRegistration& registration) const +bool ServiceRegistrationBase::operator==(const ServiceRegistrationBase& registration) const { return d == registration.d; } -ServiceRegistration& ServiceRegistration::operator=(const ServiceRegistration& registration) +ServiceRegistrationBase& ServiceRegistrationBase::operator=(const ServiceRegistrationBase& registration) { - ServiceRegistrationPrivate* curr_d = d; + ServiceRegistrationBasePrivate* 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/CppMicroServices/src/service/usServiceRegistrationBase.h similarity index 57% rename from Core/Code/CppMicroServices/src/service/usServiceRegistration.h rename to Core/CppMicroServices/src/service/usServiceRegistrationBase.h index 0203adedd2..f4dafda78f 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistration.h +++ b/Core/CppMicroServices/src/service/usServiceRegistrationBase.h @@ -1,191 +1,223 @@ /*============================================================================= 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 +#ifndef USSERVICEREGISTRATIONBASE_H +#define USSERVICEREGISTRATIONBASE_H #include "usServiceProperties.h" #include "usServiceReference.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4396) #endif US_BEGIN_NAMESPACE class ModulePrivate; +class ServiceRegistrationBasePrivate; +class ServicePropertiesImpl; /** * \ingroup MicroServices * * A registered service. * *

- * The framework returns a ServiceRegistration object when a + * The framework returns a ServiceRegistrationBase object when a * ModuleContext#RegisterService() method invocation is successful. - * The ServiceRegistration object is for the private use of the + * The ServiceRegistrationBase 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 + * The ServiceRegistrationBase object may be used to update the * properties of the service or to unregister the service. * + * \note This class is provided as public API for low-level service management only. + * In almost all cases you should use the template ServiceRegistration instead. + * * @see ModuleContext#RegisterService() * @remarks This class is thread safe. */ -class US_EXPORT ServiceRegistration { +class US_EXPORT ServiceRegistrationBase { public: + ServiceRegistrationBase(const ServiceRegistrationBase& reg); + /** - * Creates an invalid ServiceRegistration object. You can use - * this object in boolean expressions and it will evaluate to - * false. + * A boolean conversion operator converting this ServiceRegistrationBase object + * to \c true if it is valid and to \c false otherwise. A SeriveRegistration + * object is invalid if it was default-constructed or was invalidated by + * assigning 0 to it. + * + * \see operator=(int) + * + * \return \c true if this ServiceRegistrationBase object is valid, \c false + * otherwise. */ - ServiceRegistration(); - - ServiceRegistration(const ServiceRegistration& reg); - operator bool() const; /** * Releases any resources held or locked by this - * ServiceRegistration and renders it invalid. + * ServiceRegistrationBase and renders it invalid. + * + * \return This ServiceRegistrationBase object. */ - ServiceRegistration& operator=(int null); + ServiceRegistrationBase& operator=(int null); - ~ServiceRegistration(); + ~ServiceRegistrationBase(); /** * 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 + * ServiceRegistrationBase object has already been * unregistered or if it is invalid. * @return ServiceReference object. */ - ServiceReference GetReference() const; + ServiceReferenceBase GetReference(const std::string& interfaceId = std::string()) 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 + * @throws std::logic_error If this ServiceRegistrationBase * 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 + * Unregisters a service. Remove a ServiceRegistrationBase object + * from the framework service registry. All ServiceRegistrationBase + * objects associated with this ServiceRegistrationBase 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 + * ServiceRegistrationBase 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 + * ServiceRegistrationBase object has already been * unregistered or if it is invalid. * @see ModuleContext#UngetService * @see ServiceFactory#UngetService */ void Unregister(); - bool operator<(const ServiceRegistration& o) const; + /** + * Compare two ServiceRegistrationBase objects. + * + * If both ServiceRegistrationBase objects are valid, the comparison is done + * using the underlying ServiceReference object. Otherwise, this ServiceRegistrationBase + * object is less than the other object if and only if this object is invalid and + * the other object is valid. + * + * @param o The ServiceRegistrationBase object to compare with. + * @return \c true if this ServiceRegistrationBase object is less than the other object. + */ + bool operator<(const ServiceRegistrationBase& o) const; - bool operator==(const ServiceRegistration& registration) const; + bool operator==(const ServiceRegistrationBase& registration) const; - ServiceRegistration& operator=(const ServiceRegistration& registration); + ServiceRegistrationBase& operator=(const ServiceRegistrationBase& registration); private: friend class ServiceRegistry; - friend class ServiceReferencePrivate; - US_HASH_FUNCTION_FRIEND(ServiceRegistration); + friend class ServiceReferenceBasePrivate; + + template friend class ServiceRegistration; + + US_HASH_FUNCTION_FRIEND(ServiceRegistrationBase); + + /** + * Creates an invalid ServiceRegistrationBase object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceRegistrationBase(); - ServiceRegistration(ServiceRegistrationPrivate* registrationPrivate); + ServiceRegistrationBase(ServiceRegistrationBasePrivate* registrationPrivate); - ServiceRegistration(ModulePrivate* module, US_BASECLASS_NAME* service, - const ServiceProperties& props); + ServiceRegistrationBase(ModulePrivate* module, const InterfaceMap& service, + const ServicePropertiesImpl& props); - ServiceRegistrationPrivate* d; + ServiceRegistrationBasePrivate* 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_BEGIN(US_PREPEND_NAMESPACE(ServiceRegistrationBase)) + return US_HASH_FUNCTION(US_PREPEND_NAMESPACE(ServiceRegistrationBasePrivate)*, arg.d); US_HASH_FUNCTION_END US_HASH_FUNCTION_NAMESPACE_END -inline std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceRegistration)& /*reg*/) +inline std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceRegistrationBase)& /*reg*/) { - return os << "US_PREPEND_NAMESPACE(ServiceRegistration) object"; + return os << "US_PREPEND_NAMESPACE(ServiceRegistrationBase) object"; } -#endif // USSERVICEREGISTRATION_H +#endif // USSERVICEREGISTRATIONBASE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.cpp b/Core/CppMicroServices/src/service/usServiceRegistrationBasePrivate.cpp similarity index 59% rename from Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.cpp rename to Core/CppMicroServices/src/service/usServiceRegistrationBasePrivate.cpp index da050082e1..078ee6fb37 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.cpp +++ b/Core/CppMicroServices/src/service/usServiceRegistrationBasePrivate.cpp @@ -1,60 +1,76 @@ /*============================================================================= 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" +#include "usServiceRegistrationBasePrivate.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) +ServiceRegistrationBasePrivate::ServiceRegistrationBasePrivate( + ModulePrivate* module, const InterfaceMap& service, + const ServicePropertiesImpl& 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() +ServiceRegistrationBasePrivate::~ServiceRegistrationBasePrivate() { } -bool ServiceRegistrationPrivate::IsUsedByModule(Module* p) +bool ServiceRegistrationBasePrivate::IsUsedByModule(Module* p) const { - return dependents.find(p) != dependents.end(); + return (dependents.find(p) != dependents.end()) || + (prototypeServiceInstances.find(p) != prototypeServiceInstances.end()); } -US_BASECLASS_NAME* ServiceRegistrationPrivate::GetService() +const InterfaceMap& ServiceRegistrationBasePrivate::GetInterfaces() const { return service; } +void* ServiceRegistrationBasePrivate::GetService(const std::string& interfaceId) const +{ + if (interfaceId.empty() && service.size() > 0) + { + return service.begin()->second; + } + + InterfaceMap::const_iterator iter = service.find(interfaceId); + if (iter != service.end()) + { + return iter->second; + } + return NULL; +} + US_END_NAMESPACE #ifdef _MSC_VER #pragma warning(pop) #endif diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.h b/Core/CppMicroServices/src/service/usServiceRegistrationBasePrivate.h similarity index 62% rename from Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.h rename to Core/CppMicroServices/src/service/usServiceRegistrationBasePrivate.h index a2099c07f0..504907f61f 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.h +++ b/Core/CppMicroServices/src/service/usServiceRegistrationBasePrivate.h @@ -1,143 +1,152 @@ /*============================================================================= 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 +#ifndef USSERVICEREGISTRATIONBASEPRIVATE_H +#define USSERVICEREGISTRATIONBASEPRIVATE_H +#include "usServiceInterface.h" #include "usServiceReference.h" -#include "usServiceProperties.h" +#include "usServicePropertiesImpl_p.h" #include "usAtomicInt_p.h" US_BEGIN_NAMESPACE class ModulePrivate; -class ServiceRegistration; +class ServiceRegistrationBase; /** * \ingroup MicroServices */ -class ServiceRegistrationPrivate +class ServiceRegistrationBasePrivate { protected: - friend class ServiceRegistration; + friend class ServiceRegistrationBase; - // The ServiceReferencePrivate class holds a pointer to a - // ServiceRegistrationPrivate instance and needs to manipulate - // its reference count. This way it can keep the ServiceRegistrationPrivate + // The ServiceReferenceBasePrivate class holds a pointer to a + // ServiceRegistrationBasePrivate instance and needs to manipulate + // its reference count. This way it can keep the ServiceRegistrationBasePrivate // instance alive and keep returning service properties for // unregistered service instances. - friend class ServiceReferencePrivate; + friend class ServiceReferenceBasePrivate; /** * Reference count for implicitly shared private implementation. */ AtomicInt ref; /** * Service or ServiceFactory object. */ - US_BASECLASS_NAME* service; + InterfaceMap service; public: typedef Mutex MutexType; typedef MutexLock MutexLocker; typedef US_UNORDERED_MAP_TYPE ModuleToRefsMap; - typedef US_UNORDERED_MAP_TYPE ModuleToServicesMap; + typedef US_UNORDERED_MAP_TYPE ModuleToServiceMap; + 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. + * Object instances that a prototype factory has produced. */ - ModuleToServicesMap serviceInstances; + ModuleToServicesMap prototypeServiceInstances; + + /** + * Object instance with module scope that a factory may have produced. + */ + ModuleToServiceMap moduleServiceInstance; /** * Module registering this service. */ ModulePrivate* module; /** * Reference object to this service registration. */ - ServiceReference reference; + ServiceReferenceBase reference; /** * Service properties. */ - ServiceProperties properties; + ServicePropertiesImpl 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); + ServiceRegistrationBasePrivate(ModulePrivate* module, const InterfaceMap& service, + const ServicePropertiesImpl& props); - ~ServiceRegistrationPrivate(); + ~ServiceRegistrationBasePrivate(); /** * Check if a module uses this service * * @param p Module to check * @return true if module uses this service */ - bool IsUsedByModule(Module* m); + bool IsUsedByModule(Module* m) const; + + const InterfaceMap& GetInterfaces() const; - US_BASECLASS_NAME* GetService(); + void* GetService(const std::string& interfaceId) const; private: // purposely not implemented - ServiceRegistrationPrivate(const ServiceRegistrationPrivate&); - ServiceRegistrationPrivate& operator=(const ServiceRegistrationPrivate&); + ServiceRegistrationBasePrivate(const ServiceRegistrationBasePrivate&); + ServiceRegistrationBasePrivate& operator=(const ServiceRegistrationBasePrivate&); }; US_END_NAMESPACE -#endif // USSERVICEREGISTRATIONPRIVATE_H +#endif // USSERVICEREGISTRATIONBASEPRIVATE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistry.cpp b/Core/CppMicroServices/src/service/usServiceRegistry.cpp similarity index 60% rename from Core/Code/CppMicroServices/src/service/usServiceRegistry.cpp rename to Core/CppMicroServices/src/service/usServiceRegistry.cpp index 5a49cdc7dd..92222eba19 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistry.cpp +++ b/Core/CppMicroServices/src/service/usServiceRegistry.cpp @@ -1,327 +1,322 @@ /*============================================================================= 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 "usPrototypeServiceFactory.h" #include "usServiceRegistry_p.h" -#include "usServiceRegistrationPrivate.h" +#include "usServiceRegistrationBasePrivate.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) +ServicePropertiesImpl ServiceRegistry::CreateServiceProperties(const ServiceProperties& in, + const std::vector& classes, + bool isFactory, bool isPrototypeFactory, + 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; + if (isPrototypeFactory) + { + props.insert(std::make_pair(ServiceConstants::SERVICE_SCOPE(), ServiceConstants::SCOPE_PROTOTYPE())); + } + else if (isFactory) + { + props.insert(std::make_pair(ServiceConstants::SERVICE_SCOPE(), ServiceConstants::SCOPE_MODULE())); + } + else + { + props.insert(std::make_pair(ServiceConstants::SERVICE_SCOPE(), ServiceConstants::SCOPE_SINGLETON())); + } + + return ServicePropertiesImpl(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, +ServiceRegistrationBase ServiceRegistry::RegisterService(ModulePrivate* module, + const InterfaceMap& service, const ServiceProperties& properties) { - if (service == 0) + if (service.empty()) { - throw std::invalid_argument("Can't register 0 as a service"); + throw std::invalid_argument("Can't register empty InterfaceMap as a service"); } + // Check if we got a service factory + bool isFactory = service.count("org.cppmicroservices.factory") > 0; + bool isPrototypeFactory = (isFactory ? dynamic_cast(reinterpret_cast(service.find("org.cppmicroservices.factory")->second)) != NULL : false); + + std::vector classes; // Check if service implements claimed classes and that they exist. - for (std::list::const_iterator i = classes.begin(); - i != classes.end(); ++i) + for (InterfaceMap::const_iterator i = service.begin(); + i != service.end(); ++i) { - if (i->empty()) + if (i->first.empty() || (!isFactory && i->second == NULL)) { 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); - } - } + classes.push_back(i->first); } - ServiceRegistration res(module, service, - CreateServiceProperties(properties, classes)); + ServiceRegistrationBase res(module, service, + CreateServiceProperties(properties, classes, isFactory, isPrototypeFactory)); { MutexLocker lock(mutex); services.insert(std::make_pair(res, classes)); serviceRegistrations.push_back(res); - for (std::list::const_iterator i = classes.begin(); + for (std::vector::const_iterator i = classes.begin(); i != classes.end(); ++i) { - std::list& s = classServices[*i]; - std::list::iterator ip = + std::vector& s = classServices[*i]; + std::vector::iterator ip = std::lower_bound(s.begin(), s.end(), res); s.insert(ip, res); } } - ServiceReference r = res.GetReference(); + ServiceReferenceBase r = res.GetReference(std::string()); 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) +void ServiceRegistry::UpdateServiceRegistrationOrder(const ServiceRegistrationBase& sr, + const std::vector& classes) { MutexLocker lock(mutex); - for (std::list::const_iterator i = classes.begin(); + for (std::vector::const_iterator i = classes.begin(); i != classes.end(); ++i) { - std::list& s = classServices[*i]; + std::vector& 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 + std::vector& 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 +ServiceReferenceBase ServiceRegistry::Get(ModulePrivate* module, const std::string& clazz) const { MutexLocker lock(mutex); try { - std::list srs; + std::vector 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(); + return ServiceReferenceBase(); } void ServiceRegistry::Get(const std::string& clazz, const std::string& filter, - ModulePrivate* module, std::list& res) const + ModulePrivate* module, std::vector& 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 + ModulePrivate* /*module*/, std::vector& res) const { - std::list::const_iterator s; - std::list::const_iterator send; - std::list v; + std::vector::const_iterator s; + std::vector::const_iterator send; + std::vector 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(); + ServiceReferenceBase sri = s->GetReference(clazz); if (filter.empty() || ldap.Evaluate(s->d->properties, false)) { res.push_back(sri); } } } -void ServiceRegistry::RemoveServiceRegistration(const ServiceRegistration& sr) +void ServiceRegistry::RemoveServiceRegistration(const ServiceRegistrationBase& sr) { MutexLocker lock(mutex); - const std::list& classes = ref_any_cast >( - sr.d->properties[ServiceConstants::OBJECTCLASS()]); + const std::vector& classes = ref_any_cast >( + sr.d->properties.Value(ServiceConstants::OBJECTCLASS())); services.erase(sr); - serviceRegistrations.remove(sr); - for (std::list::const_iterator i = classes.begin(); + serviceRegistrations.erase(std::remove(serviceRegistrations.begin(), serviceRegistrations.end(), sr), + serviceRegistrations.end()); + for (std::vector::const_iterator i = classes.begin(); i != classes.end(); ++i) { - std::list& s = classServices[*i]; + std::vector& 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 + std::vector& res) const { MutexLocker lock(mutex); - for (std::list::const_iterator i = serviceRegistrations.begin(); + for (std::vector::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 + std::vector& res) const { MutexLocker lock(mutex); - for (std::list::const_iterator i = serviceRegistrations.begin(); + for (std::vector::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/CppMicroServices/src/service/usServiceRegistry_p.h similarity index 70% rename from Core/Code/CppMicroServices/src/service/usServiceRegistry_p.h rename to Core/CppMicroServices/src/service/usServiceRegistry_p.h index 49af448db6..9d780ab707 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistry_p.h +++ b/Core/CppMicroServices/src/service/usServiceRegistry_p.h @@ -1,196 +1,185 @@ /*============================================================================= 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 "usServiceInterface.h" #include "usServiceRegistration.h" -#include "usServiceProperties.h" #include "usThreads_p.h" US_BEGIN_NAMESPACE class CoreModuleContext; class ModulePrivate; +class ServicePropertiesImpl; /** * 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); + static ServicePropertiesImpl CreateServiceProperties(const ServiceProperties& in, + const std::vector& classes = std::vector(), + bool isFactory = false, bool isPrototypeFactory = false, long sid = -1); - typedef US_UNORDERED_MAP_TYPE > MapServiceClasses; - typedef US_UNORDERED_MAP_TYPE > MapClassServices; + 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; + std::vector 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); + ServiceRegistrationBase RegisterService(ModulePrivate* module, + const InterfaceMap& 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; + void UpdateServiceRegistrationOrder(const ServiceRegistrationBase& sr, + const std::vector& classes); /** * 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; + void Get(const std::string& clazz, std::vector& 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; + ServiceReferenceBase 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; + ModulePrivate* module, std::vector& serviceRefs) const; /** * Remove a registered service. * * @param sr The ServiceRegistration object that is registered. */ - void RemoveServiceRegistration(const ServiceRegistration& sr) ; + void RemoveServiceRegistration(const ServiceRegistrationBase& 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; + void GetRegisteredByModule(ModulePrivate* m, std::vector& 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; + void GetUsedByModule(Module* m, std::vector& serviceRegs) const; private: void Get_unlocked(const std::string& clazz, const std::string& filter, - ModulePrivate* module, std::list& serviceRefs) const; + ModulePrivate* module, std::vector& 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/CppMicroServices/src/service/usServiceTracker.h similarity index 70% rename from Core/Code/CppMicroServices/src/service/usServiceTracker.h rename to Core/CppMicroServices/src/service/usServiceTracker.h index 0915ec51f9..1dee7e7eec 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceTracker.h +++ b/Core/CppMicroServices/src/service/usServiceTracker.h @@ -1,433 +1,600 @@ /*============================================================================= 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 + * + * A base class template for type traits for objects tracked by a + * ServiceTracker instance. It provides the \c TrackedType typedef + * and two dummy method definitions. + * + * Tracked type traits (TTT) classes must additionally provide the + * following methods: + * + *
    + *
  • static bool IsValid(const TrackedType& t) Returns \c true if \c t is a valid object, \c false otherwise.
  • + *
  • static void Dispose(TrackedType& t) Clears any resources held by the tracked object \c t.
  • + *
  • static TrackedType DefaultValue() Returns the default value for newly created tracked objects.
  • + *
+ * + * @tparam T The type of the tracked object. + * @tparam TTT The tracked type traits class deriving from this class. + * + * @see ServiceTracker + */ +template +struct TrackedTypeTraitsBase +{ + typedef T TrackedType; + + // Needed for S == void + static TrackedType ConvertToTrackedType(const InterfaceMap&) + { + throw std::runtime_error("A custom ServiceTrackerCustomizer instance is required for custom tracked objects."); + return TTT::DefaultValue(); + } + + // Needed for S != void + static TrackedType ConvertToTrackedType(void*) + { + throw std::runtime_error("A custom ServiceTrackerCustomizer instance is required for custom tracked objects."); + return TTT::DefaultValue(); + } +}; + +/// \cond +template +struct TrackedTypeTraits; +/// \endcond + +/** + * \ingroup MicroServices + * + * Default type traits for custom tracked objects of pointer type. + * + * Use this tracked type traits template for custom tracked objects of + * pointer type with the ServiceTracker class. + * + * @tparam S The type of the service being tracked. + * @tparam T The type of the tracked object. + */ +template +struct TrackedTypeTraits : public TrackedTypeTraitsBase > +{ + typedef T* TrackedType; + + static bool IsValid(const TrackedType& t) + { + return t != NULL; + } + + static TrackedType DefaultValue() + { + return NULL; + } + + static void Dispose(TrackedType& t) + { + t = 0; + } +}; + +/// \cond +template +struct TrackedTypeTraits +{ + typedef S* TrackedType; + + static bool IsValid(const TrackedType& t) + { + return t != NULL; + } + + static TrackedType DefaultValue() + { + return NULL; + } + + static void Dispose(TrackedType& t) + { + t = 0; + } + + static TrackedType ConvertToTrackedType(S* s) + { + return s; + } +}; +/// \endcond + +/// \cond +/* + * This specialization is "special" because the tracked type is not + * void* (as specified in the second template parameter) but InterfaceMap. + * This is in line with the ModuleContext::GetService(...) overloads to + * return either S* or InterfaceMap dependening on the template parameter. + */ +template<> +struct TrackedTypeTraits +{ + typedef InterfaceMap TrackedType; + + static bool IsValid(const TrackedType& t) + { + return !t.empty(); + } + + static TrackedType DefaultValue() + { + return TrackedType(); + } + + static void Dispose(TrackedType& t) + { + t.clear(); + } + + static TrackedType ConvertToTrackedType(const InterfaceMap& im) + { + return im; + } +}; +/// \endcond + /** * \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 + * \note The ServiceTracker class is thread-safe. It does not call a + * ServiceTrackerCustomizer while holding any locks. + * ServiceTrackerCustomizer implementations must also be + * thread-safe. + * + * Customization of the services to be tracked requires a custom tracked type traits + * class if the custom tracked type is not a pointer type. To customize a tracked + * service using a custom type with value-semantics like + * \snippet uServices-servicetracker/main.cpp tt + * the custom tracked type traits class should look like this: + * \snippet uServices-servicetracker/main.cpp ttt + * + * For a custom tracked type, a ServiceTrackerCustomizer is required, which knows + * how to associate the tracked service with the custom tracked type: + * \snippet uServices-servicetracker/main.cpp customizer + * The custom tracking type traits class and customizer can now be used to instantiate + * a ServiceTracker: + * \snippet uServices-servicetracker/main.cpp tracker + * + * If the custom tracked type is a pointer type, a suitable tracked type traits + * template is provided by the framework and only a ServiceTrackerCustomizer needs + * to be provided: + * \snippet uServices-servicetracker/main.cpp tracker2 + * + * + * @tparam S The type of the service being tracked. The type S* must be an * assignable datatype. Further, if the - * ServiceTracker(ModuleContext*, ServiceTrackerCustomizer*) + * 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. + * @tparam TTT Type traits of the tracked object. The type traits class provides + * information about the customized service object, see TrackedTypeTraitsBase. + * + * @remarks This class is thread safe. */ -template -class ServiceTracker : protected ServiceTrackerCustomizer +template > +class ServiceTracker : protected ServiceTrackerCustomizer { public: - typedef std::map TrackingMap; + /// The type of the service being tracked + typedef S ServiceT; + /// The type of the tracked object + typedef typename TTT::TrackedType T; + + typedef ServiceReference ServiceReferenceT; + + typedef std::map,T> 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); + const ServiceReferenceT& 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); + 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); + 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); + 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; + virtual void GetServiceReferences(std::vector& 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; + virtual ServiceReferenceT 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; + virtual T GetService(const ServiceReferenceT& 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; + virtual void GetServices(std::vector& 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); + virtual void Remove(const ServiceReferenceT& 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 + * \link RemovedService(const ServiceReferenceT&, 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); + T AddingService(const ServiceReferenceT& 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); + void ModifiedService(const ServiceReferenceT& 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 + * implementation of \link AddingService(const ServiceReferenceT&) 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) + * @see ServiceTrackerCustomizer::RemovedService(const ServiceReferenceT&, T) */ - void RemovedService(const ServiceReference& reference, T service); + void RemovedService(const ServiceReferenceT& reference, T service); private: - typedef ServiceTracker _ServiceTracker; - typedef TrackedService _TrackedService; - typedef ServiceTrackerPrivate _ServiceTrackerPrivate; - typedef ServiceTrackerCustomizer _ServiceTrackerCustomizer; + typedef ServiceTracker _ServiceTracker; + typedef TrackedService _TrackedService; + typedef ServiceTrackerPrivate _ServiceTrackerPrivate; + typedef ServiceTrackerCustomizer _ServiceTrackerCustomizer; - friend class TrackedService; - friend class ServiceTrackerPrivate; + 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/CppMicroServices/src/service/usServiceTracker.tpp similarity index 64% rename from Core/Code/CppMicroServices/src/service/usServiceTracker.tpp rename to Core/CppMicroServices/src/service/usServiceTracker.tpp index 608c628c61..ea9319d4c1 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceTracker.tpp +++ b/Core/CppMicroServices/src/service/usServiceTracker.tpp @@ -1,448 +1,459 @@ /*============================================================================= 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() +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) +template +ServiceTracker::ServiceTracker(ModuleContext* context, + const ServiceReferenceT& reference, + _ServiceTrackerCustomizer* customizer) : d(new _ServiceTrackerPrivate(this, context, reference, customizer)) { } -template -ServiceTracker::ServiceTracker(ModuleContext* context, const std::string& clazz, - _ServiceTrackerCustomizer* 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) +template +ServiceTracker::ServiceTracker(ModuleContext* context, const LDAPFilter& filter, + _ServiceTrackerCustomizer* customizer) : d(new _ServiceTrackerPrivate(this, context, filter, customizer)) { } -template -ServiceTracker::ServiceTracker(ModuleContext *context, ServiceTrackerCustomizer *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() +template +void ServiceTracker::Open() { _TrackedService* t; { typename _ServiceTrackerPrivate::Lock l(d); if (d->trackedService) { return; } - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::Open: " << d->filter; + 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; + std::vector 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() +template +void ServiceTracker::Close() { _TrackedService* outgoing; - std::list references; + std::vector references; { typename _ServiceTrackerPrivate::Lock l(d); outgoing = d->trackedService; if (outgoing == 0) { return; } - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::close:" << d->filter; + 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(); + for(typename std::vector::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)) + if ((d->cachedReference.GetModule() == 0) && !TTT::IsValid(d->cachedService)) { - US_DEBUG(true) << "ServiceTracker::close[cached cleared]:" + US_DEBUG(true) << "ServiceTracker::close[cached cleared]:" << d->filter; } } delete outgoing; d->trackedService = 0; } -template -T ServiceTracker::WaitForService(unsigned long timeoutMillis) +template +typename ServiceTracker::T +ServiceTracker::WaitForService(unsigned long timeoutMillis) { T object = GetService(); - while (object == 0) + while (!TTT::IsValid(object)) { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ - return 0; + return TTT::DefaultValue(); } { typename _TrackedService::Lock l(t); if (t->Size() == 0) { t->Wait(timeoutMillis); } } object = GetService(); } return object; } -template -void ServiceTracker::GetServiceReferences(std::list& refs) const +template +void ServiceTracker::GetServiceReferences(std::vector& 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 +template +typename ServiceTracker::ServiceReferenceT +ServiceTracker::GetServiceReference() const { - ServiceReference reference(0); + ServiceReferenceT reference; { typename _ServiceTrackerPrivate::Lock l(d); reference = d->cachedReference; } if (reference.GetModule() != 0) { - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getServiceReference[cached]:" + US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getServiceReference[cached]:" << d->filter; return reference; } - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getServiceReference:" << d->filter; - std::list references; + US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getServiceReference:" << d->filter; + std::vector 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; + typename std::vector::const_iterator selectedRef = references.begin(); 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(); + typename std::vector::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 +template +typename ServiceTracker::T +ServiceTracker::GetService(const ServiceReferenceT& reference) const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ - return 0; + return TTT::DefaultValue(); } { typename _TrackedService::Lock l(t); return t->GetCustomizedObject(reference); } } -template -void ServiceTracker::GetServices(std::list& services) const +template +void ServiceTracker::GetServices(std::vector& services) const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return; } { typename _TrackedService::Lock l(t); - std::list references; + std::vector references; d->GetServiceReferences_unlocked(references, t); - for(std::list::const_iterator ref = references.begin(); + for(typename std::vector::const_iterator ref = references.begin(); ref != references.end(); ++ref) { services.push_back(t->GetCustomizedObject(*ref)); } } } -template -T ServiceTracker::GetService() const +template +typename ServiceTracker::T +ServiceTracker::GetService() const { - T service = d->cachedService; - if (service != 0) { - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getService[cached]:" - << d->filter; - return service; + typename _ServiceTrackerPrivate::Lock l(d); + const T& service = d->cachedService; + if (TTT::IsValid(service)) + { + US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getService[cached]:" + << d->filter; + return service; + } } - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getService:" << d->filter; + US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getService:" << d->filter; try { - ServiceReference reference = GetServiceReference(); + ServiceReferenceT reference = GetServiceReference(); if (reference.GetModule() == 0) { - return 0; + return TTT::DefaultValue(); + } + { + typename _ServiceTrackerPrivate::Lock l(d); + return d->cachedService = GetService(reference); } - return d->cachedService = GetService(reference); } catch (const ServiceException&) { - return 0; + return TTT::DefaultValue(); } } -template -void ServiceTracker::Remove(const ServiceReference& reference) +template +void ServiceTracker::Remove(const ServiceReferenceT& reference) { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return; } t->Untrack(reference, ServiceEvent()); } -template -int ServiceTracker::Size() const +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 +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 +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 +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) +template +typename ServiceTracker::T +ServiceTracker::AddingService(const ServiceReferenceT& reference) { - return dynamic_cast(d->context->GetService(reference)); + return TTT::ConvertToTrackedType(d->context->GetService(reference)); } -template -void ServiceTracker::ModifiedService(const ServiceReference& /*reference*/, T /*service*/) +template +void ServiceTracker::ModifiedService(const ServiceReferenceT& /*reference*/, T /*service*/) { /* do nothing */ } -template -void ServiceTracker::RemovedService(const ServiceReference& reference, T /*service*/) +template +void ServiceTracker::RemovedService(const ServiceReferenceT& reference, T /*service*/) { d->context->UngetService(reference); } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceTrackerCustomizer.h b/Core/CppMicroServices/src/service/usServiceTrackerCustomizer.h similarity index 91% rename from Core/Code/CppMicroServices/src/service/usServiceTrackerCustomizer.h rename to Core/CppMicroServices/src/service/usServiceTrackerCustomizer.h index f3704a7930..f7aa7e0eb1 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceTrackerCustomizer.h +++ b/Core/CppMicroServices/src/service/usServiceTrackerCustomizer.h @@ -1,113 +1,117 @@ /*============================================================================= 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 S The type of the service being tracked * \tparam T The type of the tracked object. * \remarks This class is thread safe. */ -template +template struct ServiceTrackerCustomizer { + typedef S ServiceT; + typedef ServiceReference ServiceReferenceT; + 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; + virtual T AddingService(const ServiceReferenceT& 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; + virtual void ModifiedService(const ServiceReferenceT& 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; + virtual void RemovedService(const ServiceReferenceT& reference, T service) = 0; }; US_END_NAMESPACE #endif // USSERVICETRACKERCUSTOMIZER_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.h b/Core/CppMicroServices/src/service/usServiceTrackerPrivate.h similarity index 74% rename from Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.h rename to Core/CppMicroServices/src/service/usServiceTrackerPrivate.h index 1229b68ca0..0d0d4f3efa 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.h +++ b/Core/CppMicroServices/src/service/usServiceTrackerPrivate.h @@ -1,172 +1,172 @@ /*============================================================================= 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 > +template +class ServiceTrackerPrivate : US_DEFAULT_THREADING > { public: - ServiceTrackerPrivate(ServiceTracker* st, + typedef typename TTT::TrackedType T; + + ServiceTrackerPrivate(ServiceTracker* st, ModuleContext* context, - const ServiceReference& reference, - ServiceTrackerCustomizer* customizer); + const ServiceReference& reference, + ServiceTrackerCustomizer* customizer); - ServiceTrackerPrivate(ServiceTracker* st, + ServiceTrackerPrivate(ServiceTracker* st, ModuleContext* context, const std::string& clazz, - ServiceTrackerCustomizer* customizer); + ServiceTrackerCustomizer* customizer); - ServiceTrackerPrivate(ServiceTracker* st, + ServiceTrackerPrivate(ServiceTracker* st, ModuleContext* context, const LDAPFilter& filter, - ServiceTrackerCustomizer* customizer); + 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); + std::vector > GetInitialReferences(const std::string& className, + const std::string& filterString); - void GetServiceReferences_unlocked(std::list& refs, TrackedService* t) const; + void GetServiceReferences_unlocked(std::vector >& 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; + 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; + ServiceReference trackReference; /** * Tracked services: ServiceReference -> customized Object and * ServiceListenerEntry object */ - TrackedService* trackedService; + 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; + 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; + mutable ServiceReference cachedReference; /** * Cached service object for GetService. - * - * This field is volatile since it is accessed by multiple threads. */ - mutable T volatile cachedService; + mutable T cachedService; private: - inline ServiceTracker* q_func() + inline ServiceTracker* q_func() { - return static_cast *>(q_ptr); + return static_cast *>(q_ptr); } - inline const ServiceTracker* q_func() const + inline const ServiceTracker* q_func() const { - return static_cast *>(q_ptr); + return static_cast *>(q_ptr); } - friend class ServiceTracker; + friend class ServiceTracker; - ServiceTracker * const q_ptr; + 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/CppMicroServices/src/service/usServiceTrackerPrivate.tpp similarity index 59% rename from Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.tpp rename to Core/CppMicroServices/src/service/usServiceTrackerPrivate.tpp index e48033f6a1..e4f7fd6e2b 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.tpp +++ b/Core/CppMicroServices/src/service/usServiceTrackerPrivate.tpp @@ -1,144 +1,155 @@ /*============================================================================= 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) +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) + trackedService(0), cachedReference(), cachedService(TTT::DefaultValue()), 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, +template +ServiceTrackerPrivate::ServiceTrackerPrivate( + ServiceTracker* st, ModuleContext* context, const std::string& clazz, - ServiceTrackerCustomizer* customizer) + ServiceTrackerCustomizer* customizer) : context(context), customizer(customizer), trackClass(clazz), - trackReference(0), trackedService(0), cachedReference(0), - cachedService(0), q_ptr(st) + trackReference(), trackedService(0), cachedReference(), + cachedService(TTT::DefaultValue()), 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, +template +ServiceTrackerPrivate::ServiceTrackerPrivate( + ServiceTracker* st, ModuleContext* context, const LDAPFilter& filter, - ServiceTrackerCustomizer* customizer) + ServiceTrackerCustomizer* customizer) : context(context), filter(filter), customizer(customizer), - listenerFilter(filter.ToString()), trackReference(0), - trackedService(0), cachedReference(0), cachedService(0), q_ptr(st) + listenerFilter(filter.ToString()), trackReference(), + trackedService(0), cachedReference(), cachedService(TTT::DefaultValue()), 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 +ServiceTrackerPrivate::~ServiceTrackerPrivate() { } -template -std::list ServiceTrackerPrivate::GetInitialReferences( +template +std::vector > ServiceTrackerPrivate::GetInitialReferences( const std::string& className, const std::string& filterString) { - return context->GetServiceReferences(className, filterString); + std::vector > result; + std::vector refs = context->GetServiceReferences(className, filterString); + for(std::vector::const_iterator iter = refs.begin(); + iter != refs.end(); ++iter) + { + ServiceReference ref(*iter); + if (ref) + { + result.push_back(ref); + } + } + return result; } -template -void ServiceTrackerPrivate::GetServiceReferences_unlocked(std::list& refs, TrackedService* t) const +template +void ServiceTrackerPrivate::GetServiceReferences_unlocked(std::vector >& refs, TrackedService* t) const { if (t->Size() == 0) { return; } t->GetTracked(refs); } -template -TrackedService* ServiceTrackerPrivate::Tracked() const +template +TrackedService* ServiceTrackerPrivate::Tracked() const { return trackedService; } -template -void ServiceTrackerPrivate::Modified() +template +void ServiceTrackerPrivate::Modified() { cachedReference = 0; /* clear cached value */ - cachedService = 0; /* clear cached value */ + TTT::Dispose(cachedService); /* 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/CppMicroServices/src/service/usTrackedService.tpp similarity index 72% rename from Core/Code/CppMicroServices/src/service/usTrackedService.tpp rename to Core/CppMicroServices/src/service/usTrackedService.tpp index 8917c200fd..8851affbbe 100644 --- a/Core/Code/CppMicroServices/src/service/usTrackedService.tpp +++ b/Core/CppMicroServices/src/service/usTrackedService.tpp @@ -1,123 +1,124 @@ /*============================================================================= 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) +template +TrackedService::TrackedService(ServiceTracker* serviceTracker, + ServiceTrackerCustomizer* customizer) : serviceTracker(serviceTracker), customizer(customizer) { } -template -void TrackedService::ServiceChanged(const ServiceEvent event) +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(); + ServiceReference reference = event.GetServiceReference(InterfaceT()); 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() +template +void TrackedService::Modified() { Superclass::Modified(); /* increment the modification count */ serviceTracker->d->Modified(); } -template -T TrackedService::CustomizerAdding(ServiceReference item, +template +typename TrackedService::T +TrackedService::CustomizerAdding(ServiceReference item, const ServiceEvent& /*related*/) { return customizer->AddingService(item); } -template -void TrackedService::CustomizerModified(ServiceReference item, - const ServiceEvent& /*related*/, - T object) +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) +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/CppMicroServices/src/service/usTrackedServiceListener_p.h similarity index 96% rename from Core/Code/CppMicroServices/src/service/usTrackedServiceListener_p.h rename to Core/CppMicroServices/src/service/usTrackedServiceListener_p.h index f70aa53365..7870bdbfd5 100644 --- a/Core/Code/CppMicroServices/src/service/usTrackedServiceListener_p.h +++ b/Core/CppMicroServices/src/service/usTrackedServiceListener_p.h @@ -1,51 +1,51 @@ /*============================================================================= 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 +struct TrackedServiceListener { 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/CppMicroServices/src/service/usTrackedService_p.h similarity index 81% rename from Core/Code/CppMicroServices/src/service/usTrackedService_p.h rename to Core/CppMicroServices/src/service/usTrackedService_p.h index 79b366e217..7f0aa6378f 100644 --- a/Core/Code/CppMicroServices/src/service/usTrackedService_p.h +++ b/Core/CppMicroServices/src/service/usTrackedService_p.h @@ -1,107 +1,110 @@ /*============================================================================= 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 +template class TrackedService : public TrackedServiceListener, - public ModuleAbstractTracked + public ModuleAbstractTracked, TTT, ServiceEvent> { public: - TrackedService(ServiceTracker* serviceTracker, - ServiceTrackerCustomizer* customizer); + + typedef typename TTT::TrackedType T; + + 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; + typedef ModuleAbstractTracked, TTT, ServiceEvent> Superclass; - ServiceTracker* serviceTracker; - ServiceTrackerCustomizer* customizer; + 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); + 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, + 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, + 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/CppMicroServices/src/util/dirent_win32_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/dirent_win32_p.h rename to Core/CppMicroServices/src/util/dirent_win32_p.h diff --git a/Core/CppMicroServices/src/util/json_p.h b/Core/CppMicroServices/src/util/json_p.h new file mode 100644 index 0000000000..0ab8e50d88 --- /dev/null +++ b/Core/CppMicroServices/src/util/json_p.h @@ -0,0 +1,1855 @@ +/// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/). +/// It is intented to be used with #include + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + +/* +The JsonCpp library's source code, including accompanying documentation, +tests and demonstration applications, are licensed under the following +conditions... + +The author (Baptiste Lepilleur) explicitly disclaims copyright in all +jurisdictions which recognize such a disclaimer. In such jurisdictions, +this software is released into the Public Domain. + +In jurisdictions which do not recognize Public Domain property (e.g. Germany as of +2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is +released under the terms of the MIT License (see below). + +In jurisdictions which recognize Public Domain property, the user of this +software may choose to accept it either as 1) Public Domain, 2) under the +conditions of the MIT License (see below), or 3) under the terms of dual +Public Domain/MIT License conditions described here, as they choose. + +The MIT License is about as close to Public Domain as a license can get, and is +described in clear, concise terms at: + + http://en.wikipedia.org/wiki/MIT_License + +The full text of the MIT License follows: + +======================================================================== +Copyright (c) 2007-2010 Baptiste Lepilleur + +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 THE AUTHORS OR COPYRIGHT HOLDERS +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. +======================================================================== +(END LICENSE TEXT) + +The MIT license is compatible with both the GPL and commercial +software, affording one all of the rights of Public Domain with the +minor nuisance of being required to keep the above copyright notice +and license text in the source code. Note also that by accepting the +Public Domain "license" you can re-license your copy using whatever +license you like. + +*/ + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + + + + + +#ifndef JSON_AMALGATED_H_INCLUDED +# define JSON_AMALGATED_H_INCLUDED +/// If defined, indicates that the source file is amalgated +/// to prevent private header inclusion. +#define JSON_IS_AMALGATED + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/config.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSON_CONFIG_H_INCLUDED +# define JSON_CONFIG_H_INCLUDED + +/// If defined, indicates that json library is embedded in CppTL library. +//# define JSON_IN_CPPTL 1 + +/// If defined, indicates that json may leverage CppTL library +//# define JSON_USE_CPPTL 1 +/// If defined, indicates that cpptl vector based map should be used instead of std::map +/// as Value container. +//# define JSON_USE_CPPTL_SMALLMAP 1 +/// If defined, indicates that Json specific container should be used +/// (hash table & simple deque container with customizable allocator). +/// THIS FEATURE IS STILL EXPERIMENTAL! There is know bugs: See #3177332 +//# define JSON_VALUE_USE_INTERNAL_MAP 1 +/// Force usage of standard new/malloc based allocator instead of memory pool based allocator. +/// The memory pools allocator used optimization (initializing Value and ValueInternalLink +/// as if it was a POD) that may cause some validation tool to report errors. +/// Only has effects if JSON_VALUE_USE_INTERNAL_MAP is defined. +//# define JSON_USE_SIMPLE_INTERNAL_ALLOCATOR 1 + +/// If defined, indicates that Json use exception to report invalid type manipulation +/// instead of C assert macro. +# define JSON_USE_EXCEPTION 1 + +/// If defined, indicates that the source file is amalgated +/// to prevent private header inclusion. +/// Remarks: it is automatically defined in the generated amalgated header. +#define JSON_IS_AMALGAMATION + + +# ifdef JSON_IN_CPPTL +# include +# ifndef JSON_USE_CPPTL +# define JSON_USE_CPPTL 1 +# endif +# endif + +# ifdef JSON_IN_CPPTL +# define JSON_API CPPTL_API +# elif defined(JSON_DLL_BUILD) +# define JSON_API __declspec(dllexport) +# elif defined(JSON_DLL) +# define JSON_API __declspec(dllimport) +# else +# define JSON_API +# endif + +// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for integer +// Storages, and 64 bits integer support is disabled. +// #define JSON_NO_INT64 1 + +#if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC 6 +// Microsoft Visual Studio 6 only support conversion from __int64 to double +// (no conversion from unsigned __int64). +#define JSON_USE_INT64_DOUBLE_CONVERSION 1 +#endif // if defined(_MSC_VER) && _MSC_VER < 1200 // MSVC 6 + +#if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008 +/// Indicates that the following function is deprecated. +# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message)) +#endif + +#if !defined(JSONCPP_DEPRECATED) +# define JSONCPP_DEPRECATED(message) +#endif // if !defined(JSONCPP_DEPRECATED) + +namespace Json { + typedef int Int; + typedef unsigned int UInt; +# if defined(JSON_NO_INT64) + typedef int LargestInt; + typedef unsigned int LargestUInt; +# undef JSON_HAS_INT64 +# else // if defined(JSON_NO_INT64) + // For Microsoft Visual use specific types as long long is not supported +# if defined(_MSC_VER) // Microsoft Visual Studio + typedef __int64 Int64; + typedef unsigned __int64 UInt64; +# else // if defined(_MSC_VER) // Other platforms, use long long + typedef long long int Int64; + typedef unsigned long long int UInt64; +# endif // if defined(_MSC_VER) + typedef Int64 LargestInt; + typedef UInt64 LargestUInt; +# define JSON_HAS_INT64 +# endif // if defined(JSON_NO_INT64) +} // end namespace Json + + +#endif // JSON_CONFIG_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/config.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/forwards.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSON_FORWARDS_H_INCLUDED +# define JSON_FORWARDS_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "config.h" +#endif // if !defined(JSON_IS_AMALGAMATION) + +namespace Json { + + // writer.h + class FastWriter; + class StyledWriter; + + // reader.h + class Reader; + + // features.h + class Features; + + // value.h + typedef unsigned int ArrayIndex; + class StaticString; + class Path; + class PathArgument; + class Value; + class ValueIteratorBase; + class ValueIterator; + class ValueConstIterator; +#ifdef JSON_VALUE_USE_INTERNAL_MAP + class ValueMapAllocator; + class ValueInternalLink; + class ValueInternalArray; + class ValueInternalMap; +#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP + +} // namespace Json + + +#endif // JSON_FORWARDS_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/forwards.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/features.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef CPPTL_JSON_FEATURES_H_INCLUDED +# define CPPTL_JSON_FEATURES_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "forwards.h" +#endif // if !defined(JSON_IS_AMALGAMATION) + +namespace Json { + + /** \brief Configuration passed to reader and writer. + * This configuration object can be used to force the Reader or Writer + * to behave in a standard conforming way. + */ + class JSON_API Features + { + public: + /** \brief A configuration that allows all features and assumes all strings are UTF-8. + * - C & C++ comments are allowed + * - Root object can be any JSON value + * - Assumes Value strings are encoded in UTF-8 + */ + static Features all(); + + /** \brief A configuration that is strictly compatible with the JSON specification. + * - Comments are forbidden. + * - Root object must be either an array or an object value. + * - Assumes Value strings are encoded in UTF-8 + */ + static Features strictMode(); + + /** \brief Initialize the configuration like JsonConfig::allFeatures; + */ + Features(); + + /// \c true if comments are allowed. Default: \c true. + bool allowComments_; + + /// \c true if root must be either an array or an object value. Default: \c false. + bool strictRoot_; + }; + +} // namespace Json + +#endif // CPPTL_JSON_FEATURES_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/features.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/value.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef CPPTL_JSON_H_INCLUDED +# define CPPTL_JSON_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "forwards.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +# include +# include + +# ifndef JSON_USE_CPPTL_SMALLMAP +# include +# else +# include +# endif +# ifdef JSON_USE_CPPTL +# include +# endif + +/** \brief JSON (JavaScript Object Notation). + */ +namespace Json { + + /** \brief Type of the value held by a Value object. + */ + enum ValueType + { + nullValue = 0, ///< 'null' value + intValue, ///< signed integer value + uintValue, ///< unsigned integer value + realValue, ///< double value + stringValue, ///< UTF-8 string value + booleanValue, ///< bool value + arrayValue, ///< array value (ordered list) + objectValue ///< object value (collection of name/value pairs). + }; + + enum CommentPlacement + { + commentBefore = 0, ///< a comment placed on the line before a value + commentAfterOnSameLine, ///< a comment just after a value on the same line + commentAfter, ///< a comment on the line after a value (only make sense for root value) + numberOfCommentPlacement + }; + +//# ifdef JSON_USE_CPPTL +// typedef CppTL::AnyEnumerator EnumMemberNames; +// typedef CppTL::AnyEnumerator EnumValues; +//# endif + + /** \brief Lightweight wrapper to tag static string. + * + * Value constructor and objectValue member assignement takes advantage of the + * StaticString and avoid the cost of string duplication when storing the + * string or the member name. + * + * Example of usage: + * \code + * Json::Value aValue( StaticString("some text") ); + * Json::Value object; + * static const StaticString code("code"); + * object[code] = 1234; + * \endcode + */ + class JSON_API StaticString + { + public: + explicit StaticString( const char *czstring ) + : str_( czstring ) + { + } + + operator const char *() const + { + return str_; + } + + const char *c_str() const + { + return str_; + } + + private: + const char *str_; + }; + + /** \brief Represents a JSON value. + * + * This class is a discriminated union wrapper that can represents a: + * - signed integer [range: Value::minInt - Value::maxInt] + * - unsigned integer (range: 0 - Value::maxUInt) + * - double + * - UTF-8 string + * - boolean + * - 'null' + * - an ordered list of Value + * - collection of name/value pairs (javascript object) + * + * The type of the held value is represented by a #ValueType and + * can be obtained using type(). + * + * values of an #objectValue or #arrayValue can be accessed using operator[]() methods. + * Non const methods will automatically create the a #nullValue element + * if it does not exist. + * The sequence of an #arrayValue will be automatically resize and initialized + * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue. + * + * The get() methods can be used to obtanis default value in the case the required element + * does not exist. + * + * It is possible to iterate over the list of a #objectValue values using + * the getMemberNames() method. + */ + class JSON_API Value + { + friend class ValueIteratorBase; +# ifdef JSON_VALUE_USE_INTERNAL_MAP + friend class ValueInternalLink; + friend class ValueInternalMap; +# endif + public: + typedef std::vector Members; + typedef ValueIterator iterator; + typedef ValueConstIterator const_iterator; + typedef Json::UInt UInt; + typedef Json::Int Int; +# if defined(JSON_HAS_INT64) + typedef Json::UInt64 UInt64; + typedef Json::Int64 Int64; +#endif // defined(JSON_HAS_INT64) + typedef Json::LargestInt LargestInt; + typedef Json::LargestUInt LargestUInt; + typedef Json::ArrayIndex ArrayIndex; + + static const Value null; + /// Minimum signed integer value that can be stored in a Json::Value. + static const LargestInt minLargestInt; + /// Maximum signed integer value that can be stored in a Json::Value. + static const LargestInt maxLargestInt; + /// Maximum unsigned integer value that can be stored in a Json::Value. + static const LargestUInt maxLargestUInt; + + /// Minimum signed int value that can be stored in a Json::Value. + static const Int minInt; + /// Maximum signed int value that can be stored in a Json::Value. + static const Int maxInt; + /// Maximum unsigned int value that can be stored in a Json::Value. + static const UInt maxUInt; + + /// Minimum signed 64 bits int value that can be stored in a Json::Value. + static const Int64 minInt64; + /// Maximum signed 64 bits int value that can be stored in a Json::Value. + static const Int64 maxInt64; + /// Maximum unsigned 64 bits int value that can be stored in a Json::Value. + static const UInt64 maxUInt64; + + private: +#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION +# ifndef JSON_VALUE_USE_INTERNAL_MAP + class CZString + { + public: + enum DuplicationPolicy + { + noDuplication = 0, + duplicate, + duplicateOnCopy + }; + CZString( ArrayIndex index ); + CZString( const char *cstr, DuplicationPolicy allocate ); + CZString( const CZString &other ); + ~CZString(); + CZString &operator =( const CZString &other ); + bool operator<( const CZString &other ) const; + bool operator==( const CZString &other ) const; + ArrayIndex index() const; + const char *c_str() const; + bool isStaticString() const; + private: + void swap( CZString &other ); + const char *cstr_; + ArrayIndex index_; + }; + + public: +# ifndef JSON_USE_CPPTL_SMALLMAP + typedef std::map ObjectValues; +# else + typedef CppTL::SmallMap ObjectValues; +# endif // ifndef JSON_USE_CPPTL_SMALLMAP +# endif // ifndef JSON_VALUE_USE_INTERNAL_MAP +#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + + public: + /** \brief Create a default Value of the given type. + + This is a very useful constructor. + To create an empty array, pass arrayValue. + To create an empty object, pass objectValue. + Another Value can then be set to this one by assignment. + This is useful since clear() and resize() will not alter types. + + Examples: + \code + Json::Value null_value; // null + Json::Value arr_value(Json::arrayValue); // [] + Json::Value obj_value(Json::objectValue); // {} + \endcode + */ + Value( ValueType type = nullValue ); + Value( Int value ); + Value( UInt value ); +#if defined(JSON_HAS_INT64) + Value( Int64 value ); + Value( UInt64 value ); +#endif // if defined(JSON_HAS_INT64) + Value( double value ); + Value( const char *value ); + Value( const char *beginValue, const char *endValue ); + /** \brief Constructs a value from a static string. + + * Like other value string constructor but do not duplicate the string for + * internal storage. The given string must remain alive after the call to this + * constructor. + * Example of usage: + * \code + * Json::Value aValue( StaticString("some text") ); + * \endcode + */ + Value( const StaticString &value ); + Value( const std::string &value ); +# ifdef JSON_USE_CPPTL + Value( const CppTL::ConstString &value ); +# endif + Value( bool value ); + Value( const Value &other ); + ~Value(); + + Value &operator=( const Value &other ); + /// Swap values. + /// \note Currently, comments are intentionally not swapped, for + /// both logic and efficiency. + void swap( Value &other ); + + ValueType type() const; + + bool operator <( const Value &other ) const; + bool operator <=( const Value &other ) const; + bool operator >=( const Value &other ) const; + bool operator >( const Value &other ) const; + + bool operator ==( const Value &other ) const; + bool operator !=( const Value &other ) const; + + int compare( const Value &other ) const; + + const char *asCString() const; + std::string asString() const; +# ifdef JSON_USE_CPPTL + CppTL::ConstString asConstString() const; +# endif + Int asInt() const; + UInt asUInt() const; + Int64 asInt64() const; + UInt64 asUInt64() const; + LargestInt asLargestInt() const; + LargestUInt asLargestUInt() const; + float asFloat() const; + double asDouble() const; + bool asBool() const; + + bool isNull() const; + bool isBool() const; + bool isInt() const; + bool isUInt() const; + bool isIntegral() const; + bool isDouble() const; + bool isNumeric() const; + bool isString() const; + bool isArray() const; + bool isObject() const; + + bool isConvertibleTo( ValueType other ) const; + + /// Number of values in array or object + ArrayIndex size() const; + + /// \brief Return true if empty array, empty object, or null; + /// otherwise, false. + bool empty() const; + + /// Return isNull() + bool operator!() const; + + /// Remove all object members and array elements. + /// \pre type() is arrayValue, objectValue, or nullValue + /// \post type() is unchanged + void clear(); + + /// Resize the array to size elements. + /// New elements are initialized to null. + /// May only be called on nullValue or arrayValue. + /// \pre type() is arrayValue or nullValue + /// \post type() is arrayValue + void resize( ArrayIndex size ); + + /// Access an array element (zero based index ). + /// If the array contains less than index element, then null value are inserted + /// in the array so that its size is index+1. + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + Value &operator[]( ArrayIndex index ); + + /// Access an array element (zero based index ). + /// If the array contains less than index element, then null value are inserted + /// in the array so that its size is index+1. + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + Value &operator[]( int index ); + + /// Access an array element (zero based index ) + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + const Value &operator[]( ArrayIndex index ) const; + + /// Access an array element (zero based index ) + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + const Value &operator[]( int index ) const; + + /// If the array contains at least index+1 elements, returns the element value, + /// otherwise returns defaultValue. + Value get( ArrayIndex index, + const Value &defaultValue ) const; + /// Return true if index < size(). + bool isValidIndex( ArrayIndex index ) const; + /// \brief Append value to array at the end. + /// + /// Equivalent to jsonvalue[jsonvalue.size()] = value; + Value &append( const Value &value ); + + /// Access an object value by name, create a null member if it does not exist. + Value &operator[]( const char *key ); + /// Access an object value by name, returns null if there is no member with that name. + const Value &operator[]( const char *key ) const; + /// Access an object value by name, create a null member if it does not exist. + Value &operator[]( const std::string &key ); + /// Access an object value by name, returns null if there is no member with that name. + const Value &operator[]( const std::string &key ) const; + /** \brief Access an object value by name, create a null member if it does not exist. + + * If the object as no entry for that name, then the member name used to store + * the new entry is not duplicated. + * Example of use: + * \code + * Json::Value object; + * static const StaticString code("code"); + * object[code] = 1234; + * \endcode + */ + Value &operator[]( const StaticString &key ); +# ifdef JSON_USE_CPPTL + /// Access an object value by name, create a null member if it does not exist. + Value &operator[]( const CppTL::ConstString &key ); + /// Access an object value by name, returns null if there is no member with that name. + const Value &operator[]( const CppTL::ConstString &key ) const; +# endif + /// Return the member named key if it exist, defaultValue otherwise. + Value get( const char *key, + const Value &defaultValue ) const; + /// Return the member named key if it exist, defaultValue otherwise. + Value get( const std::string &key, + const Value &defaultValue ) const; +# ifdef JSON_USE_CPPTL + /// Return the member named key if it exist, defaultValue otherwise. + Value get( const CppTL::ConstString &key, + const Value &defaultValue ) const; +# endif + /// \brief Remove and return the named member. + /// + /// Do nothing if it did not exist. + /// \return the removed Value, or null. + /// \pre type() is objectValue or nullValue + /// \post type() is unchanged + Value removeMember( const char* key ); + /// Same as removeMember(const char*) + Value removeMember( const std::string &key ); + + /// Return true if the object has a member named key. + bool isMember( const char *key ) const; + /// Return true if the object has a member named key. + bool isMember( const std::string &key ) const; +# ifdef JSON_USE_CPPTL + /// Return true if the object has a member named key. + bool isMember( const CppTL::ConstString &key ) const; +# endif + + /// \brief Return a list of the member names. + /// + /// If null, return an empty list. + /// \pre type() is objectValue or nullValue + /// \post if type() was nullValue, it remains nullValue + Members getMemberNames() const; + +//# ifdef JSON_USE_CPPTL +// EnumMemberNames enumMemberNames() const; +// EnumValues enumValues() const; +//# endif + + /// Comments must be //... or /* ... */ + void setComment( const char *comment, + CommentPlacement placement ); + /// Comments must be //... or /* ... */ + void setComment( const std::string &comment, + CommentPlacement placement ); + bool hasComment( CommentPlacement placement ) const; + /// Include delimiters and embedded newlines. + std::string getComment( CommentPlacement placement ) const; + + std::string toStyledString() const; + + const_iterator begin() const; + const_iterator end() const; + + iterator begin(); + iterator end(); + + private: + Value &resolveReference( const char *key, + bool isStatic ); + +# ifdef JSON_VALUE_USE_INTERNAL_MAP + inline bool isItemAvailable() const + { + return itemIsUsed_ == 0; + } + + inline void setItemUsed( bool isUsed = true ) + { + itemIsUsed_ = isUsed ? 1 : 0; + } + + inline bool isMemberNameStatic() const + { + return memberNameIsStatic_ == 0; + } + + inline void setMemberNameIsStatic( bool isStatic ) + { + memberNameIsStatic_ = isStatic ? 1 : 0; + } +# endif // # ifdef JSON_VALUE_USE_INTERNAL_MAP + + private: + struct CommentInfo + { + CommentInfo(); + ~CommentInfo(); + + void setComment( const char *text ); + + char *comment_; + }; + + //struct MemberNamesTransform + //{ + // typedef const char *result_type; + // const char *operator()( const CZString &name ) const + // { + // return name.c_str(); + // } + //}; + + union ValueHolder + { + LargestInt int_; + LargestUInt uint_; + double real_; + bool bool_; + char *string_; +# ifdef JSON_VALUE_USE_INTERNAL_MAP + ValueInternalArray *array_; + ValueInternalMap *map_; +#else + ObjectValues *map_; +# endif + } value_; + ValueType type_ : 8; + int allocated_ : 1; // Notes: if declared as bool, bitfield is useless. +# ifdef JSON_VALUE_USE_INTERNAL_MAP + unsigned int itemIsUsed_ : 1; // used by the ValueInternalMap container. + int memberNameIsStatic_ : 1; // used by the ValueInternalMap container. +# endif + CommentInfo *comments_; + }; + + + /** \brief Experimental and untested: represents an element of the "path" to access a node. + */ + class PathArgument + { + public: + friend class Path; + + PathArgument(); + PathArgument( ArrayIndex index ); + PathArgument( const char *key ); + PathArgument( const std::string &key ); + + private: + enum Kind + { + kindNone = 0, + kindIndex, + kindKey + }; + std::string key_; + ArrayIndex index_; + Kind kind_; + }; + + /** \brief Experimental and untested: represents a "path" to access a node. + * + * Syntax: + * - "." => root node + * - ".[n]" => elements at index 'n' of root node (an array value) + * - ".name" => member named 'name' of root node (an object value) + * - ".name1.name2.name3" + * - ".[0][1][2].name1[3]" + * - ".%" => member name is provided as parameter + * - ".[%]" => index is provied as parameter + */ + class Path + { + public: + Path( const std::string &path, + const PathArgument &a1 = PathArgument(), + const PathArgument &a2 = PathArgument(), + const PathArgument &a3 = PathArgument(), + const PathArgument &a4 = PathArgument(), + const PathArgument &a5 = PathArgument() ); + + const Value &resolve( const Value &root ) const; + Value resolve( const Value &root, + const Value &defaultValue ) const; + /// Creates the "path" to access the specified node and returns a reference on the node. + Value &make( Value &root ) const; + + private: + typedef std::vector InArgs; + typedef std::vector Args; + + void makePath( const std::string &path, + const InArgs &in ); + void addPathInArg( const std::string &path, + const InArgs &in, + InArgs::const_iterator &itInArg, + PathArgument::Kind kind ); + void invalidPath( const std::string &path, + int location ); + + Args args_; + }; + + + +#ifdef JSON_VALUE_USE_INTERNAL_MAP + /** \brief Allocator to customize Value internal map. + * Below is an example of a simple implementation (default implementation actually + * use memory pool for speed). + * \code + class DefaultValueMapAllocator : public ValueMapAllocator + { + public: // overridden from ValueMapAllocator + virtual ValueInternalMap *newMap() + { + return new ValueInternalMap(); + } + + virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) + { + return new ValueInternalMap( other ); + } + + virtual void destructMap( ValueInternalMap *map ) + { + delete map; + } + + virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) + { + return new ValueInternalLink[size]; + } + + virtual void releaseMapBuckets( ValueInternalLink *links ) + { + delete [] links; + } + + virtual ValueInternalLink *allocateMapLink() + { + return new ValueInternalLink(); + } + + virtual void releaseMapLink( ValueInternalLink *link ) + { + delete link; + } + }; + * \endcode + */ + class JSON_API ValueMapAllocator + { + public: + virtual ~ValueMapAllocator(); + virtual ValueInternalMap *newMap() = 0; + virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) = 0; + virtual void destructMap( ValueInternalMap *map ) = 0; + virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) = 0; + virtual void releaseMapBuckets( ValueInternalLink *links ) = 0; + virtual ValueInternalLink *allocateMapLink() = 0; + virtual void releaseMapLink( ValueInternalLink *link ) = 0; + }; + + /** \brief ValueInternalMap hash-map bucket chain link (for internal use only). + * \internal previous_ & next_ allows for bidirectional traversal. + */ + class JSON_API ValueInternalLink + { + public: + enum { itemPerLink = 6 }; // sizeof(ValueInternalLink) = 128 on 32 bits architecture. + enum InternalFlags { + flagAvailable = 0, + flagUsed = 1 + }; + + ValueInternalLink(); + + ~ValueInternalLink(); + + Value items_[itemPerLink]; + char *keys_[itemPerLink]; + ValueInternalLink *previous_; + ValueInternalLink *next_; + }; + + + /** \brief A linked page based hash-table implementation used internally by Value. + * \internal ValueInternalMap is a tradional bucket based hash-table, with a linked + * list in each bucket to handle collision. There is an addional twist in that + * each node of the collision linked list is a page containing a fixed amount of + * value. This provides a better compromise between memory usage and speed. + * + * Each bucket is made up of a chained list of ValueInternalLink. The last + * link of a given bucket can be found in the 'previous_' field of the following bucket. + * The last link of the last bucket is stored in tailLink_ as it has no following bucket. + * Only the last link of a bucket may contains 'available' item. The last link always + * contains at least one element unless is it the bucket one very first link. + */ + class JSON_API ValueInternalMap + { + friend class ValueIteratorBase; + friend class Value; + public: + typedef unsigned int HashKey; + typedef unsigned int BucketIndex; + +# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + struct IteratorState + { + IteratorState() + : map_(0) + , link_(0) + , itemIndex_(0) + , bucketIndex_(0) + { + } + ValueInternalMap *map_; + ValueInternalLink *link_; + BucketIndex itemIndex_; + BucketIndex bucketIndex_; + }; +# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + + ValueInternalMap(); + ValueInternalMap( const ValueInternalMap &other ); + ValueInternalMap &operator =( const ValueInternalMap &other ); + ~ValueInternalMap(); + + void swap( ValueInternalMap &other ); + + BucketIndex size() const; + + void clear(); + + bool reserveDelta( BucketIndex growth ); + + bool reserve( BucketIndex newItemCount ); + + const Value *find( const char *key ) const; + + Value *find( const char *key ); + + Value &resolveReference( const char *key, + bool isStatic ); + + void remove( const char *key ); + + void doActualRemove( ValueInternalLink *link, + BucketIndex index, + BucketIndex bucketIndex ); + + ValueInternalLink *&getLastLinkInBucket( BucketIndex bucketIndex ); + + Value &setNewItem( const char *key, + bool isStatic, + ValueInternalLink *link, + BucketIndex index ); + + Value &unsafeAdd( const char *key, + bool isStatic, + HashKey hashedKey ); + + HashKey hash( const char *key ) const; + + int compare( const ValueInternalMap &other ) const; + + private: + void makeBeginIterator( IteratorState &it ) const; + void makeEndIterator( IteratorState &it ) const; + static bool equals( const IteratorState &x, const IteratorState &other ); + static void increment( IteratorState &iterator ); + static void incrementBucket( IteratorState &iterator ); + static void decrement( IteratorState &iterator ); + static const char *key( const IteratorState &iterator ); + static const char *key( const IteratorState &iterator, bool &isStatic ); + static Value &value( const IteratorState &iterator ); + static int distance( const IteratorState &x, const IteratorState &y ); + + private: + ValueInternalLink *buckets_; + ValueInternalLink *tailLink_; + BucketIndex bucketsSize_; + BucketIndex itemCount_; + }; + + /** \brief A simplified deque implementation used internally by Value. + * \internal + * It is based on a list of fixed "page", each page contains a fixed number of items. + * Instead of using a linked-list, a array of pointer is used for fast item look-up. + * Look-up for an element is as follow: + * - compute page index: pageIndex = itemIndex / itemsPerPage + * - look-up item in page: pages_[pageIndex][itemIndex % itemsPerPage] + * + * Insertion is amortized constant time (only the array containing the index of pointers + * need to be reallocated when items are appended). + */ + class JSON_API ValueInternalArray + { + friend class Value; + friend class ValueIteratorBase; + public: + enum { itemsPerPage = 8 }; // should be a power of 2 for fast divide and modulo. + typedef Value::ArrayIndex ArrayIndex; + typedef unsigned int PageIndex; + +# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + struct IteratorState // Must be a POD + { + IteratorState() + : array_(0) + , currentPageIndex_(0) + , currentItemIndex_(0) + { + } + ValueInternalArray *array_; + Value **currentPageIndex_; + unsigned int currentItemIndex_; + }; +# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + + ValueInternalArray(); + ValueInternalArray( const ValueInternalArray &other ); + ValueInternalArray &operator =( const ValueInternalArray &other ); + ~ValueInternalArray(); + void swap( ValueInternalArray &other ); + + void clear(); + void resize( ArrayIndex newSize ); + + Value &resolveReference( ArrayIndex index ); + + Value *find( ArrayIndex index ) const; + + ArrayIndex size() const; + + int compare( const ValueInternalArray &other ) const; + + private: + static bool equals( const IteratorState &x, const IteratorState &other ); + static void increment( IteratorState &iterator ); + static void decrement( IteratorState &iterator ); + static Value &dereference( const IteratorState &iterator ); + static Value &unsafeDereference( const IteratorState &iterator ); + static int distance( const IteratorState &x, const IteratorState &y ); + static ArrayIndex indexOf( const IteratorState &iterator ); + void makeBeginIterator( IteratorState &it ) const; + void makeEndIterator( IteratorState &it ) const; + void makeIterator( IteratorState &it, ArrayIndex index ) const; + + void makeIndexValid( ArrayIndex index ); + + Value **pages_; + ArrayIndex size_; + PageIndex pageCount_; + }; + + /** \brief Experimental: do not use. Allocator to customize Value internal array. + * Below is an example of a simple implementation (actual implementation use + * memory pool). + \code +class DefaultValueArrayAllocator : public ValueArrayAllocator +{ +public: // overridden from ValueArrayAllocator + virtual ~DefaultValueArrayAllocator() + { + } + + virtual ValueInternalArray *newArray() + { + return new ValueInternalArray(); + } + + virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) + { + return new ValueInternalArray( other ); + } + + virtual void destruct( ValueInternalArray *array ) + { + delete array; + } + + virtual void reallocateArrayPageIndex( Value **&indexes, + ValueInternalArray::PageIndex &indexCount, + ValueInternalArray::PageIndex minNewIndexCount ) + { + ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1; + if ( minNewIndexCount > newIndexCount ) + newIndexCount = minNewIndexCount; + void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount ); + if ( !newIndexes ) + throw std::bad_alloc(); + indexCount = newIndexCount; + indexes = static_cast( newIndexes ); + } + virtual void releaseArrayPageIndex( Value **indexes, + ValueInternalArray::PageIndex indexCount ) + { + if ( indexes ) + free( indexes ); + } + + virtual Value *allocateArrayPage() + { + return static_cast( malloc( sizeof(Value) * ValueInternalArray::itemsPerPage ) ); + } + + virtual void releaseArrayPage( Value *value ) + { + if ( value ) + free( value ); + } +}; + \endcode + */ + class JSON_API ValueArrayAllocator + { + public: + virtual ~ValueArrayAllocator(); + virtual ValueInternalArray *newArray() = 0; + virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) = 0; + virtual void destructArray( ValueInternalArray *array ) = 0; + /** \brief Reallocate array page index. + * Reallocates an array of pointer on each page. + * \param indexes [input] pointer on the current index. May be \c NULL. + * [output] pointer on the new index of at least + * \a minNewIndexCount pages. + * \param indexCount [input] current number of pages in the index. + * [output] number of page the reallocated index can handle. + * \b MUST be >= \a minNewIndexCount. + * \param minNewIndexCount Minimum number of page the new index must be able to + * handle. + */ + virtual void reallocateArrayPageIndex( Value **&indexes, + ValueInternalArray::PageIndex &indexCount, + ValueInternalArray::PageIndex minNewIndexCount ) = 0; + virtual void releaseArrayPageIndex( Value **indexes, + ValueInternalArray::PageIndex indexCount ) = 0; + virtual Value *allocateArrayPage() = 0; + virtual void releaseArrayPage( Value *value ) = 0; + }; +#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP + + + /** \brief base class for Value iterators. + * + */ + class ValueIteratorBase + { + public: + typedef unsigned int size_t; + typedef int difference_type; + typedef ValueIteratorBase SelfType; + + ValueIteratorBase(); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + explicit ValueIteratorBase( const Value::ObjectValues::iterator ¤t ); +#else + ValueIteratorBase( const ValueInternalArray::IteratorState &state ); + ValueIteratorBase( const ValueInternalMap::IteratorState &state ); +#endif + + bool operator ==( const SelfType &other ) const + { + return isEqual( other ); + } + + bool operator !=( const SelfType &other ) const + { + return !isEqual( other ); + } + + difference_type operator -( const SelfType &other ) const + { + return computeDistance( other ); + } + + /// Return either the index or the member name of the referenced value as a Value. + Value key() const; + + /// Return the index of the referenced Value. -1 if it is not an arrayValue. + UInt index() const; + + /// Return the member name of the referenced Value. "" if it is not an objectValue. + const char *memberName() const; + + protected: + Value &deref() const; + + void increment(); + + void decrement(); + + difference_type computeDistance( const SelfType &other ) const; + + bool isEqual( const SelfType &other ) const; + + void copy( const SelfType &other ); + + private: +#ifndef JSON_VALUE_USE_INTERNAL_MAP + Value::ObjectValues::iterator current_; + // Indicates that iterator is for a null value. + bool isNull_; +#else + union + { + ValueInternalArray::IteratorState array_; + ValueInternalMap::IteratorState map_; + } iterator_; + bool isArray_; +#endif + }; + + /** \brief const iterator for object and array value. + * + */ + class ValueConstIterator : public ValueIteratorBase + { + friend class Value; + public: + typedef unsigned int size_t; + typedef int difference_type; + typedef const Value &reference; + typedef const Value *pointer; + typedef ValueConstIterator SelfType; + + ValueConstIterator(); + private: + /*! \internal Use by Value to create an iterator. + */ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + explicit ValueConstIterator( const Value::ObjectValues::iterator ¤t ); +#else + ValueConstIterator( const ValueInternalArray::IteratorState &state ); + ValueConstIterator( const ValueInternalMap::IteratorState &state ); +#endif + public: + SelfType &operator =( const ValueIteratorBase &other ); + + SelfType operator++( int ) + { + SelfType temp( *this ); + ++*this; + return temp; + } + + SelfType operator--( int ) + { + SelfType temp( *this ); + --*this; + return temp; + } + + SelfType &operator--() + { + decrement(); + return *this; + } + + SelfType &operator++() + { + increment(); + return *this; + } + + reference operator *() const + { + return deref(); + } + }; + + + /** \brief Iterator for object and array value. + */ + class ValueIterator : public ValueIteratorBase + { + friend class Value; + public: + typedef unsigned int size_t; + typedef int difference_type; + typedef Value &reference; + typedef Value *pointer; + typedef ValueIterator SelfType; + + ValueIterator(); + ValueIterator( const ValueConstIterator &other ); + ValueIterator( const ValueIterator &other ); + private: + /*! \internal Use by Value to create an iterator. + */ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + explicit ValueIterator( const Value::ObjectValues::iterator ¤t ); +#else + ValueIterator( const ValueInternalArray::IteratorState &state ); + ValueIterator( const ValueInternalMap::IteratorState &state ); +#endif + public: + + SelfType &operator =( const SelfType &other ); + + SelfType operator++( int ) + { + SelfType temp( *this ); + ++*this; + return temp; + } + + SelfType operator--( int ) + { + SelfType temp( *this ); + --*this; + return temp; + } + + SelfType &operator--() + { + decrement(); + return *this; + } + + SelfType &operator++() + { + increment(); + return *this; + } + + reference operator *() const + { + return deref(); + } + }; + + +} // namespace Json + + +#endif // CPPTL_JSON_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/value.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/reader.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef CPPTL_JSON_READER_H_INCLUDED +# define CPPTL_JSON_READER_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "features.h" +# include "value.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +# include +# include +# include +# include + +namespace Json { + + /** \brief Unserialize a JSON document into a Value. + * + */ + class JSON_API Reader + { + public: + typedef char Char; + typedef const Char *Location; + + /** \brief Constructs a Reader allowing all features + * for parsing. + */ + Reader(); + + /** \brief Constructs a Reader allowing the specified feature set + * for parsing. + */ + Reader( const Features &features ); + + /** \brief Read a Value from a JSON document. + * \param document UTF-8 encoded string containing the document to read. + * \param root [out] Contains the root value of the document if it was + * successfully parsed. + * \param collectComments \c true to collect comment and allow writing them back during + * serialization, \c false to discard comments. + * This parameter is ignored if Features::allowComments_ + * is \c false. + * \return \c true if the document was successfully parsed, \c false if an error occurred. + */ + bool parse( const std::string &document, + Value &root, + bool collectComments = true ); + + /** \brief Read a Value from a JSON document. + * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the document to read. + * \param endDoc Pointer on the end of the UTF-8 encoded string of the document to read. + \ Must be >= beginDoc. + * \param root [out] Contains the root value of the document if it was + * successfully parsed. + * \param collectComments \c true to collect comment and allow writing them back during + * serialization, \c false to discard comments. + * This parameter is ignored if Features::allowComments_ + * is \c false. + * \return \c true if the document was successfully parsed, \c false if an error occurred. + */ + bool parse( const char *beginDoc, const char *endDoc, + Value &root, + bool collectComments = true ); + + /// \brief Parse from input stream. + /// \see Json::operator>>(std::istream&, Json::Value&). + bool parse( std::istream &is, + Value &root, + bool collectComments = true ); + + /** \brief Returns a user friendly string that list errors in the parsed document. + * \return Formatted error message with the list of errors with their location in + * the parsed document. An empty string is returned if no error occurred + * during parsing. + * \deprecated Use getFormattedErrorMessages() instead (typo fix). + */ + JSONCPP_DEPRECATED("Use getFormattedErrorMessages instead") + std::string getFormatedErrorMessages() const; + + /** \brief Returns a user friendly string that list errors in the parsed document. + * \return Formatted error message with the list of errors with their location in + * the parsed document. An empty string is returned if no error occurred + * during parsing. + */ + std::string getFormattedErrorMessages() const; + + private: + enum TokenType + { + tokenEndOfStream = 0, + tokenObjectBegin, + tokenObjectEnd, + tokenArrayBegin, + tokenArrayEnd, + tokenString, + tokenNumber, + tokenTrue, + tokenFalse, + tokenNull, + tokenArraySeparator, + tokenMemberSeparator, + tokenComment, + tokenError + }; + + class Token + { + public: + TokenType type_; + Location start_; + Location end_; + }; + + class ErrorInfo + { + public: + Token token_; + std::string message_; + Location extra_; + }; + + typedef std::deque Errors; + + bool expectToken( TokenType type, Token &token, const char *message ); + bool readToken( Token &token ); + void skipSpaces(); + bool match( Location pattern, + int patternLength ); + bool readComment(); + bool readCStyleComment(); + bool readCppStyleComment(); + bool readString(); + void readNumber(); + bool readValue(); + bool readObject( Token &token ); + bool readArray( Token &token ); + bool decodeNumber( Token &token ); + bool decodeString( Token &token ); + bool decodeString( Token &token, std::string &decoded ); + bool decodeDouble( Token &token ); + bool decodeUnicodeCodePoint( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ); + bool decodeUnicodeEscapeSequence( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ); + bool addError( const std::string &message, + Token &token, + Location extra = 0 ); + bool recoverFromError( TokenType skipUntilToken ); + bool addErrorAndRecover( const std::string &message, + Token &token, + TokenType skipUntilToken ); + void skipUntilSpace(); + Value ¤tValue(); + Char getNextChar(); + void getLocationLineAndColumn( Location location, + int &line, + int &column ) const; + std::string getLocationLineAndColumn( Location location ) const; + void addComment( Location begin, + Location end, + CommentPlacement placement ); + void skipCommentTokens( Token &token ); + + typedef std::stack Nodes; + Nodes nodes_; + Errors errors_; + std::string document_; + Location begin_; + Location end_; + Location current_; + Location lastValueEnd_; + Value *lastValue_; + std::string commentsBefore_; + Features features_; + bool collectComments_; + }; + + /** \brief Read from 'sin' into 'root'. + + Always keep comments from the input JSON. + + This can be used to read a file into a particular sub-object. + For example: + \code + Json::Value root; + cin >> root["dir"]["file"]; + cout << root; + \endcode + Result: + \verbatim + { + "dir": { + "file": { + // The input stream JSON would be nested here. + } + } + } + \endverbatim + \throw std::exception on parse error. + \see Json::operator<<() + */ + std::istream& operator>>( std::istream&, Value& ); + +} // namespace Json + +#endif // CPPTL_JSON_READER_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/reader.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/writer.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSON_WRITER_H_INCLUDED +# define JSON_WRITER_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "value.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +# include +# include +# include + +namespace Json { + + class Value; + + /** \brief Abstract class for writers. + */ + class JSON_API Writer + { + public: + virtual ~Writer(); + + virtual std::string write( const Value &root ) = 0; + }; + + /** \brief Outputs a Value in JSON format without formatting (not human friendly). + * + * The JSON document is written in a single line. It is not intended for 'human' consumption, + * but may be usefull to support feature such as RPC where bandwith is limited. + * \sa Reader, Value + */ + class JSON_API FastWriter : public Writer + { + public: + FastWriter(); + virtual ~FastWriter(){} + + void enableYAMLCompatibility(); + + public: // overridden from Writer + virtual std::string write( const Value &root ); + + private: + void writeValue( const Value &value ); + + std::string document_; + bool yamlCompatiblityEnabled_; + }; + + /** \brief Writes a Value in JSON format in a human friendly way. + * + * The rules for line break and indent are as follow: + * - Object value: + * - if empty then print {} without indent and line break + * - if not empty the print '{', line break & indent, print one value per line + * and then unindent and line break and print '}'. + * - Array value: + * - if empty then print [] without indent and line break + * - if the array contains no object value, empty array or some other value types, + * and all the values fit on one lines, then print the array on a single line. + * - otherwise, it the values do not fit on one line, or the array contains + * object or non empty array, then print one value per line. + * + * If the Value have comments then they are outputed according to their #CommentPlacement. + * + * \sa Reader, Value, Value::setComment() + */ + class JSON_API StyledWriter: public Writer + { + public: + StyledWriter(); + virtual ~StyledWriter(){} + + public: // overridden from Writer + /** \brief Serialize a Value in JSON format. + * \param root Value to serialize. + * \return String containing the JSON document that represents the root value. + */ + virtual std::string write( const Value &root ); + + private: + void writeValue( const Value &value ); + void writeArrayValue( const Value &value ); + bool isMultineArray( const Value &value ); + void pushValue( const std::string &value ); + void writeIndent(); + void writeWithIndent( const std::string &value ); + void indent(); + void unindent(); + void writeCommentBeforeValue( const Value &root ); + void writeCommentAfterValueOnSameLine( const Value &root ); + bool hasCommentForValue( const Value &value ); + static std::string normalizeEOL( const std::string &text ); + + typedef std::vector ChildValues; + + ChildValues childValues_; + std::string document_; + std::string indentString_; + int rightMargin_; + int indentSize_; + bool addChildValues_; + }; + + /** \brief Writes a Value in JSON format in a human friendly way, + to a stream rather than to a string. + * + * The rules for line break and indent are as follow: + * - Object value: + * - if empty then print {} without indent and line break + * - if not empty the print '{', line break & indent, print one value per line + * and then unindent and line break and print '}'. + * - Array value: + * - if empty then print [] without indent and line break + * - if the array contains no object value, empty array or some other value types, + * and all the values fit on one lines, then print the array on a single line. + * - otherwise, it the values do not fit on one line, or the array contains + * object or non empty array, then print one value per line. + * + * If the Value have comments then they are outputed according to their #CommentPlacement. + * + * \param indentation Each level will be indented by this amount extra. + * \sa Reader, Value, Value::setComment() + */ + class JSON_API StyledStreamWriter + { + public: + StyledStreamWriter( std::string indentation="\t" ); + ~StyledStreamWriter(){} + + public: + /** \brief Serialize a Value in JSON format. + * \param out Stream to write to. (Can be ostringstream, e.g.) + * \param root Value to serialize. + * \note There is no point in deriving from Writer, since write() should not return a value. + */ + void write( std::ostream &out, const Value &root ); + + private: + void writeValue( const Value &value ); + void writeArrayValue( const Value &value ); + bool isMultineArray( const Value &value ); + void pushValue( const std::string &value ); + void writeIndent(); + void writeWithIndent( const std::string &value ); + void indent(); + void unindent(); + void writeCommentBeforeValue( const Value &root ); + void writeCommentAfterValueOnSameLine( const Value &root ); + bool hasCommentForValue( const Value &value ); + static std::string normalizeEOL( const std::string &text ); + + typedef std::vector ChildValues; + + ChildValues childValues_; + std::ostream* document_; + std::string indentString_; + int rightMargin_; + std::string indentation_; + bool addChildValues_; + }; + +# if defined(JSON_HAS_INT64) + std::string JSON_API valueToString( Int value ); + std::string JSON_API valueToString( UInt value ); +# endif // if defined(JSON_HAS_INT64) + std::string JSON_API valueToString( LargestInt value ); + std::string JSON_API valueToString( LargestUInt value ); + std::string JSON_API valueToString( double value ); + std::string JSON_API valueToString( bool value ); + std::string JSON_API valueToQuotedString( const char *value ); + + /// \brief Output using the StyledStreamWriter. + /// \see Json::operator>>() + std::ostream& operator<<( std::ostream&, const Value &root ); + +} // namespace Json + + + +#endif // JSON_WRITER_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/writer.h +// ////////////////////////////////////////////////////////////////////// + + + + + +#endif //ifndef JSON_AMALGATED_H_INCLUDED diff --git a/Core/CppMicroServices/src/util/jsoncpp.cpp b/Core/CppMicroServices/src/util/jsoncpp.cpp new file mode 100644 index 0000000000..8b2781c281 --- /dev/null +++ b/Core/CppMicroServices/src/util/jsoncpp.cpp @@ -0,0 +1,4225 @@ +/// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/). +/// It is intented to be used with #include + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + +/* +The JsonCpp library's source code, including accompanying documentation, +tests and demonstration applications, are licensed under the following +conditions... + +The author (Baptiste Lepilleur) explicitly disclaims copyright in all +jurisdictions which recognize such a disclaimer. In such jurisdictions, +this software is released into the Public Domain. + +In jurisdictions which do not recognize Public Domain property (e.g. Germany as of +2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is +released under the terms of the MIT License (see below). + +In jurisdictions which recognize Public Domain property, the user of this +software may choose to accept it either as 1) Public Domain, 2) under the +conditions of the MIT License (see below), or 3) under the terms of dual +Public Domain/MIT License conditions described here, as they choose. + +The MIT License is about as close to Public Domain as a license can get, and is +described in clear, concise terms at: + + http://en.wikipedia.org/wiki/MIT_License + +The full text of the MIT License follows: + +======================================================================== +Copyright (c) 2007-2010 Baptiste Lepilleur + +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 THE AUTHORS OR COPYRIGHT HOLDERS +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. +======================================================================== +(END LICENSE TEXT) + +The MIT license is compatible with both the GPL and commercial +software, affording one all of the rights of Public Domain with the +minor nuisance of being required to keep the above copyright notice +and license text in the source code. Note also that by accepting the +Public Domain "license" you can re-license your copy using whatever +license you like. + +*/ + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + + + + + + +#include + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_tool.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED +# define LIB_JSONCPP_JSON_TOOL_H_INCLUDED + +/* This header provides common string manipulation support, such as UTF-8, + * portable conversion from/to string... + * + * It is an internal header that must not be exposed. + */ + +namespace Json { + +/// Converts a unicode code-point to UTF-8. +static inline std::string +codePointToUTF8(unsigned int cp) +{ + std::string result; + + // based on description from http://en.wikipedia.org/wiki/UTF-8 + + if (cp <= 0x7f) + { + result.resize(1); + result[0] = static_cast(cp); + } + else if (cp <= 0x7FF) + { + result.resize(2); + result[1] = static_cast(0x80 | (0x3f & cp)); + result[0] = static_cast(0xC0 | (0x1f & (cp >> 6))); + } + else if (cp <= 0xFFFF) + { + result.resize(3); + result[2] = static_cast(0x80 | (0x3f & cp)); + result[1] = 0x80 | static_cast((0x3f & (cp >> 6))); + result[0] = 0xE0 | static_cast((0xf & (cp >> 12))); + } + else if (cp <= 0x10FFFF) + { + result.resize(4); + result[3] = static_cast(0x80 | (0x3f & cp)); + result[2] = static_cast(0x80 | (0x3f & (cp >> 6))); + result[1] = static_cast(0x80 | (0x3f & (cp >> 12))); + result[0] = static_cast(0xF0 | (0x7 & (cp >> 18))); + } + + return result; +} + + +/// Returns true if ch is a control character (in range [0,32[). +static inline bool +isControlCharacter(char ch) +{ + return ch > 0 && ch <= 0x1F; +} + + +enum { + /// Constant that specify the size of the buffer that must be passed to uintToString. + uintToStringBufferSize = 3*sizeof(LargestUInt)+1 +}; + +// Defines a char buffer for use with uintToString(). +typedef char UIntToStringBuffer[uintToStringBufferSize]; + + +/** Converts an unsigned integer to string. + * @param value Unsigned interger to convert to string + * @param current Input/Output string buffer. + * Must have at least uintToStringBufferSize chars free. + */ +static inline void +uintToString( LargestUInt value, + char *¤t ) +{ + *--current = 0; + do + { + *--current = char(value % 10) + '0'; + value /= 10; + } + while ( value != 0 ); +} + +} // namespace Json { + +#endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_tool.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_reader.cpp +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#if !defined(JSON_IS_AMALGAMATION) +# include +# include +# include "json_tool.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +#include +#include +#include +#include +#include +#include + +#if _MSC_VER >= 1400 // VC++ 8.0 +#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated. +#endif + +namespace Json { + +// Implementation of class Features +// //////////////////////////////// + +Features::Features() + : allowComments_( true ) + , strictRoot_( false ) +{ +} + + +Features +Features::all() +{ + return Features(); +} + + +Features +Features::strictMode() +{ + Features features; + features.allowComments_ = false; + features.strictRoot_ = true; + return features; +} + +// Implementation of class Reader +// //////////////////////////////// + + +static inline bool +in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4 ) +{ + return c == c1 || c == c2 || c == c3 || c == c4; +} + +static inline bool +in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4, Reader::Char c5 ) +{ + return c == c1 || c == c2 || c == c3 || c == c4 || c == c5; +} + + +static bool +containsNewLine( Reader::Location begin, + Reader::Location end ) +{ + for ( ;begin < end; ++begin ) + if ( *begin == '\n' || *begin == '\r' ) + return true; + return false; +} + + +// Class Reader +// ////////////////////////////////////////////////////////////////// + +Reader::Reader() + : features_( Features::all() ) +{ +} + + +Reader::Reader( const Features &features ) + : features_( features ) +{ +} + + +bool +Reader::parse( const std::string &document, + Value &root, + bool collectComments ) +{ + document_ = document; + const char *begin = document_.c_str(); + const char *end = begin + document_.length(); + return parse( begin, end, root, collectComments ); +} + + +bool +Reader::parse( std::istream& sin, + Value &root, + bool collectComments ) +{ + //std::istream_iterator begin(sin); + //std::istream_iterator end; + // Those would allow streamed input from a file, if parse() were a + // template function. + + // Since std::string is reference-counted, this at least does not + // create an extra copy. + std::string doc; + std::getline(sin, doc, static_cast(EOF)); + return parse( doc, root, collectComments ); +} + +bool +Reader::parse( const char *beginDoc, const char *endDoc, + Value &root, + bool collectComments ) +{ + if ( !features_.allowComments_ ) + { + collectComments = false; + } + + begin_ = beginDoc; + end_ = endDoc; + collectComments_ = collectComments; + current_ = begin_; + lastValueEnd_ = 0; + lastValue_ = 0; + commentsBefore_ = ""; + errors_.clear(); + while ( !nodes_.empty() ) + nodes_.pop(); + nodes_.push( &root ); + + bool successful = readValue(); + Token token; + skipCommentTokens( token ); + if ( collectComments_ && !commentsBefore_.empty() ) + root.setComment( commentsBefore_, commentAfter ); + if ( features_.strictRoot_ ) + { + if ( !root.isArray() && !root.isObject() ) + { + // Set error location to start of doc, ideally should be first token found in doc + token.type_ = tokenError; + token.start_ = beginDoc; + token.end_ = endDoc; + addError( "A valid JSON document must be either an array or an object value.", + token ); + return false; + } + } + return successful; +} + + +bool +Reader::readValue() +{ + Token token; + skipCommentTokens( token ); + bool successful = true; + + if ( collectComments_ && !commentsBefore_.empty() ) + { + currentValue().setComment( commentsBefore_, commentBefore ); + commentsBefore_ = ""; + } + + + switch ( token.type_ ) + { + case tokenObjectBegin: + successful = readObject( token ); + break; + case tokenArrayBegin: + successful = readArray( token ); + break; + case tokenNumber: + successful = decodeNumber( token ); + break; + case tokenString: + successful = decodeString( token ); + break; + case tokenTrue: + currentValue() = true; + break; + case tokenFalse: + currentValue() = false; + break; + case tokenNull: + currentValue() = Value(); + break; + default: + return addError( "Syntax error: value, object or array expected.", token ); + } + + if ( collectComments_ ) + { + lastValueEnd_ = current_; + lastValue_ = ¤tValue(); + } + + return successful; +} + + +void +Reader::skipCommentTokens( Token &token ) +{ + if ( features_.allowComments_ ) + { + do + { + readToken( token ); + } + while ( token.type_ == tokenComment ); + } + else + { + readToken( token ); + } +} + + +bool +Reader::expectToken( TokenType type, Token &token, const char *message ) +{ + readToken( token ); + if ( token.type_ != type ) + return addError( message, token ); + return true; +} + + +bool +Reader::readToken( Token &token ) +{ + skipSpaces(); + token.start_ = current_; + Char c = getNextChar(); + bool ok = true; + switch ( c ) + { + case '{': + token.type_ = tokenObjectBegin; + break; + case '}': + token.type_ = tokenObjectEnd; + break; + case '[': + token.type_ = tokenArrayBegin; + break; + case ']': + token.type_ = tokenArrayEnd; + break; + case '"': + token.type_ = tokenString; + ok = readString(); + break; + case '/': + token.type_ = tokenComment; + ok = readComment(); + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '-': + token.type_ = tokenNumber; + readNumber(); + break; + case 't': + token.type_ = tokenTrue; + ok = match( "rue", 3 ); + break; + case 'f': + token.type_ = tokenFalse; + ok = match( "alse", 4 ); + break; + case 'n': + token.type_ = tokenNull; + ok = match( "ull", 3 ); + break; + case ',': + token.type_ = tokenArraySeparator; + break; + case ':': + token.type_ = tokenMemberSeparator; + break; + case 0: + token.type_ = tokenEndOfStream; + break; + default: + ok = false; + break; + } + if ( !ok ) + token.type_ = tokenError; + token.end_ = current_; + return true; +} + + +void +Reader::skipSpaces() +{ + while ( current_ != end_ ) + { + Char c = *current_; + if ( c == ' ' || c == '\t' || c == '\r' || c == '\n' ) + ++current_; + else + break; + } +} + + +bool +Reader::match( Location pattern, + int patternLength ) +{ + if ( end_ - current_ < patternLength ) + return false; + int index = patternLength; + while ( index-- ) + if ( current_[index] != pattern[index] ) + return false; + current_ += patternLength; + return true; +} + + +bool +Reader::readComment() +{ + Location commentBegin = current_ - 1; + Char c = getNextChar(); + bool successful = false; + if ( c == '*' ) + successful = readCStyleComment(); + else if ( c == '/' ) + successful = readCppStyleComment(); + if ( !successful ) + return false; + + if ( collectComments_ ) + { + CommentPlacement placement = commentBefore; + if ( lastValueEnd_ && !containsNewLine( lastValueEnd_, commentBegin ) ) + { + if ( c != '*' || !containsNewLine( commentBegin, current_ ) ) + placement = commentAfterOnSameLine; + } + + addComment( commentBegin, current_, placement ); + } + return true; +} + + +void +Reader::addComment( Location begin, + Location end, + CommentPlacement placement ) +{ + assert( collectComments_ ); + if ( placement == commentAfterOnSameLine ) + { + assert( lastValue_ != 0 ); + lastValue_->setComment( std::string( begin, end ), placement ); + } + else + { + if ( !commentsBefore_.empty() ) + commentsBefore_ += "\n"; + commentsBefore_ += std::string( begin, end ); + } +} + + +bool +Reader::readCStyleComment() +{ + while ( current_ != end_ ) + { + Char c = getNextChar(); + if ( c == '*' && *current_ == '/' ) + break; + } + return getNextChar() == '/'; +} + + +bool +Reader::readCppStyleComment() +{ + while ( current_ != end_ ) + { + Char c = getNextChar(); + if ( c == '\r' || c == '\n' ) + break; + } + return true; +} + + +void +Reader::readNumber() +{ + while ( current_ != end_ ) + { + if ( !(*current_ >= '0' && *current_ <= '9') && + !in( *current_, '.', 'e', 'E', '+', '-' ) ) + break; + ++current_; + } +} + +bool +Reader::readString() +{ + Char c = 0; + while ( current_ != end_ ) + { + c = getNextChar(); + if ( c == '\\' ) + getNextChar(); + else if ( c == '"' ) + break; + } + return c == '"'; +} + + +bool +Reader::readObject( Token &/*tokenStart*/ ) +{ + Token tokenName; + std::string name; + currentValue() = Value( objectValue ); + while ( readToken( tokenName ) ) + { + bool initialTokenOk = true; + while ( tokenName.type_ == tokenComment && initialTokenOk ) + initialTokenOk = readToken( tokenName ); + if ( !initialTokenOk ) + break; + if ( tokenName.type_ == tokenObjectEnd && name.empty() ) // empty object + return true; + if ( tokenName.type_ != tokenString ) + break; + + name = ""; + if ( !decodeString( tokenName, name ) ) + return recoverFromError( tokenObjectEnd ); + + Token colon; + if ( !readToken( colon ) || colon.type_ != tokenMemberSeparator ) + { + return addErrorAndRecover( "Missing ':' after object member name", + colon, + tokenObjectEnd ); + } + Value &value = currentValue()[ name ]; + nodes_.push( &value ); + bool ok = readValue(); + nodes_.pop(); + if ( !ok ) // error already set + return recoverFromError( tokenObjectEnd ); + + Token comma; + if ( !readToken( comma ) + || ( comma.type_ != tokenObjectEnd && + comma.type_ != tokenArraySeparator && + comma.type_ != tokenComment ) ) + { + return addErrorAndRecover( "Missing ',' or '}' in object declaration", + comma, + tokenObjectEnd ); + } + bool finalizeTokenOk = true; + while ( comma.type_ == tokenComment && + finalizeTokenOk ) + finalizeTokenOk = readToken( comma ); + if ( comma.type_ == tokenObjectEnd ) + return true; + } + return addErrorAndRecover( "Missing '}' or object member name", + tokenName, + tokenObjectEnd ); +} + + +bool +Reader::readArray( Token &/*tokenStart*/ ) +{ + currentValue() = Value( arrayValue ); + skipSpaces(); + if ( *current_ == ']' ) // empty array + { + Token endArray; + readToken( endArray ); + return true; + } + int index = 0; + for (;;) + { + Value &value = currentValue()[ index++ ]; + nodes_.push( &value ); + bool ok = readValue(); + nodes_.pop(); + if ( !ok ) // error already set + return recoverFromError( tokenArrayEnd ); + + Token token; + // Accept Comment after last item in the array. + ok = readToken( token ); + while ( token.type_ == tokenComment && ok ) + { + ok = readToken( token ); + } + bool badTokenType = ( token.type_ != tokenArraySeparator && + token.type_ != tokenArrayEnd ); + if ( !ok || badTokenType ) + { + return addErrorAndRecover( "Missing ',' or ']' in array declaration", + token, + tokenArrayEnd ); + } + if ( token.type_ == tokenArrayEnd ) + break; + } + return true; +} + + +bool +Reader::decodeNumber( Token &token ) +{ + bool isDouble = false; + for ( Location inspect = token.start_; inspect != token.end_; ++inspect ) + { + isDouble = isDouble + || in( *inspect, '.', 'e', 'E', '+' ) + || ( *inspect == '-' && inspect != token.start_ ); + } + if ( isDouble ) + return decodeDouble( token ); + // Attempts to parse the number as an integer. If the number is + // larger than the maximum supported value of an integer then + // we decode the number as a double. + Location current = token.start_; + bool isNegative = *current == '-'; + if ( isNegative ) + ++current; + Value::LargestUInt maxIntegerValue = isNegative ? Value::LargestUInt(-Value::minLargestInt) + : Value::maxLargestUInt; + Value::LargestUInt threshold = maxIntegerValue / 10; + Value::UInt lastDigitThreshold = Value::UInt( maxIntegerValue % 10 ); + assert(/* lastDigitThreshold >=0 &&*/ lastDigitThreshold <= 9 ); + Value::LargestUInt value = 0; + while ( current < token.end_ ) + { + Char c = *current++; + if ( c < '0' || c > '9' ) + return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token ); + Value::UInt digit(c - '0'); + if ( value >= threshold ) + { + // If the current digit is not the last one, or if it is + // greater than the last digit of the maximum integer value, + // the parse the number as a double. + if ( current != token.end_ || digit > lastDigitThreshold ) + { + return decodeDouble( token ); + } + } + value = value * 10 + digit; + } + if ( isNegative ) + currentValue() = -Value::LargestInt( value ); + else if ( value <= Value::LargestUInt(Value::maxInt) ) + currentValue() = Value::LargestInt( value ); + else + currentValue() = value; + return true; +} + + +bool +Reader::decodeDouble( Token &token ) +{ + double value = 0; + const int bufferSize = 32; + int count; + int length = int(token.end_ - token.start_); + if ( length <= bufferSize ) + { + Char buffer[bufferSize+1]; + memcpy( buffer, token.start_, length ); + buffer[length] = 0; + count = sscanf( buffer, "%lf", &value ); + } + else + { + std::string buffer( token.start_, token.end_ ); + count = sscanf( buffer.c_str(), "%lf", &value ); + } + + if ( count != 1 ) + return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token ); + currentValue() = value; + return true; +} + + +bool +Reader::decodeString( Token &token ) +{ + std::string decoded; + if ( !decodeString( token, decoded ) ) + return false; + currentValue() = decoded; + return true; +} + + +bool +Reader::decodeString( Token &token, std::string &decoded ) +{ + decoded.reserve( token.end_ - token.start_ - 2 ); + Location current = token.start_ + 1; // skip '"' + Location end = token.end_ - 1; // do not include '"' + while ( current != end ) + { + Char c = *current++; + if ( c == '"' ) + break; + else if ( c == '\\' ) + { + if ( current == end ) + return addError( "Empty escape sequence in string", token, current ); + Char escape = *current++; + switch ( escape ) + { + case '"': decoded += '"'; break; + case '/': decoded += '/'; break; + case '\\': decoded += '\\'; break; + case 'b': decoded += '\b'; break; + case 'f': decoded += '\f'; break; + case 'n': decoded += '\n'; break; + case 'r': decoded += '\r'; break; + case 't': decoded += '\t'; break; + case 'u': + { + unsigned int unicode; + if ( !decodeUnicodeCodePoint( token, current, end, unicode ) ) + return false; + decoded += codePointToUTF8(unicode); + } + break; + default: + return addError( "Bad escape sequence in string", token, current ); + } + } + else + { + decoded += c; + } + } + return true; +} + +bool +Reader::decodeUnicodeCodePoint( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ) +{ + + if ( !decodeUnicodeEscapeSequence( token, current, end, unicode ) ) + return false; + if (unicode >= 0xD800 && unicode <= 0xDBFF) + { + // surrogate pairs + if (end - current < 6) + return addError( "additional six characters expected to parse unicode surrogate pair.", token, current ); + unsigned int surrogatePair; + if (*(current++) == '\\' && *(current++)== 'u') + { + if (decodeUnicodeEscapeSequence( token, current, end, surrogatePair )) + { + unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF); + } + else + return false; + } + else + return addError( "expecting another \\u token to begin the second half of a unicode surrogate pair", token, current ); + } + return true; +} + +bool +Reader::decodeUnicodeEscapeSequence( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ) +{ + if ( end - current < 4 ) + return addError( "Bad unicode escape sequence in string: four digits expected.", token, current ); + unicode = 0; + for ( int index =0; index < 4; ++index ) + { + Char c = *current++; + unicode *= 16; + if ( c >= '0' && c <= '9' ) + unicode += c - '0'; + else if ( c >= 'a' && c <= 'f' ) + unicode += c - 'a' + 10; + else if ( c >= 'A' && c <= 'F' ) + unicode += c - 'A' + 10; + else + return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current ); + } + return true; +} + + +bool +Reader::addError( const std::string &message, + Token &token, + Location extra ) +{ + ErrorInfo info; + info.token_ = token; + info.message_ = message; + info.extra_ = extra; + errors_.push_back( info ); + return false; +} + + +bool +Reader::recoverFromError( TokenType skipUntilToken ) +{ + int errorCount = int(errors_.size()); + Token skip; + for (;;) + { + if ( !readToken(skip) ) + errors_.resize( errorCount ); // discard errors caused by recovery + if ( skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream ) + break; + } + errors_.resize( errorCount ); + return false; +} + + +bool +Reader::addErrorAndRecover( const std::string &message, + Token &token, + TokenType skipUntilToken ) +{ + addError( message, token ); + return recoverFromError( skipUntilToken ); +} + + +Value & +Reader::currentValue() +{ + return *(nodes_.top()); +} + + +Reader::Char +Reader::getNextChar() +{ + if ( current_ == end_ ) + return 0; + return *current_++; +} + + +void +Reader::getLocationLineAndColumn( Location location, + int &line, + int &column ) const +{ + Location current = begin_; + Location lastLineStart = current; + line = 0; + while ( current < location && current != end_ ) + { + Char c = *current++; + if ( c == '\r' ) + { + if ( *current == '\n' ) + ++current; + lastLineStart = current; + ++line; + } + else if ( c == '\n' ) + { + lastLineStart = current; + ++line; + } + } + // column & line start at 1 + column = int(location - lastLineStart) + 1; + ++line; +} + + +std::string +Reader::getLocationLineAndColumn( Location location ) const +{ + int line, column; + getLocationLineAndColumn( location, line, column ); + char buffer[18+16+16+1]; + sprintf( buffer, "Line %d, Column %d", line, column ); + return buffer; +} + + +// Deprecated. Preserved for backward compatibility +std::string +Reader::getFormatedErrorMessages() const +{ + return getFormattedErrorMessages(); +} + + +std::string +Reader::getFormattedErrorMessages() const +{ + std::string formattedMessage; + for ( Errors::const_iterator itError = errors_.begin(); + itError != errors_.end(); + ++itError ) + { + const ErrorInfo &error = *itError; + formattedMessage += "* " + getLocationLineAndColumn( error.token_.start_ ) + "\n"; + formattedMessage += " " + error.message_ + "\n"; + if ( error.extra_ ) + formattedMessage += "See " + getLocationLineAndColumn( error.extra_ ) + " for detail.\n"; + } + return formattedMessage; +} + + +std::istream& operator>>( std::istream &sin, Value &root ) +{ + Json::Reader reader; + bool ok = reader.parse(sin, root, true); + //JSON_ASSERT( ok ); + if (!ok) throw std::runtime_error(reader.getFormattedErrorMessages()); + return sin; +} + + +} // namespace Json + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_reader.cpp +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_batchallocator.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSONCPP_BATCHALLOCATOR_H_INCLUDED +# define JSONCPP_BATCHALLOCATOR_H_INCLUDED + +# include +# include + +# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + +namespace Json { + +/* Fast memory allocator. + * + * This memory allocator allocates memory for a batch of object (specified by + * the page size, the number of object in each page). + * + * It does not allow the destruction of a single object. All the allocated objects + * can be destroyed at once. The memory can be either released or reused for future + * allocation. + * + * The in-place new operator must be used to construct the object using the pointer + * returned by allocate. + */ +template +class BatchAllocator +{ +public: + typedef AllocatedType Type; + + BatchAllocator( unsigned int objectsPerPage = 255 ) + : freeHead_( 0 ) + , objectsPerPage_( objectsPerPage ) + { +// printf( "Size: %d => %s\n", sizeof(AllocatedType), typeid(AllocatedType).name() ); + assert( sizeof(AllocatedType) * objectPerAllocation >= sizeof(AllocatedType *) ); // We must be able to store a slist in the object free space. + assert( objectsPerPage >= 16 ); + batches_ = allocateBatch( 0 ); // allocated a dummy page + currentBatch_ = batches_; + } + + ~BatchAllocator() + { + for ( BatchInfo *batch = batches_; batch; ) + { + BatchInfo *nextBatch = batch->next_; + free( batch ); + batch = nextBatch; + } + } + + /// allocate space for an array of objectPerAllocation object. + /// @warning it is the responsability of the caller to call objects constructors. + AllocatedType *allocate() + { + if ( freeHead_ ) // returns node from free list. + { + AllocatedType *object = freeHead_; + freeHead_ = *static_cast(object); + return object; + } + if ( currentBatch_->used_ == currentBatch_->end_ ) + { + currentBatch_ = currentBatch_->next_; + while ( currentBatch_ && currentBatch_->used_ == currentBatch_->end_ ) + currentBatch_ = currentBatch_->next_; + + if ( !currentBatch_ ) // no free batch found, allocate a new one + { + currentBatch_ = allocateBatch( objectsPerPage_ ); + currentBatch_->next_ = batches_; // insert at the head of the list + batches_ = currentBatch_; + } + } + AllocatedType *allocated = currentBatch_->used_; + currentBatch_->used_ += objectPerAllocation; + return allocated; + } + + /// Release the object. + /// @warning it is the responsability of the caller to actually destruct the object. + void release( AllocatedType *object ) + { + assert( object != 0 ); + *static_cast(object) = freeHead_; + freeHead_ = object; + } + +private: + struct BatchInfo + { + BatchInfo *next_; + AllocatedType *used_; + AllocatedType *end_; + AllocatedType buffer_[objectPerAllocation]; + }; + + // disabled copy constructor and assignement operator. + BatchAllocator( const BatchAllocator & ); + void operator =( const BatchAllocator &); + + static BatchInfo *allocateBatch( unsigned int objectsPerPage ) + { + const unsigned int mallocSize = sizeof(BatchInfo) - sizeof(AllocatedType)* objectPerAllocation + + sizeof(AllocatedType) * objectPerAllocation * objectsPerPage; + BatchInfo *batch = static_cast( malloc( mallocSize ) ); + batch->next_ = 0; + batch->used_ = batch->buffer_; + batch->end_ = batch->buffer_ + objectsPerPage; + return batch; + } + + BatchInfo *batches_; + BatchInfo *currentBatch_; + /// Head of a single linked list within the allocated space of freeed object + AllocatedType *freeHead_; + unsigned int objectsPerPage_; +}; + + +} // namespace Json + +# endif // ifndef JSONCPP_DOC_INCLUDE_IMPLEMENTATION + +#endif // JSONCPP_BATCHALLOCATOR_H_INCLUDED + + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_batchallocator.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_valueiterator.inl +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +// included by json_value.cpp + +namespace Json { + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueIteratorBase +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +ValueIteratorBase::ValueIteratorBase() +#ifndef JSON_VALUE_USE_INTERNAL_MAP + : current_() + , isNull_( true ) +{ +} +#else + : isArray_( true ) + , isNull_( true ) +{ + iterator_.array_ = ValueInternalArray::IteratorState(); +} +#endif + + +#ifndef JSON_VALUE_USE_INTERNAL_MAP +ValueIteratorBase::ValueIteratorBase( const Value::ObjectValues::iterator ¤t ) + : current_( current ) + , isNull_( false ) +{ +} +#else +ValueIteratorBase::ValueIteratorBase( const ValueInternalArray::IteratorState &state ) + : isArray_( true ) +{ + iterator_.array_ = state; +} + + +ValueIteratorBase::ValueIteratorBase( const ValueInternalMap::IteratorState &state ) + : isArray_( false ) +{ + iterator_.map_ = state; +} +#endif + +Value & +ValueIteratorBase::deref() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + return current_->second; +#else + if ( isArray_ ) + return ValueInternalArray::dereference( iterator_.array_ ); + return ValueInternalMap::value( iterator_.map_ ); +#endif +} + + +void +ValueIteratorBase::increment() +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + ++current_; +#else + if ( isArray_ ) + ValueInternalArray::increment( iterator_.array_ ); + ValueInternalMap::increment( iterator_.map_ ); +#endif +} + + +void +ValueIteratorBase::decrement() +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + --current_; +#else + if ( isArray_ ) + ValueInternalArray::decrement( iterator_.array_ ); + ValueInternalMap::decrement( iterator_.map_ ); +#endif +} + + +ValueIteratorBase::difference_type +ValueIteratorBase::computeDistance( const SelfType &other ) const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP +# ifdef JSON_USE_CPPTL_SMALLMAP + return current_ - other.current_; +# else + // Iterator for null value are initialized using the default + // constructor, which initialize current_ to the default + // std::map::iterator. As begin() and end() are two instance + // of the default std::map::iterator, they can not be compared. + // To allow this, we handle this comparison specifically. + if ( isNull_ && other.isNull_ ) + { + return 0; + } + + + // Usage of std::distance is not portable (does not compile with Sun Studio 12 RogueWave STL, + // which is the one used by default). + // Using a portable hand-made version for non random iterator instead: + // return difference_type( std::distance( current_, other.current_ ) ); + difference_type myDistance = 0; + for ( Value::ObjectValues::iterator it = current_; it != other.current_; ++it ) + { + ++myDistance; + } + return myDistance; +# endif +#else + if ( isArray_ ) + return ValueInternalArray::distance( iterator_.array_, other.iterator_.array_ ); + return ValueInternalMap::distance( iterator_.map_, other.iterator_.map_ ); +#endif +} + + +bool +ValueIteratorBase::isEqual( const SelfType &other ) const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + if ( isNull_ ) + { + return other.isNull_; + } + return current_ == other.current_; +#else + if ( isArray_ ) + return ValueInternalArray::equals( iterator_.array_, other.iterator_.array_ ); + return ValueInternalMap::equals( iterator_.map_, other.iterator_.map_ ); +#endif +} + + +void +ValueIteratorBase::copy( const SelfType &other ) +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + current_ = other.current_; +#else + if ( isArray_ ) + iterator_.array_ = other.iterator_.array_; + iterator_.map_ = other.iterator_.map_; +#endif +} + + +Value +ValueIteratorBase::key() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + const Value::CZString czstring = (*current_).first; + if ( czstring.c_str() ) + { + if ( czstring.isStaticString() ) + return Value( StaticString( czstring.c_str() ) ); + return Value( czstring.c_str() ); + } + return Value( czstring.index() ); +#else + if ( isArray_ ) + return Value( ValueInternalArray::indexOf( iterator_.array_ ) ); + bool isStatic; + const char *memberName = ValueInternalMap::key( iterator_.map_, isStatic ); + if ( isStatic ) + return Value( StaticString( memberName ) ); + return Value( memberName ); +#endif +} + + +UInt +ValueIteratorBase::index() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + const Value::CZString czstring = (*current_).first; + if ( !czstring.c_str() ) + return czstring.index(); + return Value::UInt( -1 ); +#else + if ( isArray_ ) + return Value::UInt( ValueInternalArray::indexOf( iterator_.array_ ) ); + return Value::UInt( -1 ); +#endif +} + + +const char * +ValueIteratorBase::memberName() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + const char *name = (*current_).first.c_str(); + return name ? name : ""; +#else + if ( !isArray_ ) + return ValueInternalMap::key( iterator_.map_ ); + return ""; +#endif +} + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueConstIterator +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +ValueConstIterator::ValueConstIterator() +{ +} + + +#ifndef JSON_VALUE_USE_INTERNAL_MAP +ValueConstIterator::ValueConstIterator( const Value::ObjectValues::iterator ¤t ) + : ValueIteratorBase( current ) +{ +} +#else +ValueConstIterator::ValueConstIterator( const ValueInternalArray::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} + +ValueConstIterator::ValueConstIterator( const ValueInternalMap::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} +#endif + +ValueConstIterator & +ValueConstIterator::operator =( const ValueIteratorBase &other ) +{ + copy( other ); + return *this; +} + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueIterator +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +ValueIterator::ValueIterator() +{ +} + + +#ifndef JSON_VALUE_USE_INTERNAL_MAP +ValueIterator::ValueIterator( const Value::ObjectValues::iterator ¤t ) + : ValueIteratorBase( current ) +{ +} +#else +ValueIterator::ValueIterator( const ValueInternalArray::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} + +ValueIterator::ValueIterator( const ValueInternalMap::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} +#endif + +ValueIterator::ValueIterator( const ValueConstIterator &other ) + : ValueIteratorBase( other ) +{ +} + +ValueIterator::ValueIterator( const ValueIterator &other ) + : ValueIteratorBase( other ) +{ +} + +ValueIterator & +ValueIterator::operator =( const SelfType &other ) +{ + copy( other ); + return *this; +} + +} // namespace Json + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_valueiterator.inl +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_value.cpp +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#if !defined(JSON_IS_AMALGAMATION) +# include +# include +# ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR +# include "json_batchallocator.h" +# endif // #ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR +#endif // if !defined(JSON_IS_AMALGAMATION) +#include +#include +#include +#include +#include +#ifdef JSON_USE_CPPTL +# include +#endif +#include // size_t + +#define JSON_ASSERT_UNREACHABLE assert( false ) +#define JSON_ASSERT( condition ) assert( condition ); // @todo <= change this into an exception throw +#define JSON_FAIL_MESSAGE( message ) throw std::runtime_error( message ); +#define JSON_ASSERT_MESSAGE( condition, message ) if (!( condition )) JSON_FAIL_MESSAGE( message ) + +namespace Json { + +const Value Value::null; +const Int Value::minInt = Int( ~(UInt(-1)/2) ); +const Int Value::maxInt = Int( UInt(-1)/2 ); +const UInt Value::maxUInt = UInt(-1); +const Int64 Value::minInt64 = Int64( ~(UInt64(-1)/2) ); +const Int64 Value::maxInt64 = Int64( UInt64(-1)/2 ); +const UInt64 Value::maxUInt64 = UInt64(-1); +const LargestInt Value::minLargestInt = LargestInt( ~(LargestUInt(-1)/2) ); +const LargestInt Value::maxLargestInt = LargestInt( LargestUInt(-1)/2 ); +const LargestUInt Value::maxLargestUInt = LargestUInt(-1); + + +/// Unknown size marker +static const unsigned int unknown = -1; + + +/** Duplicates the specified string value. + * @param value Pointer to the string to duplicate. Must be zero-terminated if + * length is "unknown". + * @param length Length of the value. if equals to unknown, then it will be + * computed using strlen(value). + * @return Pointer on the duplicate instance of string. + */ +static inline char * +duplicateStringValue( const char *value, + unsigned int length = unknown ) +{ + if ( length == unknown ) + length = static_cast(strlen(value)); + char *newString = static_cast( malloc( length + 1 ) ); + JSON_ASSERT_MESSAGE( newString != 0, "Failed to allocate string value buffer" ); + memcpy( newString, value, length ); + newString[length] = 0; + return newString; +} + + +/** Free the string duplicated by duplicateStringValue(). + */ +static inline void +releaseStringValue( char *value ) +{ + if ( value ) + free( value ); +} + +} // namespace Json + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ValueInternals... +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +#if !defined(JSON_IS_AMALGAMATION) +# ifdef JSON_VALUE_USE_INTERNAL_MAP +# include "json_internalarray.inl" +# include "json_internalmap.inl" +# endif // JSON_VALUE_USE_INTERNAL_MAP + +# include "json_valueiterator.inl" +#endif // if !defined(JSON_IS_AMALGAMATION) + +namespace Json { + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class Value::CommentInfo +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + + +Value::CommentInfo::CommentInfo() + : comment_( 0 ) +{ +} + +Value::CommentInfo::~CommentInfo() +{ + if ( comment_ ) + releaseStringValue( comment_ ); +} + + +void +Value::CommentInfo::setComment( const char *text ) +{ + if ( comment_ ) + releaseStringValue( comment_ ); + JSON_ASSERT( text != 0 ); + JSON_ASSERT_MESSAGE( text[0]=='\0' || text[0]=='/', "Comments must start with /"); + // It seems that /**/ style comments are acceptable as well. + comment_ = duplicateStringValue( text ); +} + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class Value::CZString +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +# ifndef JSON_VALUE_USE_INTERNAL_MAP + +// Notes: index_ indicates if the string was allocated when +// a string is stored. + +Value::CZString::CZString( ArrayIndex index ) + : cstr_( 0 ) + , index_( index ) +{ +} + +Value::CZString::CZString( const char *cstr, DuplicationPolicy allocate ) + : cstr_( allocate == duplicate ? duplicateStringValue(cstr) + : cstr ) + , index_( allocate ) +{ +} + +Value::CZString::CZString( const CZString &other ) +: cstr_( other.index_ != noDuplication && other.cstr_ != 0 + ? duplicateStringValue( other.cstr_ ) + : other.cstr_ ) + , index_( other.cstr_ ? (other.index_ == noDuplication ? static_cast(noDuplication) : static_cast(duplicate)) + : other.index_ ) +{ +} + +Value::CZString::~CZString() +{ + if ( cstr_ && index_ == duplicate ) + releaseStringValue( const_cast( cstr_ ) ); +} + +void +Value::CZString::swap( CZString &other ) +{ + std::swap( cstr_, other.cstr_ ); + std::swap( index_, other.index_ ); +} + +Value::CZString & +Value::CZString::operator =( const CZString &other ) +{ + CZString temp( other ); + swap( temp ); + return *this; +} + +bool +Value::CZString::operator<( const CZString &other ) const +{ + if ( cstr_ ) + return strcmp( cstr_, other.cstr_ ) < 0; + return index_ < other.index_; +} + +bool +Value::CZString::operator==( const CZString &other ) const +{ + if ( cstr_ ) + return strcmp( cstr_, other.cstr_ ) == 0; + return index_ == other.index_; +} + + +ArrayIndex +Value::CZString::index() const +{ + return index_; +} + + +const char * +Value::CZString::c_str() const +{ + return cstr_; +} + +bool +Value::CZString::isStaticString() const +{ + return index_ == noDuplication; +} + +#endif // ifndef JSON_VALUE_USE_INTERNAL_MAP + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class Value::Value +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +/*! \internal Default constructor initialization must be equivalent to: + * memset( this, 0, sizeof(Value) ) + * This optimization is used in ValueInternalMap fast allocator. + */ +Value::Value( ValueType type ) + : type_( type ) + , allocated_( 0 ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + switch ( type ) + { + case nullValue: + break; + case intValue: + case uintValue: + value_.int_ = 0; + break; + case realValue: + value_.real_ = 0.0; + break; + case stringValue: + value_.string_ = 0; + break; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + value_.map_ = new ObjectValues(); + break; +#else + case arrayValue: + value_.array_ = arrayAllocator()->newArray(); + break; + case objectValue: + value_.map_ = mapAllocator()->newMap(); + break; +#endif + case booleanValue: + value_.bool_ = false; + break; + default: + JSON_ASSERT_UNREACHABLE; + } +} + + +#if defined(JSON_HAS_INT64) +Value::Value( UInt value ) + : type_( uintValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.uint_ = value; +} + +Value::Value( Int value ) + : type_( intValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.int_ = value; +} + +#endif // if defined(JSON_HAS_INT64) + + +Value::Value( Int64 value ) + : type_( intValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.int_ = value; +} + + +Value::Value( UInt64 value ) + : type_( uintValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.uint_ = value; +} + +Value::Value( double value ) + : type_( realValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.real_ = value; +} + +Value::Value( const char *value ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = duplicateStringValue( value ); +} + + +Value::Value( const char *beginValue, + const char *endValue ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = duplicateStringValue( beginValue, + static_cast(endValue - beginValue) ); +} + + +Value::Value( const std::string &value ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = duplicateStringValue( value.c_str(), + static_cast(value.length()) ); + +} + +Value::Value( const StaticString &value ) + : type_( stringValue ) + , allocated_( false ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = const_cast( value.c_str() ); +} + + +# ifdef JSON_USE_CPPTL +Value::Value( const CppTL::ConstString &value ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = duplicateStringValue( value, value.length() ); +} +# endif + +Value::Value( bool value ) + : type_( booleanValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.bool_ = value; +} + + +Value::Value( const Value &other ) + : type_( other.type_ ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + switch ( type_ ) + { + case nullValue: + case intValue: + case uintValue: + case realValue: + case booleanValue: + value_ = other.value_; + break; + case stringValue: + if ( other.value_.string_ ) + { + value_.string_ = duplicateStringValue( other.value_.string_ ); + allocated_ = true; + } + else + value_.string_ = 0; + break; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + value_.map_ = new ObjectValues( *other.value_.map_ ); + break; +#else + case arrayValue: + value_.array_ = arrayAllocator()->newArrayCopy( *other.value_.array_ ); + break; + case objectValue: + value_.map_ = mapAllocator()->newMapCopy( *other.value_.map_ ); + break; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + if ( other.comments_ ) + { + comments_ = new CommentInfo[numberOfCommentPlacement]; + for ( int comment =0; comment < numberOfCommentPlacement; ++comment ) + { + const CommentInfo &otherComment = other.comments_[comment]; + if ( otherComment.comment_ ) + comments_[comment].setComment( otherComment.comment_ ); + } + } +} + + +Value::~Value() +{ + switch ( type_ ) + { + case nullValue: + case intValue: + case uintValue: + case realValue: + case booleanValue: + break; + case stringValue: + if ( allocated_ ) + releaseStringValue( value_.string_ ); + break; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + delete value_.map_; + break; +#else + case arrayValue: + arrayAllocator()->destructArray( value_.array_ ); + break; + case objectValue: + mapAllocator()->destructMap( value_.map_ ); + break; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + + if ( comments_ ) + delete[] comments_; +} + +Value & +Value::operator=( const Value &other ) +{ + Value temp( other ); + swap( temp ); + return *this; +} + +void +Value::swap( Value &other ) +{ + ValueType temp = type_; + type_ = other.type_; + other.type_ = temp; + std::swap( value_, other.value_ ); + int temp2 = allocated_; + allocated_ = other.allocated_; + other.allocated_ = temp2; +} + +ValueType +Value::type() const +{ + return type_; +} + + +int +Value::compare( const Value &other ) const +{ + if ( *this < other ) + return -1; + if ( *this > other ) + return 1; + return 0; +} + + +bool +Value::operator <( const Value &other ) const +{ + int typeDelta = type_ - other.type_; + if ( typeDelta ) + return typeDelta < 0 ? true : false; + switch ( type_ ) + { + case nullValue: + return false; + case intValue: + return value_.int_ < other.value_.int_; + case uintValue: + return value_.uint_ < other.value_.uint_; + case realValue: + return value_.real_ < other.value_.real_; + case booleanValue: + return value_.bool_ < other.value_.bool_; + case stringValue: + return ( value_.string_ == 0 && other.value_.string_ ) + || ( other.value_.string_ + && value_.string_ + && strcmp( value_.string_, other.value_.string_ ) < 0 ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + { + int delta = int( value_.map_->size() - other.value_.map_->size() ); + if ( delta ) + return delta < 0; + return (*value_.map_) < (*other.value_.map_); + } +#else + case arrayValue: + return value_.array_->compare( *(other.value_.array_) ) < 0; + case objectValue: + return value_.map_->compare( *(other.value_.map_) ) < 0; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable +} + +bool +Value::operator <=( const Value &other ) const +{ + return !(other < *this); +} + +bool +Value::operator >=( const Value &other ) const +{ + return !(*this < other); +} + +bool +Value::operator >( const Value &other ) const +{ + return other < *this; +} + +bool +Value::operator ==( const Value &other ) const +{ + //if ( type_ != other.type_ ) + // GCC 2.95.3 says: + // attempt to take address of bit-field structure member `Json::Value::type_' + // Beats me, but a temp solves the problem. + int temp = other.type_; + if ( type_ != temp ) + return false; + switch ( type_ ) + { + case nullValue: + return true; + case intValue: + return value_.int_ == other.value_.int_; + case uintValue: + return value_.uint_ == other.value_.uint_; + case realValue: + return value_.real_ == other.value_.real_; + case booleanValue: + return value_.bool_ == other.value_.bool_; + case stringValue: + return ( value_.string_ == other.value_.string_ ) + || ( other.value_.string_ + && value_.string_ + && strcmp( value_.string_, other.value_.string_ ) == 0 ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + return value_.map_->size() == other.value_.map_->size() + && (*value_.map_) == (*other.value_.map_); +#else + case arrayValue: + return value_.array_->compare( *(other.value_.array_) ) == 0; + case objectValue: + return value_.map_->compare( *(other.value_.map_) ) == 0; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable +} + +bool +Value::operator !=( const Value &other ) const +{ + return !( *this == other ); +} + +const char * +Value::asCString() const +{ + JSON_ASSERT( type_ == stringValue ); + return value_.string_; +} + + +std::string +Value::asString() const +{ + switch ( type_ ) + { + case nullValue: + return ""; + case stringValue: + return value_.string_ ? value_.string_ : ""; + case booleanValue: + return value_.bool_ ? "true" : "false"; + case intValue: + case uintValue: + case realValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to string" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return ""; // unreachable +} + +# ifdef JSON_USE_CPPTL +CppTL::ConstString +Value::asConstString() const +{ + return CppTL::ConstString( asString().c_str() ); +} +# endif + + +Value::Int +Value::asInt() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + JSON_ASSERT_MESSAGE( value_.int_ >= minInt && value_.int_ <= maxInt, "unsigned integer out of signed int range" ); + return Int(value_.int_); + case uintValue: + JSON_ASSERT_MESSAGE( value_.uint_ <= UInt(maxInt), "unsigned integer out of signed int range" ); + return Int(value_.uint_); + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= minInt && value_.real_ <= maxInt, "Real out of signed integer range" ); + return Int( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to int" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + + +Value::UInt +Value::asUInt() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + JSON_ASSERT_MESSAGE( value_.int_ >= 0, "Negative integer can not be converted to unsigned integer" ); + JSON_ASSERT_MESSAGE( value_.int_ <= maxUInt, "signed integer out of UInt range" ); + return UInt(value_.int_); + case uintValue: + JSON_ASSERT_MESSAGE( value_.uint_ <= maxUInt, "unsigned integer out of UInt range" ); + return UInt(value_.uint_); + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= 0 && value_.real_ <= maxUInt, "Real out of unsigned integer range" ); + return UInt( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to uint" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + + +# if defined(JSON_HAS_INT64) + +Value::Int64 +Value::asInt64() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + return value_.int_; + case uintValue: + JSON_ASSERT_MESSAGE( value_.uint_ <= UInt64(maxInt64), "unsigned integer out of Int64 range" ); + return value_.uint_; + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= minInt64 && value_.real_ <= maxInt64, "Real out of Int64 range" ); + return Int( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to Int64" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + + +Value::UInt64 +Value::asUInt64() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + JSON_ASSERT_MESSAGE( value_.int_ >= 0, "Negative integer can not be converted to UInt64" ); + return value_.int_; + case uintValue: + return value_.uint_; + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= 0 && value_.real_ <= maxUInt64, "Real out of UInt64 range" ); + return UInt( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to UInt64" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} +# endif // if defined(JSON_HAS_INT64) + + +LargestInt +Value::asLargestInt() const +{ +#if defined(JSON_NO_INT64) + return asInt(); +#else + return asInt64(); +#endif +} + + +LargestUInt +Value::asLargestUInt() const +{ +#if defined(JSON_NO_INT64) + return asUInt(); +#else + return asUInt64(); +#endif +} + + +double +Value::asDouble() const +{ + switch ( type_ ) + { + case nullValue: + return 0.0; + case intValue: + return static_cast( value_.int_ ); + case uintValue: +#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + return static_cast( value_.uint_ ); +#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + return static_cast( Int(value_.uint_/2) ) * 2 + Int(value_.uint_ & 1); +#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + case realValue: + return value_.real_; + case booleanValue: + return value_.bool_ ? 1.0 : 0.0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to double" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + +float +Value::asFloat() const +{ + switch ( type_ ) + { + case nullValue: + return 0.0f; + case intValue: + return static_cast( value_.int_ ); + case uintValue: +#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + return static_cast( value_.uint_ ); +#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + return static_cast( Int(value_.uint_/2) ) * 2 + Int(value_.uint_ & 1); +#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + case realValue: + return static_cast( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1.0f : 0.0f; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to float" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0.0f; // unreachable; +} + +bool +Value::asBool() const +{ + switch ( type_ ) + { + case nullValue: + return false; + case intValue: + case uintValue: + return value_.int_ != 0; + case realValue: + return value_.real_ != 0.0; + case booleanValue: + return value_.bool_; + case stringValue: + return value_.string_ && value_.string_[0] != 0; + case arrayValue: + case objectValue: + return value_.map_->size() != 0; + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable; +} + + +bool +Value::isConvertibleTo( ValueType other ) const +{ + switch ( type_ ) + { + case nullValue: + return true; + case intValue: + return ( other == nullValue && value_.int_ == 0 ) + || other == intValue + || ( other == uintValue && value_.int_ >= 0 ) + || other == realValue + || other == stringValue + || other == booleanValue; + case uintValue: + return ( other == nullValue && value_.uint_ == 0 ) + || ( other == intValue && value_.uint_ <= static_cast(maxInt) ) + || other == uintValue + || other == realValue + || other == stringValue + || other == booleanValue; + case realValue: + return ( other == nullValue && value_.real_ == 0.0 ) + || ( other == intValue && value_.real_ >= minInt && value_.real_ <= maxInt ) + || ( other == uintValue && value_.real_ >= 0 && value_.real_ <= maxUInt ) + || other == realValue + || other == stringValue + || other == booleanValue; + case booleanValue: + return ( other == nullValue && value_.bool_ == false ) + || other == intValue + || other == uintValue + || other == realValue + || other == stringValue + || other == booleanValue; + case stringValue: + return other == stringValue + || ( other == nullValue && (!value_.string_ || value_.string_[0] == 0) ); + case arrayValue: + return other == arrayValue + || ( other == nullValue && value_.map_->size() == 0 ); + case objectValue: + return other == objectValue + || ( other == nullValue && value_.map_->size() == 0 ); + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable; +} + + +/// Number of values in array or object +ArrayIndex +Value::size() const +{ + switch ( type_ ) + { + case nullValue: + case intValue: + case uintValue: + case realValue: + case booleanValue: + case stringValue: + return 0; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: // size of the array is highest index + 1 + if ( !value_.map_->empty() ) + { + ObjectValues::const_iterator itLast = value_.map_->end(); + --itLast; + return (*itLast).first.index()+1; + } + return 0; + case objectValue: + return ArrayIndex( value_.map_->size() ); +#else + case arrayValue: + return Int( value_.array_->size() ); + case objectValue: + return Int( value_.map_->size() ); +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + + +bool +Value::empty() const +{ + if ( isNull() || isArray() || isObject() ) + return size() == 0u; + else + return false; +} + + +bool +Value::operator!() const +{ + return isNull(); +} + + +void +Value::clear() +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue || type_ == objectValue ); + + switch ( type_ ) + { +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + value_.map_->clear(); + break; +#else + case arrayValue: + value_.array_->clear(); + break; + case objectValue: + value_.map_->clear(); + break; +#endif + default: + break; + } +} + +void +Value::resize( ArrayIndex newSize ) +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); + if ( type_ == nullValue ) + *this = Value( arrayValue ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + ArrayIndex oldSize = size(); + if ( newSize == 0 ) + clear(); + else if ( newSize > oldSize ) + (*this)[ newSize - 1 ]; + else + { + for ( ArrayIndex index = newSize; index < oldSize; ++index ) + { + value_.map_->erase( index ); + } + assert( size() == newSize ); + } +#else + value_.array_->resize( newSize ); +#endif +} + + +Value & +Value::operator[]( ArrayIndex index ) +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); + if ( type_ == nullValue ) + *this = Value( arrayValue ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString key( index ); + ObjectValues::iterator it = value_.map_->lower_bound( key ); + if ( it != value_.map_->end() && (*it).first == key ) + return (*it).second; + + ObjectValues::value_type defaultValue( key, null ); + it = value_.map_->insert( it, defaultValue ); + return (*it).second; +#else + return value_.array_->resolveReference( index ); +#endif +} + + +Value & +Value::operator[]( int index ) +{ + JSON_ASSERT( index >= 0 ); + return (*this)[ ArrayIndex(index) ]; +} + + +const Value & +Value::operator[]( ArrayIndex index ) const +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); + if ( type_ == nullValue ) + return null; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString key( index ); + ObjectValues::const_iterator it = value_.map_->find( key ); + if ( it == value_.map_->end() ) + return null; + return (*it).second; +#else + Value *value = value_.array_->find( index ); + return value ? *value : null; +#endif +} + + +const Value & +Value::operator[]( int index ) const +{ + JSON_ASSERT( index >= 0 ); + return (*this)[ ArrayIndex(index) ]; +} + + +Value & +Value::operator[]( const char *key ) +{ + return resolveReference( key, false ); +} + + +Value & +Value::resolveReference( const char *key, + bool isStatic ) +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + *this = Value( objectValue ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString actualKey( key, isStatic ? CZString::noDuplication + : CZString::duplicateOnCopy ); + ObjectValues::iterator it = value_.map_->lower_bound( actualKey ); + if ( it != value_.map_->end() && (*it).first == actualKey ) + return (*it).second; + + ObjectValues::value_type defaultValue( actualKey, null ); + it = value_.map_->insert( it, defaultValue ); + Value &value = (*it).second; + return value; +#else + return value_.map_->resolveReference( key, isStatic ); +#endif +} + + +Value +Value::get( ArrayIndex index, + const Value &defaultValue ) const +{ + const Value *value = &((*this)[index]); + return value == &null ? defaultValue : *value; +} + + +bool +Value::isValidIndex( ArrayIndex index ) const +{ + return index < size(); +} + + + +const Value & +Value::operator[]( const char *key ) const +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + return null; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString actualKey( key, CZString::noDuplication ); + ObjectValues::const_iterator it = value_.map_->find( actualKey ); + if ( it == value_.map_->end() ) + return null; + return (*it).second; +#else + const Value *value = value_.map_->find( key ); + return value ? *value : null; +#endif +} + + +Value & +Value::operator[]( const std::string &key ) +{ + return (*this)[ key.c_str() ]; +} + + +const Value & +Value::operator[]( const std::string &key ) const +{ + return (*this)[ key.c_str() ]; +} + +Value & +Value::operator[]( const StaticString &key ) +{ + return resolveReference( key, true ); +} + + +# ifdef JSON_USE_CPPTL +Value & +Value::operator[]( const CppTL::ConstString &key ) +{ + return (*this)[ key.c_str() ]; +} + + +const Value & +Value::operator[]( const CppTL::ConstString &key ) const +{ + return (*this)[ key.c_str() ]; +} +# endif + + +Value & +Value::append( const Value &value ) +{ + return (*this)[size()] = value; +} + + +Value +Value::get( const char *key, + const Value &defaultValue ) const +{ + const Value *value = &((*this)[key]); + return value == &null ? defaultValue : *value; +} + + +Value +Value::get( const std::string &key, + const Value &defaultValue ) const +{ + return get( key.c_str(), defaultValue ); +} + +Value +Value::removeMember( const char* key ) +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + return null; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString actualKey( key, CZString::noDuplication ); + ObjectValues::iterator it = value_.map_->find( actualKey ); + if ( it == value_.map_->end() ) + return null; + Value old(it->second); + value_.map_->erase(it); + return old; +#else + Value *value = value_.map_->find( key ); + if (value){ + Value old(*value); + value_.map_.remove( key ); + return old; + } else { + return null; + } +#endif +} + +Value +Value::removeMember( const std::string &key ) +{ + return removeMember( key.c_str() ); +} + +# ifdef JSON_USE_CPPTL +Value +Value::get( const CppTL::ConstString &key, + const Value &defaultValue ) const +{ + return get( key.c_str(), defaultValue ); +} +# endif + +bool +Value::isMember( const char *key ) const +{ + const Value *value = &((*this)[key]); + return value != &null; +} + + +bool +Value::isMember( const std::string &key ) const +{ + return isMember( key.c_str() ); +} + + +# ifdef JSON_USE_CPPTL +bool +Value::isMember( const CppTL::ConstString &key ) const +{ + return isMember( key.c_str() ); +} +#endif + +Value::Members +Value::getMemberNames() const +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + return Value::Members(); + Members members; + members.reserve( value_.map_->size() ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + ObjectValues::const_iterator it = value_.map_->begin(); + ObjectValues::const_iterator itEnd = value_.map_->end(); + for ( ; it != itEnd; ++it ) + members.push_back( std::string( (*it).first.c_str() ) ); +#else + ValueInternalMap::IteratorState it; + ValueInternalMap::IteratorState itEnd; + value_.map_->makeBeginIterator( it ); + value_.map_->makeEndIterator( itEnd ); + for ( ; !ValueInternalMap::equals( it, itEnd ); ValueInternalMap::increment(it) ) + members.push_back( std::string( ValueInternalMap::key( it ) ) ); +#endif + return members; +} +// +//# ifdef JSON_USE_CPPTL +//EnumMemberNames +//Value::enumMemberNames() const +//{ +// if ( type_ == objectValue ) +// { +// return CppTL::Enum::any( CppTL::Enum::transform( +// CppTL::Enum::keys( *(value_.map_), CppTL::Type() ), +// MemberNamesTransform() ) ); +// } +// return EnumMemberNames(); +//} +// +// +//EnumValues +//Value::enumValues() const +//{ +// if ( type_ == objectValue || type_ == arrayValue ) +// return CppTL::Enum::anyValues( *(value_.map_), +// CppTL::Type() ); +// return EnumValues(); +//} +// +//# endif + + +bool +Value::isNull() const +{ + return type_ == nullValue; +} + + +bool +Value::isBool() const +{ + return type_ == booleanValue; +} + + +bool +Value::isInt() const +{ + return type_ == intValue; +} + + +bool +Value::isUInt() const +{ + return type_ == uintValue; +} + + +bool +Value::isIntegral() const +{ + return type_ == intValue + || type_ == uintValue + || type_ == booleanValue; +} + + +bool +Value::isDouble() const +{ + return type_ == realValue; +} + + +bool +Value::isNumeric() const +{ + return isIntegral() || isDouble(); +} + + +bool +Value::isString() const +{ + return type_ == stringValue; +} + + +bool +Value::isArray() const +{ + return type_ == nullValue || type_ == arrayValue; +} + + +bool +Value::isObject() const +{ + return type_ == nullValue || type_ == objectValue; +} + + +void +Value::setComment( const char *comment, + CommentPlacement placement ) +{ + if ( !comments_ ) + comments_ = new CommentInfo[numberOfCommentPlacement]; + comments_[placement].setComment( comment ); +} + + +void +Value::setComment( const std::string &comment, + CommentPlacement placement ) +{ + setComment( comment.c_str(), placement ); +} + + +bool +Value::hasComment( CommentPlacement placement ) const +{ + return comments_ != 0 && comments_[placement].comment_ != 0; +} + +std::string +Value::getComment( CommentPlacement placement ) const +{ + if ( hasComment(placement) ) + return comments_[placement].comment_; + return ""; +} + + +std::string +Value::toStyledString() const +{ + StyledWriter writer; + return writer.write( *this ); +} + + +Value::const_iterator +Value::begin() const +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeBeginIterator( it ); + return const_iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeBeginIterator( it ); + return const_iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return const_iterator( value_.map_->begin() ); + break; +#endif + default: + break; + } + return const_iterator(); +} + +Value::const_iterator +Value::end() const +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeEndIterator( it ); + return const_iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeEndIterator( it ); + return const_iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return const_iterator( value_.map_->end() ); + break; +#endif + default: + break; + } + return const_iterator(); +} + + +Value::iterator +Value::begin() +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeBeginIterator( it ); + return iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeBeginIterator( it ); + return iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return iterator( value_.map_->begin() ); + break; +#endif + default: + break; + } + return iterator(); +} + +Value::iterator +Value::end() +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeEndIterator( it ); + return iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeEndIterator( it ); + return iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return iterator( value_.map_->end() ); + break; +#endif + default: + break; + } + return iterator(); +} + + +// class PathArgument +// ////////////////////////////////////////////////////////////////// + +PathArgument::PathArgument() + : kind_( kindNone ) +{ +} + + +PathArgument::PathArgument( ArrayIndex index ) + : index_( index ) + , kind_( kindIndex ) +{ +} + + +PathArgument::PathArgument( const char *key ) + : key_( key ) + , kind_( kindKey ) +{ +} + + +PathArgument::PathArgument( const std::string &key ) + : key_( key.c_str() ) + , kind_( kindKey ) +{ +} + +// class Path +// ////////////////////////////////////////////////////////////////// + +Path::Path( const std::string &path, + const PathArgument &a1, + const PathArgument &a2, + const PathArgument &a3, + const PathArgument &a4, + const PathArgument &a5 ) +{ + InArgs in; + in.push_back( &a1 ); + in.push_back( &a2 ); + in.push_back( &a3 ); + in.push_back( &a4 ); + in.push_back( &a5 ); + makePath( path, in ); +} + + +void +Path::makePath( const std::string &path, + const InArgs &in ) +{ + const char *current = path.c_str(); + const char *end = current + path.length(); + InArgs::const_iterator itInArg = in.begin(); + while ( current != end ) + { + if ( *current == '[' ) + { + ++current; + if ( *current == '%' ) + addPathInArg( path, in, itInArg, PathArgument::kindIndex ); + else + { + ArrayIndex index = 0; + for ( ; current != end && *current >= '0' && *current <= '9'; ++current ) + index = index * 10 + ArrayIndex(*current - '0'); + args_.push_back( index ); + } + if ( current == end || *current++ != ']' ) + invalidPath( path, int(current - path.c_str()) ); + } + else if ( *current == '%' ) + { + addPathInArg( path, in, itInArg, PathArgument::kindKey ); + ++current; + } + else if ( *current == '.' ) + { + ++current; + } + else + { + const char *beginName = current; + while ( current != end && !strchr( "[.", *current ) ) + ++current; + args_.push_back( std::string( beginName, current ) ); + } + } +} + + +void +Path::addPathInArg( const std::string &/*path*/, + const InArgs &in, + InArgs::const_iterator &itInArg, + PathArgument::Kind kind ) +{ + if ( itInArg == in.end() ) + { + // Error: missing argument %d + } + else if ( (*itInArg)->kind_ != kind ) + { + // Error: bad argument type + } + else + { + args_.push_back( **itInArg ); + } +} + + +void +Path::invalidPath( const std::string &/*path*/, + int /*location*/ ) +{ + // Error: invalid path. +} + + +const Value & +Path::resolve( const Value &root ) const +{ + const Value *node = &root; + for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) + { + const PathArgument &arg = *it; + if ( arg.kind_ == PathArgument::kindIndex ) + { + if ( !node->isArray() || node->isValidIndex( arg.index_ ) ) + { + // Error: unable to resolve path (array value expected at position... + } + node = &((*node)[arg.index_]); + } + else if ( arg.kind_ == PathArgument::kindKey ) + { + if ( !node->isObject() ) + { + // Error: unable to resolve path (object value expected at position...) + } + node = &((*node)[arg.key_]); + if ( node == &Value::null ) + { + // Error: unable to resolve path (object has no member named '' at position...) + } + } + } + return *node; +} + + +Value +Path::resolve( const Value &root, + const Value &defaultValue ) const +{ + const Value *node = &root; + for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) + { + const PathArgument &arg = *it; + if ( arg.kind_ == PathArgument::kindIndex ) + { + if ( !node->isArray() || node->isValidIndex( arg.index_ ) ) + return defaultValue; + node = &((*node)[arg.index_]); + } + else if ( arg.kind_ == PathArgument::kindKey ) + { + if ( !node->isObject() ) + return defaultValue; + node = &((*node)[arg.key_]); + if ( node == &Value::null ) + return defaultValue; + } + } + return *node; +} + + +Value & +Path::make( Value &root ) const +{ + Value *node = &root; + for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) + { + const PathArgument &arg = *it; + if ( arg.kind_ == PathArgument::kindIndex ) + { + if ( !node->isArray() ) + { + // Error: node is not an array at position ... + } + node = &((*node)[arg.index_]); + } + else if ( arg.kind_ == PathArgument::kindKey ) + { + if ( !node->isObject() ) + { + // Error: node is not an object at position... + } + node = &((*node)[arg.key_]); + } + } + return *node; +} + + +} // namespace Json + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_value.cpp +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_writer.cpp +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#if !defined(JSON_IS_AMALGAMATION) +# include +# include "json_tool.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +#include +#include +#include +#include +#include +#include +#include + +#if _MSC_VER >= 1400 // VC++ 8.0 +#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated. +#endif + +namespace Json { + +static bool containsControlCharacter( const char* str ) +{ + while ( *str ) + { + if ( isControlCharacter( *(str++) ) ) + return true; + } + return false; +} + + +std::string valueToString( LargestInt value ) +{ + UIntToStringBuffer buffer; + char *current = buffer + sizeof(buffer); + bool isNegative = value < 0; + if ( isNegative ) + value = -value; + uintToString( LargestUInt(value), current ); + if ( isNegative ) + *--current = '-'; + assert( current >= buffer ); + return current; +} + + +std::string valueToString( LargestUInt value ) +{ + UIntToStringBuffer buffer; + char *current = buffer + sizeof(buffer); + uintToString( value, current ); + assert( current >= buffer ); + return current; +} + +#if defined(JSON_HAS_INT64) + +std::string valueToString( Int value ) +{ + return valueToString( LargestInt(value) ); +} + + +std::string valueToString( UInt value ) +{ + return valueToString( LargestUInt(value) ); +} + +#endif // # if defined(JSON_HAS_INT64) + + +std::string valueToString( double value ) +{ + char buffer[32]; +#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with visual studio 2005 to avoid warning. + sprintf_s(buffer, sizeof(buffer), "%#.16g", value); +#else + sprintf(buffer, "%#.16g", value); +#endif + char* ch = buffer + strlen(buffer) - 1; + if (*ch != '0') return buffer; // nothing to truncate, so save time + while(ch > buffer && *ch == '0'){ + --ch; + } + char* last_nonzero = ch; + while(ch >= buffer){ + switch(*ch){ + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + --ch; + continue; + case '.': + // Truncate zeroes to save bytes in output, but keep one. + *(last_nonzero+2) = '\0'; + return buffer; + default: + return buffer; + } + } + return buffer; +} + + +std::string valueToString( bool value ) +{ + return value ? "true" : "false"; +} + +std::string valueToQuotedString( const char *value ) +{ + // Not sure how to handle unicode... + if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL && !containsControlCharacter( value )) + return std::string("\"") + value + "\""; + // We have to walk value and escape any special characters. + // Appending to std::string is not efficient, but this should be rare. + // (Note: forward slashes are *not* rare, but I am not escaping them.) + std::string::size_type maxsize = strlen(value)*2 + 3; // allescaped+quotes+NULL + std::string result; + result.reserve(maxsize); // to avoid lots of mallocs + result += "\""; + for (const char* c=value; *c != 0; ++c) + { + switch(*c) + { + case '\"': + result += "\\\""; + break; + case '\\': + result += "\\\\"; + break; + case '\b': + result += "\\b"; + break; + case '\f': + result += "\\f"; + break; + case '\n': + result += "\\n"; + break; + case '\r': + result += "\\r"; + break; + case '\t': + result += "\\t"; + break; + //case '/': + // Even though \/ is considered a legal escape in JSON, a bare + // slash is also legal, so I see no reason to escape it. + // (I hope I am not misunderstanding something. + // blep notes: actually escaping \/ may be useful in javascript to avoid (*c); + result += oss.str(); + } + else + { + result += *c; + } + break; + } + } + result += "\""; + return result; +} + +// Class Writer +// ////////////////////////////////////////////////////////////////// +Writer::~Writer() +{ +} + + +// Class FastWriter +// ////////////////////////////////////////////////////////////////// + +FastWriter::FastWriter() + : yamlCompatiblityEnabled_( false ) +{ +} + + +void +FastWriter::enableYAMLCompatibility() +{ + yamlCompatiblityEnabled_ = true; +} + + +std::string +FastWriter::write( const Value &root ) +{ + document_ = ""; + writeValue( root ); + document_ += "\n"; + return document_; +} + + +void +FastWriter::writeValue( const Value &value ) +{ + switch ( value.type() ) + { + case nullValue: + document_ += "null"; + break; + case intValue: + document_ += valueToString( value.asLargestInt() ); + break; + case uintValue: + document_ += valueToString( value.asLargestUInt() ); + break; + case realValue: + document_ += valueToString( value.asDouble() ); + break; + case stringValue: + document_ += valueToQuotedString( value.asCString() ); + break; + case booleanValue: + document_ += valueToString( value.asBool() ); + break; + case arrayValue: + { + document_ += "["; + int size = value.size(); + for ( int index =0; index < size; ++index ) + { + if ( index > 0 ) + document_ += ","; + writeValue( value[index] ); + } + document_ += "]"; + } + break; + case objectValue: + { + Value::Members members( value.getMemberNames() ); + document_ += "{"; + for ( Value::Members::iterator it = members.begin(); + it != members.end(); + ++it ) + { + const std::string &name = *it; + if ( it != members.begin() ) + document_ += ","; + document_ += valueToQuotedString( name.c_str() ); + document_ += yamlCompatiblityEnabled_ ? ": " + : ":"; + writeValue( value[name] ); + } + document_ += "}"; + } + break; + } +} + + +// Class StyledWriter +// ////////////////////////////////////////////////////////////////// + +StyledWriter::StyledWriter() + : rightMargin_( 74 ) + , indentSize_( 3 ) +{ +} + + +std::string +StyledWriter::write( const Value &root ) +{ + document_ = ""; + addChildValues_ = false; + indentString_ = ""; + writeCommentBeforeValue( root ); + writeValue( root ); + writeCommentAfterValueOnSameLine( root ); + document_ += "\n"; + return document_; +} + + +void +StyledWriter::writeValue( const Value &value ) +{ + switch ( value.type() ) + { + case nullValue: + pushValue( "null" ); + break; + case intValue: + pushValue( valueToString( value.asLargestInt() ) ); + break; + case uintValue: + pushValue( valueToString( value.asLargestUInt() ) ); + break; + case realValue: + pushValue( valueToString( value.asDouble() ) ); + break; + case stringValue: + pushValue( valueToQuotedString( value.asCString() ) ); + break; + case booleanValue: + pushValue( valueToString( value.asBool() ) ); + break; + case arrayValue: + writeArrayValue( value); + break; + case objectValue: + { + Value::Members members( value.getMemberNames() ); + if ( members.empty() ) + pushValue( "{}" ); + else + { + writeWithIndent( "{" ); + indent(); + Value::Members::iterator it = members.begin(); + for (;;) + { + const std::string &name = *it; + const Value &childValue = value[name]; + writeCommentBeforeValue( childValue ); + writeWithIndent( valueToQuotedString( name.c_str() ) ); + document_ += " : "; + writeValue( childValue ); + if ( ++it == members.end() ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + document_ += ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "}" ); + } + } + break; + } +} + + +void +StyledWriter::writeArrayValue( const Value &value ) +{ + unsigned size = value.size(); + if ( size == 0 ) + pushValue( "[]" ); + else + { + bool isArrayMultiLine = isMultineArray( value ); + if ( isArrayMultiLine ) + { + writeWithIndent( "[" ); + indent(); + bool hasChildValue = !childValues_.empty(); + unsigned index =0; + for (;;) + { + const Value &childValue = value[index]; + writeCommentBeforeValue( childValue ); + if ( hasChildValue ) + writeWithIndent( childValues_[index] ); + else + { + writeIndent(); + writeValue( childValue ); + } + if ( ++index == size ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + document_ += ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "]" ); + } + else // output on a single line + { + assert( childValues_.size() == size ); + document_ += "[ "; + for ( unsigned index =0; index < size; ++index ) + { + if ( index > 0 ) + document_ += ", "; + document_ += childValues_[index]; + } + document_ += " ]"; + } + } +} + + +bool +StyledWriter::isMultineArray( const Value &value ) +{ + int size = value.size(); + bool isMultiLine = size*3 >= rightMargin_ ; + childValues_.clear(); + for ( int index =0; index < size && !isMultiLine; ++index ) + { + const Value &childValue = value[index]; + isMultiLine = isMultiLine || + ( (childValue.isArray() || childValue.isObject()) && + childValue.size() > 0 ); + } + if ( !isMultiLine ) // check if line length > max line length + { + childValues_.reserve( size ); + addChildValues_ = true; + int lineLength = 4 + (size-1)*2; // '[ ' + ', '*n + ' ]' + for ( int index =0; index < size && !isMultiLine; ++index ) + { + writeValue( value[index] ); + lineLength += int( childValues_[index].length() ); + isMultiLine = isMultiLine && hasCommentForValue( value[index] ); + } + addChildValues_ = false; + isMultiLine = isMultiLine || lineLength >= rightMargin_; + } + return isMultiLine; +} + + +void +StyledWriter::pushValue( const std::string &value ) +{ + if ( addChildValues_ ) + childValues_.push_back( value ); + else + document_ += value; +} + + +void +StyledWriter::writeIndent() +{ + if ( !document_.empty() ) + { + char last = document_[document_.length()-1]; + if ( last == ' ' ) // already indented + return; + if ( last != '\n' ) // Comments may add new-line + document_ += '\n'; + } + document_ += indentString_; +} + + +void +StyledWriter::writeWithIndent( const std::string &value ) +{ + writeIndent(); + document_ += value; +} + + +void +StyledWriter::indent() +{ + indentString_ += std::string( indentSize_, ' ' ); +} + + +void +StyledWriter::unindent() +{ + assert( int(indentString_.size()) >= indentSize_ ); + indentString_.resize( indentString_.size() - indentSize_ ); +} + + +void +StyledWriter::writeCommentBeforeValue( const Value &root ) +{ + if ( !root.hasComment( commentBefore ) ) + return; + document_ += normalizeEOL( root.getComment( commentBefore ) ); + document_ += "\n"; +} + + +void +StyledWriter::writeCommentAfterValueOnSameLine( const Value &root ) +{ + if ( root.hasComment( commentAfterOnSameLine ) ) + document_ += " " + normalizeEOL( root.getComment( commentAfterOnSameLine ) ); + + if ( root.hasComment( commentAfter ) ) + { + document_ += "\n"; + document_ += normalizeEOL( root.getComment( commentAfter ) ); + document_ += "\n"; + } +} + + +bool +StyledWriter::hasCommentForValue( const Value &value ) +{ + return value.hasComment( commentBefore ) + || value.hasComment( commentAfterOnSameLine ) + || value.hasComment( commentAfter ); +} + + +std::string +StyledWriter::normalizeEOL( const std::string &text ) +{ + std::string normalized; + normalized.reserve( text.length() ); + const char *begin = text.c_str(); + const char *end = begin + text.length(); + const char *current = begin; + while ( current != end ) + { + char c = *current++; + if ( c == '\r' ) // mac or dos EOL + { + if ( *current == '\n' ) // convert dos EOL + ++current; + normalized += '\n'; + } + else // handle unix EOL & other char + normalized += c; + } + return normalized; +} + + +// Class StyledStreamWriter +// ////////////////////////////////////////////////////////////////// + +StyledStreamWriter::StyledStreamWriter( std::string indentation ) + : document_(NULL) + , rightMargin_( 74 ) + , indentation_( indentation ) +{ +} + + +void +StyledStreamWriter::write( std::ostream &out, const Value &root ) +{ + document_ = &out; + addChildValues_ = false; + indentString_ = ""; + writeCommentBeforeValue( root ); + writeValue( root ); + writeCommentAfterValueOnSameLine( root ); + *document_ << "\n"; + document_ = NULL; // Forget the stream, for safety. +} + + +void +StyledStreamWriter::writeValue( const Value &value ) +{ + switch ( value.type() ) + { + case nullValue: + pushValue( "null" ); + break; + case intValue: + pushValue( valueToString( value.asLargestInt() ) ); + break; + case uintValue: + pushValue( valueToString( value.asLargestUInt() ) ); + break; + case realValue: + pushValue( valueToString( value.asDouble() ) ); + break; + case stringValue: + pushValue( valueToQuotedString( value.asCString() ) ); + break; + case booleanValue: + pushValue( valueToString( value.asBool() ) ); + break; + case arrayValue: + writeArrayValue( value); + break; + case objectValue: + { + Value::Members members( value.getMemberNames() ); + if ( members.empty() ) + pushValue( "{}" ); + else + { + writeWithIndent( "{" ); + indent(); + Value::Members::iterator it = members.begin(); + for (;;) + { + const std::string &name = *it; + const Value &childValue = value[name]; + writeCommentBeforeValue( childValue ); + writeWithIndent( valueToQuotedString( name.c_str() ) ); + *document_ << " : "; + writeValue( childValue ); + if ( ++it == members.end() ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + *document_ << ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "}" ); + } + } + break; + } +} + + +void +StyledStreamWriter::writeArrayValue( const Value &value ) +{ + unsigned size = value.size(); + if ( size == 0 ) + pushValue( "[]" ); + else + { + bool isArrayMultiLine = isMultineArray( value ); + if ( isArrayMultiLine ) + { + writeWithIndent( "[" ); + indent(); + bool hasChildValue = !childValues_.empty(); + unsigned index =0; + for (;;) + { + const Value &childValue = value[index]; + writeCommentBeforeValue( childValue ); + if ( hasChildValue ) + writeWithIndent( childValues_[index] ); + else + { + writeIndent(); + writeValue( childValue ); + } + if ( ++index == size ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + *document_ << ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "]" ); + } + else // output on a single line + { + assert( childValues_.size() == size ); + *document_ << "[ "; + for ( unsigned index =0; index < size; ++index ) + { + if ( index > 0 ) + *document_ << ", "; + *document_ << childValues_[index]; + } + *document_ << " ]"; + } + } +} + + +bool +StyledStreamWriter::isMultineArray( const Value &value ) +{ + int size = value.size(); + bool isMultiLine = size*3 >= rightMargin_ ; + childValues_.clear(); + for ( int index =0; index < size && !isMultiLine; ++index ) + { + const Value &childValue = value[index]; + isMultiLine = isMultiLine || + ( (childValue.isArray() || childValue.isObject()) && + childValue.size() > 0 ); + } + if ( !isMultiLine ) // check if line length > max line length + { + childValues_.reserve( size ); + addChildValues_ = true; + int lineLength = 4 + (size-1)*2; // '[ ' + ', '*n + ' ]' + for ( int index =0; index < size && !isMultiLine; ++index ) + { + writeValue( value[index] ); + lineLength += int( childValues_[index].length() ); + isMultiLine = isMultiLine && hasCommentForValue( value[index] ); + } + addChildValues_ = false; + isMultiLine = isMultiLine || lineLength >= rightMargin_; + } + return isMultiLine; +} + + +void +StyledStreamWriter::pushValue( const std::string &value ) +{ + if ( addChildValues_ ) + childValues_.push_back( value ); + else + *document_ << value; +} + + +void +StyledStreamWriter::writeIndent() +{ + /* + Some comments in this method would have been nice. ;-) + + if ( !document_.empty() ) + { + char last = document_[document_.length()-1]; + if ( last == ' ' ) // already indented + return; + if ( last != '\n' ) // Comments may add new-line + *document_ << '\n'; + } + */ + *document_ << '\n' << indentString_; +} + + +void +StyledStreamWriter::writeWithIndent( const std::string &value ) +{ + writeIndent(); + *document_ << value; +} + + +void +StyledStreamWriter::indent() +{ + indentString_ += indentation_; +} + + +void +StyledStreamWriter::unindent() +{ + assert( indentString_.size() >= indentation_.size() ); + indentString_.resize( indentString_.size() - indentation_.size() ); +} + + +void +StyledStreamWriter::writeCommentBeforeValue( const Value &root ) +{ + if ( !root.hasComment( commentBefore ) ) + return; + *document_ << normalizeEOL( root.getComment( commentBefore ) ); + *document_ << "\n"; +} + + +void +StyledStreamWriter::writeCommentAfterValueOnSameLine( const Value &root ) +{ + if ( root.hasComment( commentAfterOnSameLine ) ) + *document_ << " " + normalizeEOL( root.getComment( commentAfterOnSameLine ) ); + + if ( root.hasComment( commentAfter ) ) + { + *document_ << "\n"; + *document_ << normalizeEOL( root.getComment( commentAfter ) ); + *document_ << "\n"; + } +} + + +bool +StyledStreamWriter::hasCommentForValue( const Value &value ) +{ + return value.hasComment( commentBefore ) + || value.hasComment( commentAfterOnSameLine ) + || value.hasComment( commentAfter ); +} + + +std::string +StyledStreamWriter::normalizeEOL( const std::string &text ) +{ + std::string normalized; + normalized.reserve( text.length() ); + const char *begin = text.c_str(); + const char *end = begin + text.length(); + const char *current = begin; + while ( current != end ) + { + char c = *current++; + if ( c == '\r' ) // mac or dos EOL + { + if ( *current == '\n' ) // convert dos EOL + ++current; + normalized += '\n'; + } + else // handle unix EOL & other char + normalized += c; + } + return normalized; +} + + +std::ostream& operator<<( std::ostream &sout, const Value &root ) +{ + Json::StyledStreamWriter writer; + writer.write(sout, root); + return sout; +} + + +} // namespace Json + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_writer.cpp +// ////////////////////////////////////////////////////////////////////// diff --git a/Core/Code/CppMicroServices/src/util/stdint_p.h b/Core/CppMicroServices/src/util/stdint_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/stdint_p.h rename to Core/CppMicroServices/src/util/stdint_p.h diff --git a/Core/Code/CppMicroServices/src/util/stdint_vc_p.h b/Core/CppMicroServices/src/util/stdint_vc_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/stdint_vc_p.h rename to Core/CppMicroServices/src/util/stdint_vc_p.h diff --git a/Core/Code/CppMicroServices/src/util/tinfl.c b/Core/CppMicroServices/src/util/tinfl.c similarity index 100% rename from Core/Code/CppMicroServices/src/util/tinfl.c rename to Core/CppMicroServices/src/util/tinfl.c diff --git a/Core/Code/CppMicroServices/src/util/usAny.cpp b/Core/CppMicroServices/src/util/usAny.cpp similarity index 73% rename from Core/Code/CppMicroServices/src/util/usAny.cpp rename to Core/CppMicroServices/src/util/usAny.cpp index fbfd8eb1ab..bac8be2580 100644 --- a/Core/Code/CppMicroServices/src/util/usAny.cpp +++ b/Core/CppMicroServices/src/util/usAny.cpp @@ -1,56 +1,78 @@ /*============================================================================= 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 +std::ostream& operator<< (std::ostream& os, const Any& any) +{ + return os << any.ToString(); +} + 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()); } +std::string any_value_to_string(const std::map& val) +{ + std::stringstream ss; + ss << "["; + typedef std::map::const_iterator Iterator; + Iterator i1 = val.begin(); + const Iterator begin = i1; + const Iterator end = val.end(); + for ( ; i1 != end; ++i1) + { + if (i1 == begin) ss << "\"" << i1->first << "\" => " << i1->second; + else ss << ", " << "\"" << i1->first << "\" => " << i1->second; + } + ss << "]"; + return ss.str(); +} + US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/util/usAny.h b/Core/CppMicroServices/src/util/usAny.h similarity index 98% rename from Core/Code/CppMicroServices/src/util/usAny.h rename to Core/CppMicroServices/src/util/usAny.h index 8c0e4df75d..01b69af5d8 100644 --- a/Core/Code/CppMicroServices/src/util/usAny.h +++ b/Core/CppMicroServices/src/util/usAny.h @@ -1,400 +1,397 @@ /*============================================================================= 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 #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); +US_EXPORT std::string any_value_to_string(const std::map& 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/CppMicroServices/src/util/usAtomicInt_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usAtomicInt_p.h rename to Core/CppMicroServices/src/util/usAtomicInt_p.h diff --git a/Core/Code/CppMicroServices/src/util/usFunctor_p.h b/Core/CppMicroServices/src/util/usFunctor_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usFunctor_p.h rename to Core/CppMicroServices/src/util/usFunctor_p.h diff --git a/Core/Code/CppMicroServices/src/util/usSharedData.h b/Core/CppMicroServices/src/util/usSharedData.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usSharedData.h rename to Core/CppMicroServices/src/util/usSharedData.h diff --git a/Core/CppMicroServices/src/util/usSharedLibrary.cpp b/Core/CppMicroServices/src/util/usSharedLibrary.cpp new file mode 100644 index 0000000000..5bead2eaed --- /dev/null +++ b/Core/CppMicroServices/src/util/usSharedLibrary.cpp @@ -0,0 +1,273 @@ +/*============================================================================= + + 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 "usSharedLibrary.h" + +#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 + +#ifdef US_PLATFORM_POSIX +static const char PATH_SEPARATOR = '/'; +#else +static const char PATH_SEPARATOR = '\\'; +#endif + +class SharedLibraryPrivate : public SharedData +{ +public: + + SharedLibraryPrivate() + : m_Handle(NULL) + #ifdef US_PLATFORM_WINDOWS + , m_Suffix(".dll") + #elif defined(US_PLATFORM_APPLE) + , m_Suffix(".dylib") + , m_Prefix("lib") + #else + , m_Suffix(".so") + , m_Prefix("lib") + #endif + {} + + void* m_Handle; + + std::string m_Name; + std::string m_Path; + std::string m_FilePath; + std::string m_Suffix; + std::string m_Prefix; + +}; + +SharedLibrary::SharedLibrary() + : d(new SharedLibraryPrivate) +{ +} + +SharedLibrary::SharedLibrary(const SharedLibrary& other) + : d(other.d) +{ +} + +SharedLibrary::SharedLibrary(const std::string& libPath, const std::string& name) + : d(new SharedLibraryPrivate) +{ + d->m_Name = name; + d->m_Path = libPath; +} + +SharedLibrary::SharedLibrary(const std::string& absoluteFilePath) + : d(new SharedLibraryPrivate) +{ + d->m_FilePath = absoluteFilePath; + SetFilePath(absoluteFilePath); +} + +SharedLibrary::~SharedLibrary() +{ +} + +SharedLibrary& SharedLibrary::operator =(const SharedLibrary& other) +{ + d = other.d; + return *this; +} + +void SharedLibrary::Load(int flags) +{ + if (d->m_Handle) throw std::logic_error(std::string("Library already loaded: ") + GetFilePath()); + std::string libPath = GetFilePath(); +#ifdef US_PLATFORM_POSIX + d->m_Handle = dlopen(libPath.c_str(), flags); + if (!d->m_Handle) + { + const char* err = dlerror(); + throw std::runtime_error(err ? std::string(err) : (std::string("Error loading ") + libPath)); + } +#else + d->m_Handle = LoadLibrary(libPath.c_str()); + if (!d->m_Handle) + { + std::string errMsg = "Loading "; + errMsg.append(libPath).append("failed with error: ").append(GetLastErrorStr()); + + throw std::runtime_error(errMsg); + } +#endif +} + +void SharedLibrary::Load() +{ +#ifdef US_PLATFORM_POSIX +#ifdef US_GCC_RTTI_WORKAROUND_NEEDED + Load(RTLD_LAZY | RTLD_GLOBAL); +#else + Load(RTLD_LAZY | RTLD_LOCAL); +#endif +#else + Load(0); +#endif +} + +void SharedLibrary::Unload() +{ + if (d->m_Handle) + { +#ifdef US_PLATFORM_POSIX + if (dlclose(d->m_Handle)) + { + const char* err = dlerror(); + throw std::runtime_error(err ? std::string(err) : (std::string("Error unloading ") + GetLibraryPath())); + } +#else + if (!FreeLibrary((HMODULE)d->m_Handle)) + { + std::string errMsg = "Unloading "; + errMsg.append(GetLibraryPath()).append("failed with error: ").append(GetLastErrorStr()); + + throw std::runtime_error(errMsg); + } +#endif + d->m_Handle = 0; + } +} + +void SharedLibrary::SetName(const std::string& name) +{ + if (IsLoaded() || !d->m_FilePath.empty()) return; + d.Detach(); + d->m_Name = name; +} + +std::string SharedLibrary::GetName() const +{ + return d->m_Name; +} + +std::string SharedLibrary::GetFilePath(const std::string& name) const +{ + if (!d->m_FilePath.empty()) return d->m_FilePath; + return GetLibraryPath() + PATH_SEPARATOR + GetPrefix() + name + GetSuffix(); +} + +void SharedLibrary::SetFilePath(const std::string& absoluteFilePath) +{ + if (IsLoaded()) return; + + d.Detach(); + d->m_FilePath = absoluteFilePath; + + std::string name = d->m_FilePath; + std::size_t pos = d->m_FilePath.find_last_of(PATH_SEPARATOR); + if (pos != std::string::npos) + { + d->m_Path = d->m_FilePath.substr(0, pos); + name = d->m_FilePath.substr(pos+1); + } + else + { + d->m_Path.clear(); + } + + if (name.size() >= d->m_Prefix.size() && + name.compare(0, d->m_Prefix.size(), d->m_Prefix) == 0) + { + name = name.substr(d->m_Prefix.size()); + } + if (name.size() >= d->m_Suffix.size() && + name.compare(name.size()-d->m_Suffix.size(), d->m_Suffix.size(), d->m_Suffix) == 0) + { + name = name.substr(0, name.size()-d->m_Suffix.size()); + } + d->m_Name = name; +} + +std::string SharedLibrary::GetFilePath() const +{ + return GetFilePath(d->m_Name); +} + +void SharedLibrary::SetLibraryPath(const std::string& path) +{ + if (IsLoaded() || !d->m_FilePath.empty()) return; + d.Detach(); + d->m_Path = path; +} + +std::string SharedLibrary::GetLibraryPath() const +{ + return d->m_Path; +} + +void SharedLibrary::SetSuffix(const std::string& suffix) +{ + if (IsLoaded() || !d->m_FilePath.empty()) return; + d.Detach(); + d->m_Suffix = suffix; +} + +std::string SharedLibrary::GetSuffix() const +{ + return d->m_Suffix; +} + +void SharedLibrary::SetPrefix(const std::string& prefix) +{ + if (IsLoaded() || !d->m_FilePath.empty()) return; + d.Detach(); + d->m_Prefix = prefix; +} + +std::string SharedLibrary::GetPrefix() const +{ + return d->m_Prefix; +} + +void* SharedLibrary::GetHandle() const +{ + return d->m_Handle; +} + +bool SharedLibrary::IsLoaded() const +{ + return d->m_Handle != NULL; +} + +US_END_NAMESPACE diff --git a/Core/CppMicroServices/src/util/usSharedLibrary.h b/Core/CppMicroServices/src/util/usSharedLibrary.h new file mode 100644 index 0000000000..5bcd9308db --- /dev/null +++ b/Core/CppMicroServices/src/util/usSharedLibrary.h @@ -0,0 +1,223 @@ +/*============================================================================= + + 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 USSHAREDLIBRARY_H +#define USSHAREDLIBRARY_H + +#include "usConfig.h" +#include "usSharedData.h" + +#include + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4251) +#endif + +US_BEGIN_NAMESPACE + +class SharedLibraryPrivate; + +/** + * \ingroup MicroServicesUtils + * + * The SharedLibrary class loads shared libraries at runtime. + */ +class US_EXPORT SharedLibrary +{ +public: + + SharedLibrary(); + SharedLibrary(const SharedLibrary& other); + + /** + * Construct a SharedLibrary object using a library search path and + * a library base name. + * + * @param libPath An absolute path containing the shared library + * @param name The base name of the shared library, without prefix + * and suffix. + */ + SharedLibrary(const std::string& libPath, const std::string& name); + + /** + * Construct a SharedLibrary object using an absolute file path to + * the shared library. Using this constructor effectively disables + * all setters except SetFilePath(). + * + * @param absoluteFilePath The absolute path to the shared library. + */ + SharedLibrary(const std::string& absoluteFilePath); + + /** + * Destroys this object but does not unload the shared library. + */ + ~SharedLibrary(); + + SharedLibrary& operator=(const SharedLibrary& other); + + /** + * Loads the shared library pointed to by this SharedLibrary object. + * On POSIX systems dlopen() is called with the RTLD_LAZY and + * RTLD_LOCAL flags unless the compiler is gcc 4.4.x or older. Then + * the RTLD_LAZY and RTLD_GLOBAL flags are used to load the shared library + * to work around RTTI problems across shared library boundaries. + * + * @throws std::logic_error If the library is already loaded. + * @throws std::runtime_error If loading the library failed. + */ + void Load(); + + /** + * Loads the shared library pointed to by this SharedLibrary object, + * using the specified flags on POSIX systems. + * + * @throws std::logic_error If the library is already loaded. + * @throws std::runtime_error If loading the library failed. + */ + void Load(int flags); + + /** + * Un-loads the shared library pointed to by this SharedLibrary object. + * + * @throws std::runtime_error If an error occurred while un-loading the + * shared library. + */ + void Unload(); + + /** + * Sets the base name of the shared library. Does nothing if the shared + * library is already loaded or the SharedLibrary(const std::string&) + * constructor was used. + * + * @param name The base name of the shared library, without prefix and + * suffix. + */ + void SetName(const std::string& name); + + /** + * Gets the base name of the shared library. + * @return The shared libraries base name. + */ + std::string GetName() const; + + /** + * Gets the absolute file path for the shared library with base name + * \c name, using the search path returned by GetLibraryPath(). + * + * @param name The shared library base name. + * @return The absolute file path of the shared library. + */ + std::string GetFilePath(const std::string& name) const; + + /** + * Sets the absolute file path of this SharedLibrary object. + * Using this methods with a non-empty \c absoluteFilePath argument + * effectively disables all other setters. + * + * @param absoluteFilePath The new absolute file path of this SharedLibrary + * object. + */ + void SetFilePath(const std::string& absoluteFilePath); + + /** + * Gets the absolute file path of this SharedLibrary object. + * + * @return The absolute file path of the shared library. + */ + std::string GetFilePath() const; + + /** + * Sets a new library search path. Does nothing if the shared + * library is already loaded or the SharedLibrary(const std::string&) + * constructor was used. + * + * @param path The new shared library search path. + */ + void SetLibraryPath(const std::string& path); + + /** + * Gets the library search path of this SharedLibrary object. + * + * @return The library search path. + */ + std::string GetLibraryPath() const; + + /** + * Sets the suffix for shared library names (e.g. lib). Does nothing if the shared + * library is already loaded or the SharedLibrary(const std::string&) + * constructor was used. + * + * @param suffix The shared library name suffix. + */ + void SetSuffix(const std::string& suffix); + + /** + * Gets the file name suffix of this SharedLibrary object. + * + * @return The file name suffix of the shared library. + */ + std::string GetSuffix() const; + + /** + * Sets the file name prefix for shared library names (e.g. .dll or .so). + * Does nothing if the shared library is already loaded or the + * SharedLibrary(const std::string&) constructor was used. + * + * @param prefix The shared library name prefix. + */ + void SetPrefix(const std::string& prefix); + + /** + * Gets the file name prefix of this SharedLibrary object. + * + * @return The file name prefix of the shared library. + */ + std::string GetPrefix() const; + + /** + * Gets the internal handle of this SharedLibrary object. + * + * @return \c NULL if the shared library is not loaded, the operating + * system specific handle otherwise. + */ + void* GetHandle() const; + + /** + * Gets the loaded/unloaded stated of this SharedLibrary object. + * + * @return \c true if the shared library is loaded, \c false otherwise. + */ + bool IsLoaded() const; + +private: + + ExplicitlySharedDataPointer d; + +}; + +US_END_NAMESPACE + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif // USTESTUTILSHAREDLIBRARY_H diff --git a/Core/Code/CppMicroServices/src/util/usStaticInit_p.h b/Core/CppMicroServices/src/util/usStaticInit_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usStaticInit_p.h rename to Core/CppMicroServices/src/util/usStaticInit_p.h diff --git a/Core/Code/CppMicroServices/src/util/usThreads.cpp b/Core/CppMicroServices/src/util/usThreads.cpp similarity index 99% rename from Core/Code/CppMicroServices/src/util/usThreads.cpp rename to Core/CppMicroServices/src/util/usThreads.cpp index f26bc0c023..4464c9038e 100644 --- a/Core/Code/CppMicroServices/src/util/usThreads.cpp +++ b/Core/CppMicroServices/src/util/usThreads.cpp @@ -1,255 +1,254 @@ /*============================================================================= 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/CppMicroServices/src/util/usThreads_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usThreads_p.h rename to Core/CppMicroServices/src/util/usThreads_p.h diff --git a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.c b/Core/CppMicroServices/src/util/usUncompressResourceData.c similarity index 100% rename from Core/Code/CppMicroServices/src/util/usUncompressResourceData.c rename to Core/CppMicroServices/src/util/usUncompressResourceData.c diff --git a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.cpp b/Core/CppMicroServices/src/util/usUncompressResourceData.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/util/usUncompressResourceData.cpp rename to Core/CppMicroServices/src/util/usUncompressResourceData.cpp diff --git a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.h b/Core/CppMicroServices/src/util/usUncompressResourceData.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usUncompressResourceData.h rename to Core/CppMicroServices/src/util/usUncompressResourceData.h diff --git a/Core/Code/CppMicroServices/src/util/usUtils.cpp b/Core/CppMicroServices/src/util/usUtils.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/util/usUtils.cpp rename to Core/CppMicroServices/src/util/usUtils.cpp diff --git a/Core/Code/CppMicroServices/src/util/usUtils_p.h b/Core/CppMicroServices/src/util/usUtils_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usUtils_p.h rename to Core/CppMicroServices/src/util/usUtils_p.h diff --git a/Core/Code/CppMicroServices/test/CMakeLists.txt b/Core/CppMicroServices/test/CMakeLists.txt similarity index 71% rename from Core/Code/CppMicroServices/test/CMakeLists.txt rename to Core/CppMicroServices/test/CMakeLists.txt index c762ed9048..c4bb27b578 100644 --- a/Core/Code/CppMicroServices/test/CMakeLists.txt +++ b/Core/CppMicroServices/test/CMakeLists.txt @@ -1,102 +1,87 @@ #----------------------------------------------------------------------------- # 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 + usServiceFactoryTest + usServiceRegistryPerformanceTest usServiceRegistryTest + usServiceTemplateTest usServiceTrackerTest usStaticModuleResourceTest usStaticModuleTest ) if(US_BUILD_SHARED_LIBS) - list(APPEND _tests usServiceListenerTest) + list(APPEND _tests usServiceListenerTest usModuleManifestTest usSharedLibraryTest) 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) +usFunctionEmbedResources(_srcs EXECUTABLE_NAME ${_test_driver} FILES usTestResource.txt manifest.json) # 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 - ) + usFunctionGenerateExecutableInit(_srcs IDENTIFIER ${_test_driver}) 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}) +target_link_libraries(${_test_driver} ${US_LIBRARY_TARGET}) -if(NOT US_ENABLE_SERVICE_FACTORY_SUPPORT) - target_link_libraries(${_test_driver} ${US_BASECLASS_LIBRARIES}) +if(UNIX AND NOT APPLE) + target_link_libraries(${_test_driver} rt) 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/CppMicroServices/test/manifest.json b/Core/CppMicroServices/test/manifest.json new file mode 100644 index 0000000000..fb898a5477 --- /dev/null +++ b/Core/CppMicroServices/test/manifest.json @@ -0,0 +1,3 @@ +{ + "module.version" : "0.1.0" +} diff --git a/Core/Code/CppMicroServices/test/modules/CMakeLists.txt b/Core/CppMicroServices/test/modules/CMakeLists.txt similarity index 85% rename from Core/Code/CppMicroServices/test/modules/CMakeLists.txt rename to Core/CppMicroServices/test/modules/CMakeLists.txt index 6d02314c68..f303ee9753 100644 --- a/Core/Code/CppMicroServices/test/modules/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/CMakeLists.txt @@ -1,11 +1,13 @@ add_subdirectory(libA) add_subdirectory(libA2) add_subdirectory(libAL) add_subdirectory(libAL2) add_subdirectory(libBWithStatic) +add_subdirectory(libH) +add_subdirectory(libM) 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/CppMicroServices/test/modules/libA/CMakeLists.txt similarity index 98% rename from Core/Code/CppMicroServices/test/modules/libA/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libA/CMakeLists.txt index c3b4969f7b..48211b0c66 100644 --- a/Core/Code/CppMicroServices/test/modules/libA/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libA/CMakeLists.txt @@ -1,3 +1,2 @@ usFunctionCreateTestModule(TestModuleA usTestModuleA.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libA/usTestModuleA.cpp b/Core/CppMicroServices/test/modules/libA/usTestModuleA.cpp similarity index 92% rename from Core/Code/CppMicroServices/test/modules/libA/usTestModuleA.cpp rename to Core/CppMicroServices/test/modules/libA/usTestModuleA.cpp index e2333c2bee..a654901ef2 100644 --- a/Core/Code/CppMicroServices/test/modules/libA/usTestModuleA.cpp +++ b/Core/CppMicroServices/test/modules/libA/usTestModuleA.cpp @@ -1,80 +1,77 @@ /*============================================================================= 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 +struct TestModuleA : public TestModuleAService { TestModuleA(ModuleContext* mc) { US_INFO << "Registering TestModuleAService"; sr = mc->RegisterService(this); } void Unregister() { if (sr) { sr.Unregister(); sr = 0; } } private: - ServiceRegistration sr; + 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/CppMicroServices/test/modules/libA/usTestModuleAService.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libA/usTestModuleAService.h rename to Core/CppMicroServices/test/modules/libA/usTestModuleAService.h diff --git a/Core/Code/CppMicroServices/test/modules/libA2/CMakeLists.txt b/Core/CppMicroServices/test/modules/libA2/CMakeLists.txt similarity index 98% rename from Core/Code/CppMicroServices/test/modules/libA2/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libA2/CMakeLists.txt index 28340c7d2c..21968cba8c 100644 --- a/Core/Code/CppMicroServices/test/modules/libA2/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libA2/CMakeLists.txt @@ -1,3 +1,2 @@ usFunctionCreateTestModule(TestModuleA2 usTestModuleA2.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp b/Core/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp similarity index 92% rename from Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp rename to Core/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp index 187870044f..d2d03adeeb 100644 --- a/Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp +++ b/Core/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp @@ -1,79 +1,76 @@ /*============================================================================= 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 +struct TestModuleA2 : public TestModuleA2Service { TestModuleA2(ModuleContext* mc) { US_INFO << "Registering TestModuleA2Service"; sr = mc->RegisterService(this); } void Unregister() { if (sr) { sr.Unregister(); } } private: - ServiceRegistration sr; + 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/CppMicroServices/test/modules/libA2/usTestModuleA2Service.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2Service.h rename to Core/CppMicroServices/test/modules/libA2/usTestModuleA2Service.h diff --git a/Core/Code/CppMicroServices/test/modules/libAL/CMakeLists.txt b/Core/CppMicroServices/test/modules/libAL/CMakeLists.txt similarity index 98% rename from Core/Code/CppMicroServices/test/modules/libAL/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libAL/CMakeLists.txt index 83a38c679b..224c6f09cb 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libAL/CMakeLists.txt @@ -1,5 +1,4 @@ usFunctionCreateTestModule(TestModuleAL usTestModuleAL.cpp) add_subdirectory(libAL_1) - diff --git a/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt b/Core/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt index 11c58a935f..5db0e45894 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt @@ -1,7 +1,6 @@ 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/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp rename to Core/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp index 1c0ca73f54..dd15f10b16 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp +++ b/Core/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp @@ -1,31 +1,30 @@ /*============================================================================= 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/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp rename to Core/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp index 9b0abf1b25..aaee431545 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp +++ b/Core/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp @@ -1,31 +1,30 @@ /*============================================================================= 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/CppMicroServices/test/modules/libAL2/CMakeLists.txt b/Core/CppMicroServices/test/modules/libAL2/CMakeLists.txt new file mode 100644 index 0000000000..8fefb1736d --- /dev/null +++ b/Core/CppMicroServices/test/modules/libAL2/CMakeLists.txt @@ -0,0 +1,4 @@ + +usFunctionCreateTestModuleWithResources(TestModuleAL2 SOURCES usTestModuleAL2.cpp RESOURCES manifest.json) + +add_subdirectory(libAL2_1) diff --git a/Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt b/Core/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt index 074d20f014..7c65e41ee5 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt @@ -1,7 +1,6 @@ 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/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp rename to Core/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp index 684e38c5d3..b81eb15a35 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp +++ b/Core/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp @@ -1,31 +1,30 @@ /*============================================================================= 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/CppMicroServices/test/modules/libAL2/resources/manifest.json b/Core/CppMicroServices/test/modules/libAL2/resources/manifest.json new file mode 100644 index 0000000000..4772f1f57c --- /dev/null +++ b/Core/CppMicroServices/test/modules/libAL2/resources/manifest.json @@ -0,0 +1,3 @@ +{ + "module.autoload_dir" : "autoload_al2" +} diff --git a/Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp b/Core/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp rename to Core/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp index 6f81242b11..0388565838 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp +++ b/Core/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp @@ -1,31 +1,30 @@ /*============================================================================= 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/CppMicroServices/test/modules/libBWithStatic/CMakeLists.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libBWithStatic/CMakeLists.txt diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/dynamic.txt b/Core/CppMicroServices/test/modules/libBWithStatic/resources/dynamic.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/dynamic.txt rename to Core/CppMicroServices/test/modules/libBWithStatic/resources/dynamic.txt diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/res.txt b/Core/CppMicroServices/test/modules/libBWithStatic/resources/res.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/res.txt rename to Core/CppMicroServices/test/modules/libBWithStatic/resources/res.txt diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/res.txt b/Core/CppMicroServices/test/modules/libBWithStatic/resources_static/res.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/res.txt rename to Core/CppMicroServices/test/modules/libBWithStatic/resources_static/res.txt diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/static.txt b/Core/CppMicroServices/test/modules/libBWithStatic/resources_static/static.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/static.txt rename to Core/CppMicroServices/test/modules/libBWithStatic/resources_static/static.txt diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp b/Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp similarity index 94% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp rename to Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp index 1b18b2a4c8..7111c3164a 100644 --- a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp +++ b/Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp @@ -1,73 +1,71 @@ /*============================================================================= 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 +struct TestModuleB : 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/CppMicroServices/test/modules/libBWithStatic/usTestModuleBService.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleBService.h rename to Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleBService.h diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp b/Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp similarity index 93% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp rename to Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp index 34459640f1..8c6008e506 100644 --- a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp +++ b/Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp @@ -1,67 +1,65 @@ /*============================================================================= 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 +struct TestModuleImportedByB : 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/CppMicroServices/test/modules/libH/CMakeLists.txt b/Core/CppMicroServices/test/modules/libH/CMakeLists.txt new file mode 100644 index 0000000000..0aa0176b5d --- /dev/null +++ b/Core/CppMicroServices/test/modules/libH/CMakeLists.txt @@ -0,0 +1,2 @@ + +usFunctionCreateTestModule(TestModuleH usTestModuleH.cpp) diff --git a/Core/CppMicroServices/test/modules/libH/usTestModuleH.cpp b/Core/CppMicroServices/test/modules/libH/usTestModuleH.cpp new file mode 100644 index 0000000000..2352c039a4 --- /dev/null +++ b/Core/CppMicroServices/test/modules/libH/usTestModuleH.cpp @@ -0,0 +1,147 @@ +/*============================================================================= + + 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_BEGIN_NAMESPACE + +struct TestModuleH +{ + virtual ~TestModuleH() {} +}; + +struct TestModuleH2 +{ + virtual ~TestModuleH2() {} +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleH), "org.cppmicroservices.TestModuleH") +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleH2), "org.cppmicroservices.TestModuleH2") + +US_BEGIN_NAMESPACE + +class TestProduct : public TestModuleH +{ + Module* caller; + +public: + + TestProduct(Module* caller) + : caller(caller) + {} + +}; + +class TestProduct2 : public TestProduct, public TestModuleH2 +{ +public: + + TestProduct2(Module* caller) + : TestProduct(caller) + {} + +}; + +class TestModuleHPrototypeServiceFactory : public PrototypeServiceFactory +{ + std::map > fcbind; // Map calling module with implementation + +public: + + InterfaceMap GetService(Module* caller, const ServiceRegistrationBase& /*sReg*/) + { + std::cout << "GetService (prototype) in H" << std::endl; + TestProduct2* product = new TestProduct2(caller); + fcbind[caller->GetModuleId()].push_back(product); + return MakeInterfaceMap(product); + } + + void UngetService(Module* caller, const ServiceRegistrationBase& /*sReg*/, const InterfaceMap& service) + { + TestProduct2* product = dynamic_cast(ExtractInterface(service)); + delete product; + fcbind[caller->GetModuleId()].remove(product); + } + +}; + + +class TestModuleHActivator : public ModuleActivator, public ServiceFactory +{ + std::string thisServiceName; + ServiceRegistration factoryService; + ServiceRegistration prototypeFactoryService; + ModuleContext* mc; + + std::map fcbind; // Map calling module with implementation + TestModuleHPrototypeServiceFactory prototypeFactory; + +public: + + TestModuleHActivator() + : thisServiceName(us_service_interface_iid()) + , mc(NULL) + {} + + void Load(ModuleContext* mc) + { + std::cout << "start in H" << std::endl; + this->mc = mc; + factoryService = mc->RegisterService(this); + prototypeFactoryService = mc->RegisterService(static_cast(&prototypeFactory)); + } + + void Unload(ModuleContext* /*mc*/) + { + factoryService.Unregister(); + } + + InterfaceMap GetService(Module* caller, const ServiceRegistrationBase& /*sReg*/) + { + std::cout << "GetService in H" << std::endl; + TestProduct* product = new TestProduct(caller); + fcbind.insert(std::make_pair(caller->GetModuleId(), product)); + return MakeInterfaceMap(product); + } + + void UngetService(Module* caller, const ServiceRegistrationBase& /*sReg*/, const InterfaceMap& service) + { + TestModuleH* product = ExtractInterface(service); + delete product; + fcbind.erase(caller->GetModuleId()); + } + +}; + + +US_END_NAMESPACE + +US_EXPORT_MODULE_ACTIVATOR(TestModuleH, us::TestModuleHActivator) diff --git a/Core/CppMicroServices/test/modules/libM/CMakeLists.txt b/Core/CppMicroServices/test/modules/libM/CMakeLists.txt new file mode 100644 index 0000000000..c96b103203 --- /dev/null +++ b/Core/CppMicroServices/test/modules/libM/CMakeLists.txt @@ -0,0 +1,8 @@ + +set(resource_files + manifest.json +) + +usFunctionCreateTestModuleWithResources(TestModuleM + SOURCES usTestModuleM.cpp + RESOURCES ${resource_files}) diff --git a/Core/CppMicroServices/test/modules/libM/resources/manifest.json b/Core/CppMicroServices/test/modules/libM/resources/manifest.json new file mode 100644 index 0000000000..c2b05e4708 --- /dev/null +++ b/Core/CppMicroServices/test/modules/libM/resources/manifest.json @@ -0,0 +1,16 @@ +{ + "module.name": "TestModuleM Module", + "module.description": "My Module description", + "module.version": "1.0.0", + "number": 5, + "vector": [ + "first", + 2, + "third" + ], + "map": { + "string": "hi", + "number": 4, + "list": [ "a", "b" ] + } +} diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp b/Core/CppMicroServices/test/modules/libM/usTestModuleM.cpp similarity index 87% copy from Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp copy to Core/CppMicroServices/test/modules/libM/usTestModuleM.cpp index 602caaf82f..934056c84b 100644 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp +++ b/Core/CppMicroServices/test/modules/libM/usTestModuleM.cpp @@ -1,44 +1,43 @@ /*============================================================================= 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 +class TestModuleMActivator : public ModuleActivator { public: void Load(ModuleContext*) { } void Unload(ModuleContext*) { } }; US_END_NAMESPACE -US_EXPORT_MODULE_ACTIVATOR(TestModuleR, US_PREPEND_NAMESPACE(TestModuleRActivator)) - +US_EXPORT_MODULE_ACTIVATOR(TestModuleM, US_PREPEND_NAMESPACE(TestModuleMActivator)) diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt b/Core/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt index c39359ab09..e5ff2c8109 100644 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt @@ -1,14 +1,13 @@ 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/CppMicroServices/test/modules/libRWithResources/resources/foo.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/resources/foo.txt rename to Core/CppMicroServices/test/modules/libRWithResources/resources/foo.txt diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/compressable.bmp b/Core/CppMicroServices/test/modules/libRWithResources/resources/icons/compressable.bmp similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/compressable.bmp rename to Core/CppMicroServices/test/modules/libRWithResources/resources/icons/compressable.bmp diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/cppmicroservices.png b/Core/CppMicroServices/test/modules/libRWithResources/resources/icons/cppmicroservices.png similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/cppmicroservices.png rename to Core/CppMicroServices/test/modules/libRWithResources/resources/icons/cppmicroservices.png diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/readme.txt b/Core/CppMicroServices/test/modules/libRWithResources/resources/icons/readme.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/readme.txt rename to Core/CppMicroServices/test/modules/libRWithResources/resources/icons/readme.txt diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/special_chars.dummy.txt b/Core/CppMicroServices/test/modules/libRWithResources/resources/special_chars.dummy.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/resources/special_chars.dummy.txt rename to Core/CppMicroServices/test/modules/libRWithResources/resources/special_chars.dummy.txt diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/test.xml b/Core/CppMicroServices/test/modules/libRWithResources/resources/test.xml similarity index 98% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/resources/test.xml rename to Core/CppMicroServices/test/modules/libRWithResources/resources/test.xml index 23208713be..bc90bc6ca9 100644 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/test.xml +++ b/Core/CppMicroServices/test/modules/libRWithResources/resources/test.xml @@ -1,4 +1,3 @@ hi - diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp b/Core/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp rename to Core/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp index 602caaf82f..be8c0291ca 100644 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp +++ b/Core/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp @@ -1,44 +1,43 @@ /*============================================================================= 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/CppMicroServices/test/modules/libS/CMakeLists.txt similarity index 98% rename from Core/Code/CppMicroServices/test/modules/libS/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libS/CMakeLists.txt index 1b97fc79ad..cb4ef91bb3 100644 --- a/Core/Code/CppMicroServices/test/modules/libS/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libS/CMakeLists.txt @@ -1,3 +1,2 @@ usFunctionCreateTestModule(TestModuleS usTestModuleS.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleS.cpp b/Core/CppMicroServices/test/modules/libS/usTestModuleS.cpp similarity index 83% rename from Core/Code/CppMicroServices/test/modules/libS/usTestModuleS.cpp rename to Core/CppMicroServices/test/modules/libS/usTestModuleS.cpp index 6ced8e1eb3..b25ead2668 100644 --- a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleS.cpp +++ b/Core/CppMicroServices/test/modules/libS/usTestModuleS.cpp @@ -1,137 +1,143 @@ /*============================================================================= 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, +class TestModuleS : 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()); + servregs.push_back(ServiceRegistrationU()); } sreg = mc->RegisterService(this); + sciReg = 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; + InterfaceMap ifm; + ifm.insert(std::make_pair(servicename.str(), static_cast(this))); ServiceProperties props; props.insert(std::make_pair(ServiceConstants::SERVICE_RANKING(), Any(ranking))); - servregs[offset] = mc->RegisterService(servicename.str().c_str(), this, props); + servregs[offset] = mc->RegisterService(ifm, props); } } if (operation == "unregister") { if (servregs[offset]) { - ServiceRegistration sr1 = servregs[offset]; + ServiceRegistrationU sr1 = servregs[offset]; sr1.Unregister(); servregs[offset] = 0; } } } } void Unregister() { if (sreg) { sreg.Unregister(); } + if (sciReg) + { + sciReg.Unregister(); + } } private: static const std::string SERVICE; // = "org.cppmicroservices.TestModuleSService" ModuleContext* mc; - std::vector servregs; - ServiceRegistration sreg; + std::vector servregs; + ServiceRegistration sreg; + ServiceRegistration sciReg; }; 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/CppMicroServices/test/modules/libS/usTestModuleSService0.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService0.h rename to Core/CppMicroServices/test/modules/libS/usTestModuleSService0.h diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService1.h b/Core/CppMicroServices/test/modules/libS/usTestModuleSService1.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService1.h rename to Core/CppMicroServices/test/modules/libS/usTestModuleSService1.h diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService2.h b/Core/CppMicroServices/test/modules/libS/usTestModuleSService2.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService2.h rename to Core/CppMicroServices/test/modules/libS/usTestModuleSService2.h diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService3.h b/Core/CppMicroServices/test/modules/libS/usTestModuleSService3.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService3.h rename to Core/CppMicroServices/test/modules/libS/usTestModuleSService3.h diff --git a/Core/Code/CppMicroServices/test/modules/libSL1/CMakeLists.txt b/Core/CppMicroServices/test/modules/libSL1/CMakeLists.txt similarity index 98% rename from Core/Code/CppMicroServices/test/modules/libSL1/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libSL1/CMakeLists.txt index caabb07644..29d6d614c3 100644 --- a/Core/Code/CppMicroServices/test/modules/libSL1/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libSL1/CMakeLists.txt @@ -1,3 +1,2 @@ usFunctionCreateTestModule(TestModuleSL1 usActivatorSL1.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp b/Core/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp similarity index 77% rename from Core/Code/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp rename to Core/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp index 70d429e6b2..f7070ce255 100644 --- a/Core/Code/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp +++ b/Core/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp @@ -1,108 +1,106 @@ /*============================================================================= 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 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); + InterfaceMap im = MakeInterfaceMap(this); + im.insert(std::make_pair(std::string("ActivatorSL1"), this)); + sr = context->RegisterService(im); 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) + FooService* AddingService(const ServiceReferenceT& reference) { props["serviceAdded"] = true; FooService* fooService = context->GetService(reference); fooService->foo(); return fooService; } - void ModifiedService(const ServiceReference& /*reference*/, FooService* /*service*/) + void ModifiedService(const ServiceReferenceT& /*reference*/, FooService* /*service*/) {} - void RemovedService(const ServiceReference& /*reference*/, FooService* /*service*/) + void RemovedService(const ServiceReferenceT& /*reference*/, FooService* /*service*/) { props["serviceRemoved"] = true; } private: ModulePropsInterface::Properties props; - ServiceRegistration sr; + ServiceRegistrationU sr; - typedef ServiceTracker FooTracker; + 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/CppMicroServices/test/modules/libSL1/usFooService.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libSL1/usFooService.h rename to Core/CppMicroServices/test/modules/libSL1/usFooService.h diff --git a/Core/Code/CppMicroServices/test/modules/libSL3/CMakeLists.txt b/Core/CppMicroServices/test/modules/libSL3/CMakeLists.txt similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libSL3/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libSL3/CMakeLists.txt index 6d11053a64..a342806dd6 100644 --- a/Core/Code/CppMicroServices/test/modules/libSL3/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libSL3/CMakeLists.txt @@ -1,5 +1,4 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../libSL1) usFunctionCreateTestModule(TestModuleSL3 usActivatorSL3.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp b/Core/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp similarity index 74% rename from Core/Code/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp rename to Core/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp index 965b5d4b01..ea5e9a8706 100644 --- a/Core/Code/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp +++ b/Core/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp @@ -1,102 +1,100 @@ /*============================================================================= 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 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); + InterfaceMap im = MakeInterfaceMap(this); + im.insert(std::make_pair(std::string("ActivatorSL3"), this)); + sr = context->RegisterService(im); 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) + FooService* AddingService(const ServiceReferenceT& reference) { props["serviceAdded"] = true; US_INFO << "SL3: Adding reference =" << reference; - FooService* fooService = context->GetService(reference); + FooService* fooService = context->GetService(reference); fooService->foo(); return fooService; } - void ModifiedService(const ServiceReference& /*reference*/, FooService* /*service*/) + void ModifiedService(const ServiceReferenceT& /*reference*/, FooService* /*service*/) { } - void RemovedService(const ServiceReference& reference, FooService* /*service*/) + void RemovedService(const ServiceReferenceT& reference, FooService* /*service*/) { props["serviceRemoved"] = true; US_INFO << "SL3: Removing reference =" << reference; } private: - typedef ServiceTracker FooTracker; + typedef ServiceTracker FooTracker; FooTracker* tracker; ModuleContext* context; - ServiceRegistration sr; + ServiceRegistrationU 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/CppMicroServices/test/modules/libSL4/CMakeLists.txt similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libSL4/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libSL4/CMakeLists.txt index b81486fc62..e81e7e6428 100644 --- a/Core/Code/CppMicroServices/test/modules/libSL4/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libSL4/CMakeLists.txt @@ -1,5 +1,4 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../libSL1) usFunctionCreateTestModule(TestModuleSL4 usActivatorSL4.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp b/Core/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp similarity index 91% rename from Core/Code/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp rename to Core/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp index a048128d83..4f0aebb814 100644 --- a/Core/Code/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp +++ b/Core/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp @@ -1,67 +1,65 @@ /*============================================================================= 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 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; + 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/CppMicroServices/test/usDebugOutputTest.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/usDebugOutputTest.cpp rename to Core/CppMicroServices/test/usDebugOutputTest.cpp index c3aab61b92..3fcc643854 100644 --- a/Core/Code/CppMicroServices/test/usDebugOutputTest.cpp +++ b/Core/CppMicroServices/test/usDebugOutputTest.cpp @@ -1,100 +1,99 @@ /*============================================================================= 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/CppMicroServices/test/usLDAPFilterTest.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/usLDAPFilterTest.cpp rename to Core/CppMicroServices/test/usLDAPFilterTest.cpp index 7b2f9b2165..f81a4f3bc7 100644 --- a/Core/Code/CppMicroServices/test/usLDAPFilterTest.cpp +++ b/Core/CppMicroServices/test/usLDAPFilterTest.cpp @@ -1,150 +1,149 @@ /*============================================================================= 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/CppMicroServices/test/usModuleAutoLoadTest.cpp similarity index 92% rename from Core/Code/CppMicroServices/test/usModuleAutoLoadTest.cpp rename to Core/CppMicroServices/test/usModuleAutoLoadTest.cpp index 0fb0042ca3..db5dae1a76 100644 --- a/Core/Code/CppMicroServices/test/usModuleAutoLoadTest.cpp +++ b/Core/CppMicroServices/test/usModuleAutoLoadTest.cpp @@ -1,170 +1,176 @@ /*============================================================================= 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 -#include "usTestUtilSharedLibrary.h" #include "usTestUtilModuleListener.h" #include "usTestingMacros.h" #include US_USE_NAMESPACE namespace { +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + void testDefaultAutoLoadPath(bool autoLoadEnabled) { ModuleContext* mc = GetModuleContext(); assert(mc); - TestModuleListener listener(mc); + TestModuleListener listener; 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"); + SharedLibrary libAL(LIB_PATH, "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); + TestModuleListener listener; 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"); + SharedLibrary libAL2(LIB_PATH, "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/CppMicroServices/test/usModuleManifestTest.cpp b/Core/CppMicroServices/test/usModuleManifestTest.cpp new file mode 100644 index 0000000000..757a38da59 --- /dev/null +++ b/Core/CppMicroServices/test/usModuleManifestTest.cpp @@ -0,0 +1,96 @@ +/*============================================================================= + + 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 + +#include "usTestingMacros.h" +#include "usTestingConfig.h" + +US_USE_NAMESPACE + +namespace { + +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + +} // end unnamed namespace + +int usModuleManifestTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ModuleManifestTest"); + + SharedLibrary target(LIB_PATH, "TestModuleM"); + + // 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" ); + } + + Module* moduleM = ModuleRegistry::GetModule("TestModuleM Module"); + US_TEST_CONDITION_REQUIRED(moduleM != 0, "Test for existing module TestModuleM") + + US_TEST_CONDITION(moduleM->GetProperty(Module::PROP_NAME()).ToString() == "TestModuleM Module", "Module name") + US_TEST_CONDITION(moduleM->GetName() == "TestModuleM Module", "Module name 2") + US_TEST_CONDITION(moduleM->GetProperty(Module::PROP_DESCRIPTION()).ToString() == "My Module description", "Module description") + US_TEST_CONDITION(moduleM->GetLocation() == moduleM->GetProperty(Module::PROP_LOCATION()).ToString(), "Module location") + US_TEST_CONDITION(moduleM->GetProperty(Module::PROP_VERSION()).ToString() == "1.0.0", "Module version") + US_TEST_CONDITION(moduleM->GetVersion() == ModuleVersion(1,0,0), "Module version 2") + + Any anyVector = moduleM->GetProperty("vector"); + US_TEST_CONDITION_REQUIRED(anyVector.Type() == typeid(std::vector), "vector type") + std::vector& vec = ref_any_cast >(anyVector); + US_TEST_CONDITION_REQUIRED(vec.size() == 3, "vector size") + US_TEST_CONDITION_REQUIRED(vec[0].Type() == typeid(std::string), "vector 0 type") + US_TEST_CONDITION_REQUIRED(vec[0].ToString() == "first", "vector 0 value") + US_TEST_CONDITION_REQUIRED(vec[1].Type() == typeid(int), "vector 1 type") + US_TEST_CONDITION_REQUIRED(any_cast(vec[1]) == 2, "vector 1 value") + + Any anyMap = moduleM->GetProperty("map"); + US_TEST_CONDITION_REQUIRED(anyMap.Type() == typeid(std::map), "map type") + std::map& m = ref_any_cast >(anyMap); + US_TEST_CONDITION_REQUIRED(m.size() == 3, "map size") + US_TEST_CONDITION_REQUIRED(m["string"].Type() == typeid(std::string), "map 0 type") + US_TEST_CONDITION_REQUIRED(m["string"].ToString() == "hi", "map 0 value") + US_TEST_CONDITION_REQUIRED(m["number"].Type() == typeid(int), "map 1 type") + US_TEST_CONDITION_REQUIRED(any_cast(m["number"]) == 4, "map 1 value") + US_TEST_CONDITION_REQUIRED(m["list"].Type() == typeid(std::vector), "map 2 type") + US_TEST_CONDITION_REQUIRED(any_cast >(m["list"]).size() == 2, "map 2 value size") + + target.Unload(); + + US_TEST_END() +} diff --git a/Core/Code/CppMicroServices/test/usModulePropsInterface.h b/Core/CppMicroServices/test/usModulePropsInterface.h similarity index 100% rename from Core/Code/CppMicroServices/test/usModulePropsInterface.h rename to Core/CppMicroServices/test/usModulePropsInterface.h diff --git a/Core/Code/CppMicroServices/test/usModuleResourceTest.cpp b/Core/CppMicroServices/test/usModuleResourceTest.cpp similarity index 95% rename from Core/Code/CppMicroServices/test/usModuleResourceTest.cpp rename to Core/CppMicroServices/test/usModuleResourceTest.cpp index 4185701c8a..ac4fc25cda 100644 --- a/Core/Code/CppMicroServices/test/usModuleResourceTest.cpp +++ b/Core/CppMicroServices/test/usModuleResourceTest.cpp @@ -1,534 +1,542 @@ /*============================================================================= 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 -#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_REQUIRED(children.size() == 10, "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") + US_TEST_CONDITION(children[3] == "manifest.json", "Check manifest.json child name") + US_TEST_CONDITION(children[4] == "manifest.json", "Check manifest.json child name") + US_TEST_CONDITION(children[5] == "res.txt", "Check res.txt child name") + US_TEST_CONDITION(children[6] == "res.txt", "Check res.txt child name") + US_TEST_CONDITION(children[7] == "special_chars.dummy.txt", "Check special_chars.dummy.txt child name") + US_TEST_CONDITION(children[8] == "static.txt", "Check static.txt child name") + US_TEST_CONDITION(children[9] == "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") + US_TEST_CONDITION(nodes.size() == 12, "Total resource number") nodes = module->FindResources("", "**", true); - US_TEST_CONDITION(nodes.size() == 10, "Total resource number") + US_TEST_CONDITION(nodes.size() == 12, "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"); + +#ifdef US_PLATFORM_WINDOWS + const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + SharedLibrary libR(LIB_PATH, "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/CppMicroServices/test/usModuleTest.cpp similarity index 89% rename from Core/Code/CppMicroServices/test/usModuleTest.cpp rename to Core/CppMicroServices/test/usModuleTest.cpp index 7958a1891e..43ff75ee8d 100644 --- a/Core/Code/CppMicroServices/test/usModuleTest.cpp +++ b/Core/CppMicroServices/test/usModuleTest.cpp @@ -1,317 +1,325 @@ /*============================================================================= 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 -#include US_BASECLASS_HEADER - -#include "usTestUtilSharedLibrary.h" #include "usTestUtilModuleListener.h" #include "usTestingMacros.h" +#include "usTestingConfig.h" US_USE_NAMESPACE namespace { +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif // 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); + TestModuleListener listener1; + TestModuleListener listener2; 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"); + SharedLibrary target(LIB_PATH, "TestModuleA"); +#ifdef US_BUILD_SHARED_LIBS // 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") + US_TEST_CONDITION(ModuleVersion(1,99,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"; + mc->GetService(ServiceReferenceU()); + US_DEBUG << "Got service object, 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) +void frame020a(ModuleContext* mc, TestModuleListener& listener, +#ifdef US_BUILD_SHARED_LIBS + SharedLibrary& 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") +#else + SharedLibrary& /*libA*/) +{ #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"); + ServiceReferenceU sr1 = mc->GetServiceReference("org.cppmicroservices.TestModuleAService"); + InterfaceMap o1 = mc->GetService(sr1); + US_TEST_CONDITION(!o1.empty(), "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) +void frame030b(ModuleContext* mc, TestModuleListener& listener, SharedLibrary& 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 + ServiceReferenceU 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); + TestModuleListener listener; 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"); + SharedLibrary libA(LIB_PATH, "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/CppMicroServices/test/usServiceControlInterface.h similarity index 100% rename from Core/Code/CppMicroServices/test/usServiceControlInterface.h rename to Core/CppMicroServices/test/usServiceControlInterface.h diff --git a/Core/CppMicroServices/test/usServiceFactoryTest.cpp b/Core/CppMicroServices/test/usServiceFactoryTest.cpp new file mode 100644 index 0000000000..14c7a8feaa --- /dev/null +++ b/Core/CppMicroServices/test/usServiceFactoryTest.cpp @@ -0,0 +1,234 @@ +/*============================================================================= + + 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 "usTestingMacros.h" +#include "usTestingConfig.h" + +US_USE_NAMESPACE + +namespace { + +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + +} // end unnamed namespace + + +US_BEGIN_NAMESPACE + +struct TestModuleH +{ + virtual ~TestModuleH() {} +}; + +struct TestModuleH2 +{ + virtual ~TestModuleH2() {} +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleH), "org.cppmicroservices.TestModuleH") +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleH2), "org.cppmicroservices.TestModuleH2") + + +void TestServiceFactoryModuleScope() +{ + + // Install and start test module H, a service factory and test that the methods + // in that interface works. + + SharedLibrary target(LIB_PATH, "TestModuleH"); + +#ifdef US_BUILD_SHARED_LIBS + try + { + target.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what()) + } + + Module* moduleH = ModuleRegistry::GetModule("TestModuleH Module"); + US_TEST_CONDITION_REQUIRED(moduleH != 0, "Test for existing module TestModuleH") + + std::vector registeredRefs = moduleH->GetRegisteredServices(); + US_TEST_CONDITION_REQUIRED(registeredRefs.size() == 2, "# of registered services") + US_TEST_CONDITION(registeredRefs[0].GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_MODULE(), "service scope") + US_TEST_CONDITION(registeredRefs[1].GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_PROTOTYPE(), "service scope") +#endif + + ModuleContext* mc = GetModuleContext(); + // Check that a service reference exist + const ServiceReferenceU sr1 = mc->GetServiceReference("org.cppmicroservices.TestModuleH"); + US_TEST_CONDITION_REQUIRED(sr1, "Service shall be present.") + US_TEST_CONDITION(sr1.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_MODULE(), "service scope") + + InterfaceMap service = mc->GetService(sr1); + US_TEST_CONDITION_REQUIRED(service.size() >= 1, "GetService()") + InterfaceMap::const_iterator serviceIter = service.find("org.cppmicroservices.TestModuleH"); + US_TEST_CONDITION_REQUIRED(serviceIter != service.end(), "GetService()") + US_TEST_CONDITION_REQUIRED(serviceIter->second != NULL, "GetService()") + + InterfaceMap service2 = mc->GetService(sr1); + US_TEST_CONDITION(service == service2, "Same service pointer") + +#ifdef US_BUILD_SHARED_LIBS + std::vector usedRefs = mc->GetModule()->GetServicesInUse(); + US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use") + US_TEST_CONDITION(usedRefs[0] == sr1, "service ref in use") + + InterfaceMap service3 = moduleH->GetModuleContext()->GetService(sr1); + US_TEST_CONDITION(service != service3, "Different service pointer") + US_TEST_CONDITION(moduleH->GetModuleContext()->UngetService(sr1), "UngetService()") +#endif + + US_TEST_CONDITION_REQUIRED(mc->UngetService(sr1), "ungetService()") + + target.Unload(); +} + +void TestServiceFactoryPrototypeScope() +{ + + // Install and start test module H, a service factory and test that the methods + // in that interface works. + + SharedLibrary target(LIB_PATH, "TestModuleH"); + +#ifdef US_BUILD_SHARED_LIBS + try + { + target.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what()) + } + + Module* moduleH = ModuleRegistry::GetModule("TestModuleH Module"); + US_TEST_CONDITION_REQUIRED(moduleH != 0, "Test for existing module TestModuleH") +#endif + + ModuleContext* mc = GetModuleContext(); + // Check that a service reference exist + const ServiceReference sr1 = mc->GetServiceReference(); + US_TEST_CONDITION_REQUIRED(sr1, "Service shall be present.") + US_TEST_CONDITION(sr1.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_PROTOTYPE(), "service scope") + + ServiceObjects svcObjects = mc->GetServiceObjects(sr1); + TestModuleH2* prototypeServiceH2 = svcObjects.GetService(); + + const ServiceReferenceU sr1void = mc->GetServiceReference(us_service_interface_iid()); + ServiceObjects svcObjectsVoid = mc->GetServiceObjects(sr1void); + InterfaceMap prototypeServiceH2Void = svcObjectsVoid.GetService(); + US_TEST_CONDITION_REQUIRED(prototypeServiceH2Void.find(us_service_interface_iid()) != prototypeServiceH2Void.end(), + "ServiceObjects::GetService()") + +#ifdef US_BUILD_SHARED_LIBS + // There should be only one service in use + US_TEST_CONDITION_REQUIRED(mc->GetModule()->GetServicesInUse().size() == 1, "services in use") +#endif + + TestModuleH2* moduleScopeService = mc->GetService(sr1); + US_TEST_CONDITION_REQUIRED(moduleScopeService && moduleScopeService != prototypeServiceH2, "GetService()") + + US_TEST_CONDITION_REQUIRED(prototypeServiceH2 != prototypeServiceH2Void.find(us_service_interface_iid())->second, + "GetService()") + + svcObjectsVoid.UngetService(prototypeServiceH2Void); + + TestModuleH2* moduleScopeService2 = mc->GetService(sr1); + US_TEST_CONDITION(moduleScopeService == moduleScopeService2, "Same service pointer") + +#ifdef US_BUILD_SHARED_LIBS + std::vector usedRefs = mc->GetModule()->GetServicesInUse(); + US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use") + US_TEST_CONDITION(usedRefs[0] == sr1, "service ref in use") +#endif + + std::string filter = "(" + ServiceConstants::SERVICE_ID() + "=" + sr1.GetProperty(ServiceConstants::SERVICE_ID()).ToString() + ")"; + const ServiceReference sr2 = mc->GetServiceReferences(filter).front(); + US_TEST_CONDITION_REQUIRED(sr2, "Service shall be present.") + US_TEST_CONDITION(sr2.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_PROTOTYPE(), "service scope") + US_TEST_CONDITION(any_cast(sr2.GetProperty(ServiceConstants::SERVICE_ID())) == any_cast(sr1.GetProperty(ServiceConstants::SERVICE_ID())), "same service id") + + try + { + svcObjects.UngetService(moduleScopeService2); + US_TEST_FAILED_MSG(<< "std::invalid_argument exception expected") + } + catch (const std::invalid_argument&) + { + // this is expected + } + +#ifdef US_BUILD_SHARED_LIBS + // There should still be only one service in use + usedRefs = mc->GetModule()->GetServicesInUse(); + US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use") +#endif + + ServiceObjects svcObjects2 = svcObjects; + ServiceObjects svcObjects3 = mc->GetServiceObjects(sr1); + try + { + svcObjects3.UngetService(prototypeServiceH2); + US_TEST_FAILED_MSG(<< "std::invalid_argument exception expected") + } + catch (const std::invalid_argument&) + { + // this is expected + } + + svcObjects2.UngetService(prototypeServiceH2); + prototypeServiceH2 = svcObjects2.GetService(); + TestModuleH2* prototypeServiceH2_2 = svcObjects3.GetService(); + + US_TEST_CONDITION_REQUIRED(prototypeServiceH2_2 && prototypeServiceH2_2 != prototypeServiceH2, "prototype service") + + svcObjects2.UngetService(prototypeServiceH2); + svcObjects3.UngetService(prototypeServiceH2_2); + US_TEST_CONDITION_REQUIRED(mc->UngetService(sr1), "ungetService()") + + target.Unload(); +} + +int usServiceFactoryTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ServiceFactoryTest"); + + TestServiceFactoryModuleScope(); + TestServiceFactoryPrototypeScope(); + + US_TEST_END() +} diff --git a/Core/Code/CppMicroServices/test/usServiceListenerTest.cpp b/Core/CppMicroServices/test/usServiceListenerTest.cpp similarity index 86% rename from Core/Code/CppMicroServices/test/usServiceListenerTest.cpp rename to Core/CppMicroServices/test/usServiceListenerTest.cpp index c49d2ca0d9..42c6235d70 100644 --- a/Core/Code/CppMicroServices/test/usServiceListenerTest.cpp +++ b/Core/CppMicroServices/test/usServiceListenerTest.cpp @@ -1,561 +1,567 @@ /*============================================================================= 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 +#include #include -#include "usTestUtilSharedLibrary.h" - US_USE_NAMESPACE +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + class TestServiceListener { private: - friend bool runLoadUnloadTest(const std::string&, int cnt, SharedLibraryHandle&, + friend bool runLoadUnloadTest(const std::string&, int cnt, SharedLibrary&, 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(); + ServiceReferenceU 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); + InterfaceMap 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) + if (service.empty()) { 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) ); + US_TEST_OUTPUT( << "Service (unreg): " << service.begin()->first << " -> " << service.begin()->second ); 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()); + std::vector 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(); + for(std::vector::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) + void printUsingModules(const ServiceReferenceU& 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, +bool runLoadUnloadTest(const std::string& name, int cnt, SharedLibrary& 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"); + SharedLibrary target(LIB_PATH, "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"); + SharedLibrary libA(LIB_PATH, "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"); + SharedLibrary libA2(LIB_PATH, "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"); + SharedLibrary libSL1(LIB_PATH, "TestModuleSL1"); + SharedLibrary libSL3(LIB_PATH, "TestModuleSL3"); + SharedLibrary libSL4(LIB_PATH, "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() ); + US_TEST_OUTPUT( << "Starting libModuleTestSL1: " << libSL1.GetFilePath() ); 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() ); + US_TEST_OUTPUT( << "Starting libModuleTestSL4: " << libSL4.GetFilePath() ); 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() ); + US_TEST_OUTPUT( << "Starting libModuleTestSL3: " << libSL3.GetFilePath() ); 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"); + ServiceReferenceU libSL3SR = mc->GetServiceReference("ActivatorSL3"); + InterfaceMap libSL3Activator = mc->GetService(libSL3SR); + US_TEST_CONDITION_REQUIRED(!libSL3Activator.empty(), "ActivatorSL3 service != 0"); - ModulePropsInterface* propsInterface = dynamic_cast(libSL3Activator); - US_TEST_CONDITION_REQUIRED(propsInterface, "Cast to ModulePropsInterface"); + ServiceReference libSL3PropsI(libSL3SR); + ModulePropsInterface* propsInterface = mc->GetService(libSL3PropsI); + US_TEST_CONDITION_REQUIRED(propsInterface, "ModulePropsInterface != 0"); 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"); + ServiceReferenceU libSL1SR = mc->GetServiceReference("ActivatorSL1"); + InterfaceMap libSL1Activator = mc->GetService(libSL1SR); + US_TEST_CONDITION_REQUIRED(!libSL1Activator.empty(), "ActivatorSL1 service != 0"); - ModulePropsInterface* propsInterface = dynamic_cast(libSL1Activator); + ServiceReference libSL1PropsI(libSL1SR); + ModulePropsInterface* propsInterface = mc->GetService(libSL1PropsI); 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() ); + US_TEST_OUTPUT( << "Stop libSL4: " << libSL4.GetFilePath() ); 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"); + ServiceReferenceU libSL3SR = mc->GetServiceReference("ActivatorSL3"); + InterfaceMap libSL3Activator = mc->GetService(libSL3SR); + US_TEST_CONDITION_REQUIRED(!libSL3Activator.empty(), "ActivatorSL3 service != 0"); - ModulePropsInterface* propsInterface = dynamic_cast(libSL3Activator); + ServiceReference libSL3PropsI(libSL3SR); + ModulePropsInterface* propsInterface = mc->GetService(libSL3PropsI); 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() ); + US_TEST_OUTPUT( << "Stop libSL1:" << libSL1.GetFilePath() ); 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() ); + US_TEST_OUTPUT( << "Stop libSL3:" << libSL3.GetFilePath() ); 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/CppMicroServices/test/usServiceRegistryPerformanceTest.cpp b/Core/CppMicroServices/test/usServiceRegistryPerformanceTest.cpp new file mode 100644 index 0000000000..8de3197608 --- /dev/null +++ b/Core/CppMicroServices/test/usServiceRegistryPerformanceTest.cpp @@ -0,0 +1,424 @@ +/*============================================================================= + + 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 "usTestingMacros.h" + +#include +#include + +US_USE_NAMESPACE + +#ifdef US_PLATFORM_APPLE +#include +#elif defined(US_PLATFORM_POSIX) +#include +#include +#ifndef _POSIX_MONOTONIC_CLOCK +#error Monotonic clock support missing on this POSIX platform +#endif +#elif defined(US_PLATFORM_WINDOWS) +#include +#else +#error High precision timer support nod available on this platform +#endif + +#include + +class HighPrecisionTimer +{ + +public: + + inline HighPrecisionTimer(); + + inline void Start(); + + inline long long ElapsedMilli(); + + inline long long ElapsedMicro(); + +private: + +#ifdef US_PLATFORM_APPLE + static double timeConvert; + uint64_t startTime; +#elif defined(US_PLATFORM_POSIX) + timespec startTime; +#elif defined(US_PLATFORM_WINDOWS) + LARGE_INTEGER timerFrequency; + LARGE_INTEGER startTime; +#endif +}; + +#ifdef US_PLATFORM_APPLE + +double HighPrecisionTimer::timeConvert = 0.0; + +inline HighPrecisionTimer::HighPrecisionTimer() +: startTime(0) +{ + if (timeConvert == 0) + { + mach_timebase_info_data_t timeBase; + mach_timebase_info(&timeBase); + timeConvert = static_cast(timeBase.numer) / static_cast(timeBase.denom) / 1000.0; + } +} + +inline void HighPrecisionTimer::Start() +{ + startTime = mach_absolute_time(); +} + +inline long long HighPrecisionTimer::ElapsedMilli() +{ + uint64_t current = mach_absolute_time(); + return static_cast(current - startTime) * timeConvert / 1000.0; +} + +inline long long HighPrecisionTimer::ElapsedMicro() +{ + uint64_t current = mach_absolute_time(); + return static_cast(current - startTime) * timeConvert; +} + +#elif defined(US_PLATFORM_POSIX) + +inline HighPrecisionTimer::HighPrecisionTimer() +{ + startTime.tv_nsec = 0; + startTime.tv_sec = 0; +} + +inline void HighPrecisionTimer::Start() +{ + clock_gettime(CLOCK_MONOTONIC, &startTime); +} + +inline long long HighPrecisionTimer::ElapsedMilli() +{ + timespec current; + clock_gettime(CLOCK_MONOTONIC, ¤t); + return (static_cast(current.tv_sec)*1000 + current.tv_nsec/1000/1000) - + (static_cast(startTime.tv_sec)*1000 + startTime.tv_nsec/1000/1000); +} + +inline long long HighPrecisionTimer::ElapsedMicro() +{ + timespec current; + clock_gettime(CLOCK_MONOTONIC, ¤t); + return (static_cast(current.tv_sec)*1000*1000 + current.tv_nsec/1000) - + (static_cast(startTime.tv_sec)*1000*1000 + startTime.tv_nsec/1000); +} + +#elif defined(US_PLATFORM_WINDOWS) + +inline HighPrecisionTimer::HighPrecisionTimer() +{ + if (!QueryPerformanceFrequency(&timerFrequency)) + throw std::runtime_error("QueryPerformanceFrequency() failed"); +} + +inline void HighPrecisionTimer::Start() +{ + //DWORD_PTR oldmask = SetThreadAffinityMask(GetCurrentThread(), 0); + QueryPerformanceCounter(&startTime); + //SetThreadAffinityMask(GetCurrentThread(), oldmask); +} + +inline long long HighPrecisionTimer::ElapsedMilli() +{ + LARGE_INTEGER current; + QueryPerformanceCounter(¤t); + return (current.QuadPart - startTime.QuadPart) / (timerFrequency.QuadPart / 1000); +} + +inline long long HighPrecisionTimer::ElapsedMicro() +{ + LARGE_INTEGER current; + QueryPerformanceCounter(¤t); + return (current.QuadPart - startTime.QuadPart) / (timerFrequency.QuadPart / (1000*1000)); +} + +#endif + +class MyServiceListener; + +struct IPerfTestService +{ + virtual ~IPerfTestService() {} +}; + +US_DECLARE_SERVICE_INTERFACE(IPerfTestService, "org.cppmicroservices.test.IPerfTestService") + + +class ServiceRegistryPerformanceTest +{ + +private: + + friend class MyServiceListener; + + ModuleContext* mc; + + int nListeners; + int nServices; + + std::size_t nRegistered; + std::size_t nUnregistering; + std::size_t nModified; + + std::vector > regs; + std::vector listeners; + std::vector services; + +public: + + ServiceRegistryPerformanceTest(ModuleContext* context); + + void InitTestCase(); + void CleanupTestCase(); + + void TestAddListeners(); + void TestRegisterServices(); + + void TestModifyServices(); + void TestUnregisterServices(); + +private: + + std::ostream& Log() const + { + return std::cout; + } + + void AddListeners(int n); + void RegisterServices(int n); + void ModifyServices(); + void UnregisterServices(); + +}; + +class MyServiceListener +{ + +private: + + ServiceRegistryPerformanceTest* ts; + +public: + + MyServiceListener(ServiceRegistryPerformanceTest* ts) + : ts(ts) + { + } + + void ServiceChanged(const ServiceEvent ev) + { + switch(ev.GetType()) + { + case ServiceEvent::REGISTERED: + ts->nRegistered++; + break; + case ServiceEvent::UNREGISTERING: + ts->nUnregistering++; + break; + case ServiceEvent::MODIFIED: + ts->nModified++; + break; + default: + break; + } + } +}; + + +ServiceRegistryPerformanceTest::ServiceRegistryPerformanceTest(ModuleContext* context) + : mc(context) + , nListeners(100) + , nServices(1000) + , nRegistered(0) + , nUnregistering(0) + , nModified(0) +{ +} + +void ServiceRegistryPerformanceTest::InitTestCase() +{ + Log() << "Initialize event counters\n"; + + nRegistered = 0; + nUnregistering = 0; + nModified = 0; +} + +void ServiceRegistryPerformanceTest::CleanupTestCase() +{ + Log() << "Remove all service listeners\n"; + + for(std::size_t i = 0; i < listeners.size(); i++) + { + try + { + MyServiceListener* l = listeners[i]; + mc->RemoveServiceListener(l, &MyServiceListener::ServiceChanged); + delete l; + } + catch (const std::exception& e) + { + Log() << e.what(); + } + } + listeners.clear(); +} + +void ServiceRegistryPerformanceTest::TestAddListeners() +{ + AddListeners(nListeners); +} + +void ServiceRegistryPerformanceTest::AddListeners(int n) +{ + Log() << "adding " << n << " service listeners\n"; + for(int i = 0; i < n; i++) + { + MyServiceListener* l = new MyServiceListener(this); + try + { + listeners.push_back(l); + mc->AddServiceListener(l, &MyServiceListener::ServiceChanged, "(perf.service.value>=0)"); + } + catch (const std::exception& e) + { + Log() << e.what(); + } + } + Log() << "listener count=" << listeners.size() << "\n"; +} + +void ServiceRegistryPerformanceTest::TestRegisterServices() +{ + Log() << "Register services, and check that we get #of services (" + << nServices << ") * #of listeners (" << nListeners << ") REGISTERED events\n"; + + Log() << "registering " << nServices << " services, listener count=" << listeners.size() << "\n"; + + HighPrecisionTimer t; + t.Start(); + RegisterServices(nServices); + long long ms = t.ElapsedMilli(); + Log() << "register took " << ms << "ms\n"; + US_TEST_CONDITION_REQUIRED(nServices * listeners.size() == nRegistered, + "# REGISTERED events must be same as # of registered services * # of listeners"); +} + +void ServiceRegistryPerformanceTest::RegisterServices(int n) +{ + class PerfTestService : public IPerfTestService + { + }; + + std::string pid("my.service."); + + for(int i = 0; i < n; i++) + { + ServiceProperties props; + std::stringstream ss; + ss << pid << i; + props["service.pid"] = ss.str(); + props["perf.service.value"] = i+1; + + PerfTestService* service = new PerfTestService(); + services.push_back(service); + ServiceRegistration reg = + mc->RegisterService(service, props); + regs.push_back(reg); + } +} + +void ServiceRegistryPerformanceTest::TestModifyServices() +{ + Log() << "Modify all services, and check that we get #of services (" + << nServices << ") * #of listeners (" << nListeners << ") MODIFIED events\n"; + + HighPrecisionTimer t; + t.Start(); + ModifyServices(); + long long ms = t.ElapsedMilli(); + Log() << "modify took " << ms << "ms\n"; + US_TEST_CONDITION_REQUIRED(nServices * listeners.size() == nModified, + "# MODIFIED events must be same as # of modified services * # of listeners"); +} + +void ServiceRegistryPerformanceTest::ModifyServices() +{ + Log() << "modifying " << regs.size() << " services, listener count=" << listeners.size() << "\n"; + + for(std::size_t i = 0; i < regs.size(); i++) + { + ServiceRegistration reg = regs[i]; + ServiceProperties props; + props["perf.service.value"] = i * 2; + reg.SetProperties(props); + } +} + +void ServiceRegistryPerformanceTest::TestUnregisterServices() +{ + Log() << "Unregister all services, and check that we get #of services (" + << nServices << ") * #of listeners (" << nListeners + << ") UNREGISTERING events\n"; + + HighPrecisionTimer t; + t.Start(); + UnregisterServices(); + long long ms = t.ElapsedMilli(); + Log() << "unregister took " << ms << "ms\n"; + US_TEST_CONDITION_REQUIRED(nServices * listeners.size() == nUnregistering, "# UNREGISTERING events must be same as # of (un)registered services * # of listeners"); +} + +void ServiceRegistryPerformanceTest::UnregisterServices() +{ + Log() << "unregistering " << regs.size() << " services, listener count=" + << listeners.size() << "\n"; + for(std::size_t i = 0; i < regs.size(); i++) + { + ServiceRegistration reg = regs[i]; + reg.Unregister(); + } + regs.clear(); +} + + +int usServiceRegistryPerformanceTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ServiceRegistryPerformanceTest") + + ServiceRegistryPerformanceTest perfTest(GetModuleContext()); + perfTest.InitTestCase(); + perfTest.TestAddListeners(); + perfTest.TestRegisterServices(); + perfTest.TestModifyServices(); + perfTest.TestUnregisterServices(); + perfTest.CleanupTestCase(); + + US_TEST_END() +} diff --git a/Core/Code/CppMicroServices/test/usServiceRegistryTest.cpp b/Core/CppMicroServices/test/usServiceRegistryTest.cpp similarity index 81% rename from Core/Code/CppMicroServices/test/usServiceRegistryTest.cpp rename to Core/CppMicroServices/test/usServiceRegistryTest.cpp index a2cbdf3507..8943242082 100644 --- a/Core/Code/CppMicroServices/test/usServiceRegistryTest.cpp +++ b/Core/CppMicroServices/test/usServiceRegistryTest.cpp @@ -1,138 +1,138 @@ /*============================================================================= 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 + struct TestServiceA : public ITestServiceA { }; ModuleContext* context = GetModuleContext(); TestServiceA s1; TestServiceA s2; - ServiceRegistration reg1 = context->RegisterService(&s1); - ServiceRegistration reg2 = context->RegisterService(&s2); + ServiceRegistration reg1 = context->RegisterService(&s1); + ServiceRegistration reg2 = context->RegisterService(&s2); - std::list refs = context->GetServiceReferences(); + std::vector > 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") + ServiceReference ref = context->GetServiceReference(); + US_TEST_CONDITION_REQUIRED(!ref, "Testing for invalid service reference") + return EXIT_SUCCESS; } int TestServicePropertiesUpdate() { - struct TestServiceA : public US_BASECLASS_NAME, public ITestServiceA + struct TestServiceA : 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(); + 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); + 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)); + 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/CppMicroServices/test/usServiceTemplateTest.cpp b/Core/CppMicroServices/test/usServiceTemplateTest.cpp new file mode 100644 index 0000000000..783ebfa8d5 --- /dev/null +++ b/Core/CppMicroServices/test/usServiceTemplateTest.cpp @@ -0,0 +1,211 @@ +/*============================================================================= + + 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 "usTestingMacros.h" + +struct Interface1 {}; +US_DECLARE_SERVICE_INTERFACE(Interface1, "org.cppmicroservices.test.Interface1") +struct Interface2 {}; +US_DECLARE_SERVICE_INTERFACE(Interface2, "org.cppmicroservices.test.Interface2") +struct Interface3 {}; +US_DECLARE_SERVICE_INTERFACE(Interface3, "org.cppmicroservices.test.Interface3") + +struct MyService1 : public Interface1 +{}; + +struct MyService2 : public Interface1, public Interface2 +{}; + +struct MyService3 : public Interface1, public Interface2, public Interface3 +{}; + +struct MyFactory1 : public us::ServiceFactory +{ + std::map m_idToServiceMap; + + virtual us::InterfaceMap GetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/) + { + MyService1* s = new MyService1; + m_idToServiceMap.insert(std::make_pair(module->GetModuleId(), s)); + return us::MakeInterfaceMap(s); + } + + virtual void UngetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/, + const us::InterfaceMap& service) + { + std::map::iterator iter = m_idToServiceMap.find(module->GetModuleId()); + if (iter != m_idToServiceMap.end()) + { + US_TEST_CONDITION(static_cast(iter->second) == us::ExtractInterface(service), "Compare service pointer") + delete iter->second; + m_idToServiceMap.erase(iter); + } + } +}; + +struct MyFactory2 : public us::ServiceFactory +{ + std::map m_idToServiceMap; + + virtual us::InterfaceMap GetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/) + { + MyService2* s = new MyService2; + m_idToServiceMap.insert(std::make_pair(module->GetModuleId(), s)); + return us::MakeInterfaceMap(s); + } + + virtual void UngetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/, + const us::InterfaceMap& service) + { + std::map::iterator iter = m_idToServiceMap.find(module->GetModuleId()); + if (iter != m_idToServiceMap.end()) + { + US_TEST_CONDITION(static_cast(iter->second) == us::ExtractInterface(service), "Compare service pointer") + delete iter->second; + m_idToServiceMap.erase(iter); + } + } +}; + +struct MyFactory3 : public us::ServiceFactory +{ + std::map m_idToServiceMap; + + virtual us::InterfaceMap GetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/) + { + MyService3* s = new MyService3; + m_idToServiceMap.insert(std::make_pair(module->GetModuleId(), s)); + return us::MakeInterfaceMap(s); + } + + virtual void UngetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/, + const us::InterfaceMap& service) + { + std::map::iterator iter = m_idToServiceMap.find(module->GetModuleId()); + if (iter != m_idToServiceMap.end()) + { + US_TEST_CONDITION(static_cast(iter->second) == us::ExtractInterface(service), "Compare service pointer") + delete iter->second; + m_idToServiceMap.erase(iter); + } + } +}; + + +US_USE_NAMESPACE + +int usServiceTemplateTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ServiceTemplateTest"); + + ModuleContext* mc = GetModuleContext(); + + // Register compile tests + MyService1 s1; + MyService2 s2; + MyService3 s3; + + us::ServiceRegistration sr1 = mc->RegisterService(&s1); + us::ServiceRegistration sr2 = mc->RegisterService(&s2); + us::ServiceRegistration sr3 = mc->RegisterService(&s3); + + MyFactory1 f1; + us::ServiceRegistration sfr1 = mc->RegisterService(&f1); + + MyFactory2 f2; + us::ServiceRegistration sfr2 = mc->RegisterService(static_cast(&f2)); + + MyFactory3 f3; + us::ServiceRegistration sfr3 = mc->RegisterService(static_cast(&f3)); + +#ifdef US_BUILD_SHARED_LIBS + US_TEST_CONDITION(mc->GetModule()->GetRegisteredServices().size() == 6, "# of reg services") +#endif + + std::vector > s1refs = mc->GetServiceReferences(); + US_TEST_CONDITION(s1refs.size() == 6, "# of interface1 regs") + std::vector > s2refs = mc->GetServiceReferences(); + US_TEST_CONDITION(s2refs.size() == 4, "# of interface2 regs") + std::vector > s3refs = mc->GetServiceReferences(); + US_TEST_CONDITION(s3refs.size() == 2, "# of interface3 regs") + + Interface1* i1 = mc->GetService(sr1.GetReference()); + US_TEST_CONDITION(i1 == static_cast(&s1), "interface1 ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sr1.GetReference()), "unget interface1 ptr") + i1 = mc->GetService(sfr1.GetReference()); + US_TEST_CONDITION(i1 == static_cast(f1.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface1 factory ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr1.GetReference()), "unget interface1 factory ptr") + + i1 = mc->GetService(sr2.GetReference(InterfaceT())); + US_TEST_CONDITION(i1 == static_cast(&s2), "interface1 ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sr2.GetReference(InterfaceT())), "unget interface1 ptr") + i1 = mc->GetService(sfr2.GetReference(InterfaceT())); + US_TEST_CONDITION(i1 == static_cast(f2.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface1 factory ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr2.GetReference(InterfaceT())), "unget interface1 factory ptr") + Interface2* i2 = mc->GetService(sr2.GetReference(InterfaceT())); + US_TEST_CONDITION(i2 == static_cast(&s2), "interface2 ptr") + i2 = NULL; + US_TEST_CONDITION(mc->UngetService(sr2.GetReference(InterfaceT())), "unget interface2 ptr") + i2 = mc->GetService(sfr2.GetReference(InterfaceT())); + US_TEST_CONDITION(i2 == static_cast(f2.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface2 factory ptr") + i2 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr2.GetReference(InterfaceT())), "unget interface2 factory ptr") + + i1 = mc->GetService(sr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i1 == static_cast(&s3), "interface1 ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sr3.GetReference(InterfaceT())), "unget interface1 ptr") + i1 = mc->GetService(sfr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i1 == static_cast(f3.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface1 factory ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr3.GetReference(InterfaceT())), "unget interface1 factory ptr") + i2 = mc->GetService(sr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i2 == static_cast(&s3), "interface2 ptr") + i2 = NULL; + US_TEST_CONDITION(mc->UngetService(sr3.GetReference(InterfaceT())), "unget interface2 ptr") + i2 = mc->GetService(sfr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i2 == static_cast(f3.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface2 factory ptr") + i2 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr3.GetReference(InterfaceT())), "unget interface2 factory ptr") + Interface3* i3 = mc->GetService(sr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i3 == static_cast(&s3), "interface3 ptr") + i3 = NULL; + US_TEST_CONDITION(mc->UngetService(sr3.GetReference(InterfaceT())), "unget interface3 ptr") + i3 = mc->GetService(sfr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i3 == static_cast(f3.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface3 factory ptr") + i3 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr3.GetReference(InterfaceT())), "unget interface3 factory ptr") + + sr1.Unregister(); + sr2.Unregister(); + sr3.Unregister(); + + US_TEST_END() +} diff --git a/Core/Code/CppMicroServices/test/usServiceTrackerTest.cpp b/Core/CppMicroServices/test/usServiceTrackerTest.cpp similarity index 64% rename from Core/Code/CppMicroServices/test/usServiceTrackerTest.cpp rename to Core/CppMicroServices/test/usServiceTrackerTest.cpp index cf1ad82485..d602d4bd02 100644 --- a/Core/Code/CppMicroServices/test/usServiceTrackerTest.cpp +++ b/Core/CppMicroServices/test/usServiceTrackerTest.cpp @@ -1,202 +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. ===================================================================*/ #include #include +#include #include #include #include #include #include - -#include US_BASECLASS_HEADER +#include #include "usServiceControlInterface.h" -#include "usTestUtilSharedLibrary.h" #include US_USE_NAMESPACE +bool CheckConvertibility(const std::vector& refs, + std::vector::const_iterator idBegin, + std::vector::const_iterator idEnd) +{ + std::vector ids; + ids.assign(idBegin, idEnd); + + for (std::vector::const_iterator sri = refs.begin(); + sri != refs.end(); ++sri) + { + for (std::vector::iterator idIter = ids.begin(); + idIter != ids.end(); ++idIter) + { + if (sri->IsConvertibleTo(*idIter)) + { + ids.erase(idIter); + break; + } + } + } + + return ids.empty(); +} + + int usServiceTrackerTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ServiceTrackerTest") +#ifdef US_PLATFORM_WINDOWS + const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + ModuleContext* mc = GetModuleContext(); - SharedLibraryHandle libS("TestModuleS"); + SharedLibrary libS(LIB_PATH, "TestModuleS"); +#ifdef US_BUILD_SHARED_LIBS // 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() ); } +#endif // 1. Create a ServiceTracker with ServiceTrackerCustomizer == null std::string s1("org.cppmicroservices.TestModuleSService"); - ServiceReference servref = mc->GetServiceReference(s1 + "0"); + ServiceReferenceU 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); + ServiceReference servCtrlRef = mc->GetServiceReference(); + US_TEST_CONDITION_REQUIRED(servCtrlRef != 0, "Test if constrol service was registered"); + + ServiceControlInterface* serviceController = mc->GetService(servCtrlRef); US_TEST_CONDITION_REQUIRED(serviceController != 0, "Test valid service controller"); - std::auto_ptr > st1(new ServiceTracker<>(mc, servref)); + 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; + std::vector 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"); + US_TEST_CONDITION_REQUIRED(s1 + "0" == sa2[0].GetInterfaceId(), "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)); + 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 + std::vector ids; + ids.push_back((s1 + "0")); + ids.push_back((s1 + "1")); + ids.push_back((s1 + "2")); + ids.push_back((s1 + "3")); + 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"); - } + US_TEST_CONDITION_REQUIRED(CheckConvertibility(sa2, ids.begin(), ids.begin()+2), "Check for expected interface id [0]"); + US_TEST_CONDITION_REQUIRED(sa2[1].IsConvertibleTo(s1 + "1"), "Check for expected interface id [1]"); // 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"); - } + + US_TEST_CONDITION_REQUIRED(CheckConvertibility(sa2, ids.begin(), ids.begin()+3), "Check for expected interface id [2]"); // 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"); - } + US_TEST_CONDITION_REQUIRED(CheckConvertibility(sa2, ids.begin(), ids.end()), "Check for expected interface id [3]"); // 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(); + ServiceReferenceU 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"); + InterfaceMap o1 = st1->GetService(h1); + US_TEST_CONDITION_REQUIRED(!o1.empty(), "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"); + InterfaceMap o3 = st1->GetService(); + US_TEST_CONDITION_REQUIRED(!o3.empty(), "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"); + InterfaceMap o2 = st1->GetService(h1); + US_TEST_CONDITION_REQUIRED(o2.empty(), "Checkt that service is null"); // 16. Get all service objects this tracker tracks, it should be 2 - std::list ts1; + std::vector 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; + std::vector 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"); - } + US_TEST_CONDITION_REQUIRED(CheckConvertibility(sa3, ids.begin(), ids.begin()+3), "Check for expected interface id [0]"); 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"); + InterfaceMap o9 = st1->WaitForService(50); + US_TEST_CONDITION_REQUIRED(!o9.empty(), "Checking WaitForService method"); US_TEST_END() } diff --git a/Core/CppMicroServices/test/usSharedLibraryTest.cpp b/Core/CppMicroServices/test/usSharedLibraryTest.cpp new file mode 100644 index 0000000000..862ae23479 --- /dev/null +++ b/Core/CppMicroServices/test/usSharedLibraryTest.cpp @@ -0,0 +1,118 @@ +/*============================================================================= + + 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 "usTestingConfig.h" + +#include +#include + +US_USE_NAMESPACE + +int usSharedLibraryTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("SharedLibraryTest"); + +#ifdef US_PLATFORM_WINDOWS + const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; + const std::string LIB_PREFIX = ""; + const std::string LIB_SUFFIX = ".dll"; + const char PATH_SEPARATOR = '\\'; +#elif defined(US_PLATFORM_APPLE) + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; + const std::string LIB_PREFIX = "lib"; + const std::string LIB_SUFFIX = ".dylib"; + const char PATH_SEPARATOR = '/'; +#else + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; + const std::string LIB_PREFIX = "lib"; + const std::string LIB_SUFFIX = ".so"; + const char PATH_SEPARATOR = '/'; + +#endif + + const std::string libAFilePath = LIB_PATH + PATH_SEPARATOR + LIB_PREFIX + "TestModuleA" + LIB_SUFFIX; + SharedLibrary lib1(libAFilePath); + US_TEST_CONDITION(lib1.GetFilePath() == libAFilePath, "Absolute file path") + US_TEST_CONDITION(lib1.GetLibraryPath() == LIB_PATH, "Library path") + US_TEST_CONDITION(lib1.GetName() == "TestModuleA", "Name") + US_TEST_CONDITION(lib1.GetPrefix() == LIB_PREFIX, "Prefix") + US_TEST_CONDITION(lib1.GetSuffix() == LIB_SUFFIX, "Suffix") + lib1.SetName("bla"); + US_TEST_CONDITION(lib1.GetName() == "TestModuleA", "Name after SetName()") + lib1.SetLibraryPath("bla"); + US_TEST_CONDITION(lib1.GetLibraryPath() == LIB_PATH, "Library path after SetLibraryPath()") + lib1.SetPrefix("bla"); + US_TEST_CONDITION(lib1.GetPrefix() == LIB_PREFIX, "Prefix after SetPrefix()") + lib1.SetSuffix("bla"); + US_TEST_CONDITION(lib1.GetSuffix() == LIB_SUFFIX, "Suffix after SetSuffix()") + US_TEST_CONDITION(lib1.GetFilePath() == libAFilePath, "File path after setters") + + lib1.SetFilePath("bla"); + US_TEST_CONDITION(lib1.GetFilePath() == "bla", "Invalid file path") + US_TEST_CONDITION(lib1.GetLibraryPath().empty(), "Empty lib path") + US_TEST_CONDITION(lib1.GetName() == "bla", "Invalid file name") + US_TEST_CONDITION(lib1.GetPrefix() == LIB_PREFIX, "Invalid prefix") + US_TEST_CONDITION(lib1.GetSuffix() == LIB_SUFFIX, "Invalid suffix") + + US_TEST_FOR_EXCEPTION(std::runtime_error, lib1.Load()) + US_TEST_CONDITION(lib1.IsLoaded() == false, "Is loaded") + US_TEST_CONDITION(lib1.GetHandle() == NULL, "Handle") + + lib1.SetFilePath(libAFilePath); + lib1.Load(); + US_TEST_CONDITION(lib1.IsLoaded() == true, "Is loaded") + US_TEST_CONDITION(lib1.GetHandle() != NULL, "Handle") + US_TEST_FOR_EXCEPTION(std::logic_error, lib1.Load()) + + lib1.SetFilePath("bla"); + US_TEST_CONDITION(lib1.GetFilePath() == libAFilePath, "File path") + lib1.Unload(); + + + SharedLibrary lib2(LIB_PATH, "TestModuleA"); + US_TEST_CONDITION(lib2.GetFilePath() == libAFilePath, "File path") + lib2.SetPrefix(""); + US_TEST_CONDITION(lib2.GetPrefix().empty(), "Lib prefix") + US_TEST_CONDITION(lib2.GetFilePath() == LIB_PATH + PATH_SEPARATOR + "TestModuleA" + LIB_SUFFIX, "File path") + + SharedLibrary lib3 = lib2; + US_TEST_CONDITION(lib3.GetFilePath() == lib2.GetFilePath(), "Compare file path") + lib3.SetPrefix(LIB_PREFIX); + US_TEST_CONDITION(lib3.GetFilePath() == libAFilePath, "Compare file path") + lib3.Load(); + US_TEST_CONDITION(lib3.IsLoaded(), "lib3 loaded") + US_TEST_CONDITION(!lib2.IsLoaded(), "lib2 not loaded") + lib1 = lib3; + US_TEST_FOR_EXCEPTION(std::logic_error, lib1.Load()) + lib2.SetPrefix(LIB_PREFIX); + lib2.Load(); + + lib3.Unload(); + US_TEST_CONDITION(!lib3.IsLoaded(), "lib3 unloaded") + US_TEST_CONDITION(!lib1.IsLoaded(), "lib3 unloaded") + lib2.Unload(); + lib1.Unload(); + + US_TEST_END() +} diff --git a/Core/Code/CppMicroServices/test/usStaticModuleResourceTest.cpp b/Core/CppMicroServices/test/usStaticModuleResourceTest.cpp similarity index 95% rename from Core/Code/CppMicroServices/test/usStaticModuleResourceTest.cpp rename to Core/CppMicroServices/test/usStaticModuleResourceTest.cpp index 2405f4572a..fd068d07c4 100644 --- a/Core/Code/CppMicroServices/test/usStaticModuleResourceTest.cpp +++ b/Core/CppMicroServices/test/usStaticModuleResourceTest.cpp @@ -1,151 +1,157 @@ /*============================================================================= 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 - -#include "usTestUtilSharedLibrary.h" #include "usTestingMacros.h" +#include "usTestingConfig.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"); + +#ifdef US_PLATFORM_WINDOWS + const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + + SharedLibrary libB(LIB_PATH, "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/CppMicroServices/test/usStaticModuleTest.cpp similarity index 85% rename from Core/Code/CppMicroServices/test/usStaticModuleTest.cpp rename to Core/CppMicroServices/test/usStaticModuleTest.cpp index 4baec3fedb..d158c6a742 100644 --- a/Core/Code/CppMicroServices/test/usStaticModuleTest.cpp +++ b/Core/CppMicroServices/test/usStaticModuleTest.cpp @@ -1,187 +1,195 @@ /*============================================================================= 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 -#include US_BASECLASS_HEADER - -#include "usTestUtilSharedLibrary.h" #include "usTestUtilModuleListener.h" #include "usTestingMacros.h" +#include "usTestingConfig.h" US_USE_NAMESPACE namespace { +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif // 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) +void frame020a(ModuleContext* mc, TestModuleListener& listener, +#ifdef US_BUILD_SHARED_LIBS + SharedLibrary& 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") +#else + SharedLibrary& /*libB*/) +{ #endif // Check if libB registered the expected service try { - std::list refs = mc->GetServiceReferences("org.cppmicroservices.TestModuleBService"); + std::vector 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"); + InterfaceMap o1 = mc->GetService(refs.front()); + US_TEST_CONDITION(!o1.empty(), "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"); + InterfaceMap o2 = mc->GetService(refs.back()); + US_TEST_CONDITION(!o2.empty(), "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) +void frame030b(ModuleContext* mc, TestModuleListener& listener, SharedLibrary& 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 + std::vector 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); + TestModuleListener listener; 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"); + SharedLibrary libB(LIB_PATH, "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/CppMicroServices/test/usTestManager.cpp similarity index 88% rename from Core/Code/CppMicroServices/test/usTestManager.cpp rename to Core/CppMicroServices/test/usTestManager.cpp index 4d0a2a29a0..100d5b5997 100644 --- a/Core/Code/CppMicroServices/test/usTestManager.cpp +++ b/Core/CppMicroServices/test/usTestManager.cpp @@ -1,78 +1,82 @@ /*============================================================================= 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_RESOURCES(CppMicroServices) US_IMPORT_MODULE(TestModuleA) US_IMPORT_MODULE(TestModuleA2) US_IMPORT_MODULE(TestModuleB) US_IMPORT_MODULE_RESOURCES(TestModuleB) +US_IMPORT_MODULE(TestModuleH) +US_IMPORT_MODULE(TestModuleM) +US_IMPORT_MODULE_RESOURCES(TestModuleM) 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 + TestModuleA TestModuleA2 TestModuleB TestModuleImportedByB TestModuleH TestModuleM + TestModuleR TestModuleS TestModuleSL1 TestModuleSL3 TestModuleSL4 ) #endif diff --git a/Core/Code/CppMicroServices/test/usTestManager.h b/Core/CppMicroServices/test/usTestManager.h similarity index 100% rename from Core/Code/CppMicroServices/test/usTestManager.h rename to Core/CppMicroServices/test/usTestManager.h diff --git a/Core/Code/CppMicroServices/test/usTestResource.txt b/Core/CppMicroServices/test/usTestResource.txt similarity index 100% rename from Core/Code/CppMicroServices/test/usTestResource.txt rename to Core/CppMicroServices/test/usTestResource.txt diff --git a/Core/Code/CppMicroServices/test/usTestUtilModuleListener.cpp b/Core/CppMicroServices/test/usTestUtilModuleListener.cpp similarity index 96% rename from Core/Code/CppMicroServices/test/usTestUtilModuleListener.cpp rename to Core/CppMicroServices/test/usTestUtilModuleListener.cpp index 2983b0e750..9098708462 100644 --- a/Core/Code/CppMicroServices/test/usTestUtilModuleListener.cpp +++ b/Core/CppMicroServices/test/usTestUtilModuleListener.cpp @@ -1,160 +1,160 @@ /*============================================================================= 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() +TestModuleListener::TestModuleListener() + : 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) + Module* moduleX, ServiceReferenceU* 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/CppMicroServices/test/usTestUtilModuleListener.h similarity index 93% rename from Core/Code/CppMicroServices/test/usTestUtilModuleListener.h rename to Core/CppMicroServices/test/usTestUtilModuleListener.h index eadf26a530..825d5a1d68 100644 --- a/Core/Code/CppMicroServices/test/usTestUtilModuleListener.h +++ b/Core/CppMicroServices/test/usTestUtilModuleListener.h @@ -1,70 +1,68 @@ /*============================================================================= 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); + TestModuleListener(); 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); + Module* moduleX, ServiceReferenceU* 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/usTestingConfig.h.in b/Core/CppMicroServices/test/usTestingConfig.h.in similarity index 100% rename from Core/Code/CppMicroServices/test/usTestingConfig.h.in rename to Core/CppMicroServices/test/usTestingConfig.h.in diff --git a/Core/Code/CppMicroServices/test/usTestingMacros.h b/Core/CppMicroServices/test/usTestingMacros.h similarity index 97% rename from Core/Code/CppMicroServices/test/usTestingMacros.h rename to Core/CppMicroServices/test/usTestingMacros.h index 4dce9000f8..0b85d3769d 100644 --- a/Core/Code/CppMicroServices/test/usTestingMacros.h +++ b/Core/CppMicroServices/test/usTestingMacros.h @@ -1,133 +1,132 @@ /*============================================================================= 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) { \ + } catch (const US_PREPEND_NAMESPACE(TestFailedException)&) { \ 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()) \ + } catch (const std::exception& ex) { \ + US_TEST_OUTPUT(<< "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/CppMicroServices/tools/CMakeLists.txt similarity index 67% rename from Core/Code/CppMicroServices/tools/CMakeLists.txt rename to Core/CppMicroServices/tools/CMakeLists.txt index 066a9f5207..336f1d20ee 100644 --- a/Core/Code/CppMicroServices/tools/CMakeLists.txt +++ b/Core/CppMicroServices/tools/CMakeLists.txt @@ -1,14 +1,19 @@ 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() + +install(TARGETS ${US_RCC_EXECUTABLE_NAME} + EXPORT ${PROJECT_NAME}Targets + FRAMEWORK DESTINATION . COMPONENT sdk + RUNTIME DESTINATION bin COMPONENT sdk) diff --git a/Core/Code/CppMicroServices/tools/miniz.c b/Core/CppMicroServices/tools/miniz.c similarity index 100% rename from Core/Code/CppMicroServices/tools/miniz.c rename to Core/CppMicroServices/tools/miniz.c diff --git a/Core/Code/CppMicroServices/tools/usResourceCompiler.cpp b/Core/CppMicroServices/tools/usResourceCompiler.cpp similarity index 100% rename from Core/Code/CppMicroServices/tools/usResourceCompiler.cpp rename to Core/CppMicroServices/tools/usResourceCompiler.cpp diff --git a/Core/Code/CppMicroServices/tools/usResourceCompressor.c b/Core/CppMicroServices/tools/usResourceCompressor.c similarity index 100% rename from Core/Code/CppMicroServices/tools/usResourceCompressor.c rename to Core/CppMicroServices/tools/usResourceCompressor.c diff --git a/Core/Code/CppMicroServices/usConfig.h.in b/Core/CppMicroServices/usConfig.h.in similarity index 90% rename from Core/Code/CppMicroServices/usConfig.h.in rename to Core/CppMicroServices/usConfig.h.in index 9489a2ccc3..c855c1047d 100644 --- a/Core/Code/CppMicroServices/usConfig.h.in +++ b/Core/CppMicroServices/usConfig.h.in @@ -1,252 +1,237 @@ /* 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 +#cmakedefine US_GCC_RTTI_WORKAROUND_NEEDED ///------------------------------------------------------------------- // 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 + #define US_ABI_EXPORT __attribute__ ((visibility ("default"))) + #define US_ABI_IMPORT __attribute__ ((visibility ("default"))) + #define US_ABI_LOCAL __attribute__ ((visibility ("hidden"))) #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 + // 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 #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/Documentation/doxygen.conf.in b/Documentation/doxygen.conf.in index 7347fa1b56..682a77f6d0 100644 --- a/Documentation/doxygen.conf.in +++ b/Documentation/doxygen.conf.in @@ -1,1921 +1,1928 @@ # Doxyfile 1.8.0 # 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 = MITK # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = @MITK_VERSION_STRING@ # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer # a quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = "Medical Imaging Interaction Toolkit" # With the PROJECT_LOGO tag one can specify 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 = @MITK_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 = 8 # 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" \ "BlueBerry=\if BLUEBERRY" \ "endBlueBerry=\endif" \ "bundlemainpage{1}=\page \1" \ "embmainpage{1}=\page \1" \ "github{2}=\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 e2b32c734f..76b96b945d 100644 --- a/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.cpp +++ b/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.cpp @@ -1,122 +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. ===================================================================*/ //#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 +}