diff --git a/Core/Code/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake b/Core/Code/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake index 9211f29df9..9c01709653 100644 --- a/Core/Code/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake +++ b/Core/Code/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake @@ -1,47 +1,47 @@ # # 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: -# MITKFunctionCheckCompilerFlags(FLAGS_TO_CHECK VALID_FLAGS_VAR) +# 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() # 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, ctkFunctionCheckCompilerFlags 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(${CXX_FLAG_TO_TEST} 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/usFunctionCreateTestModule.cmake b/Core/Code/CppMicroServices/CMake/usFunctionCreateTestModule.cmake index e67d034c75..babbf6afa0 100644 --- a/Core/Code/CppMicroServices/CMake/usFunctionCreateTestModule.cmake +++ b/Core/Code/CppMicroServices/CMake/usFunctionCreateTestModule.cmake @@ -1,15 +1,15 @@ function(usFunctionCreateTestModule name) set(_srcs ${ARGN}) - usFunctionGenerateModuleInit(_srcs NAME ${name}) + usFunctionGenerateModuleInit(_srcs NAME "${name} Module" LIBRARY_NAME ${name}) add_library(${name} ${_srcs}) target_link_libraries(${name} ${US_LINK_LIBRARIES}) if(NOT US_ENABLE_SERVICE_FACTORY_SUPPORT) target_link_libraries(${name} ${US_BASECLASS_LIBRARIES}) endif() set(_us_test_module_libs "${_us_test_module_libs};${name}" CACHE INTERNAL "" FORCE) endfunction() diff --git a/Core/Code/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake b/Core/Code/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake index 55c4d98b9f..87a4ca4733 100644 --- a/Core/Code/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake +++ b/Core/Code/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake @@ -1,26 +1,71 @@ +#! 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 DEPENDS (optional) A string containing module dependencies. +#! \param VERSION (optional) A version string for the module. +#! function(usFunctionGenerateModuleInit src_var) MACRO_PARSE_ARGUMENTS(US_MODULE "NAME;LIBRARY_NAME;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() + # 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() -set(module_init_src_file "${CMAKE_CURRENT_BINARY_DIR}/${US_MODULE_NAME}_init.cpp") +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 index 738a93160a..cb6bf187bb 100644 --- a/Core/Code/CppMicroServices/CMake/usModuleInit.cpp +++ b/Core/Code/CppMicroServices/CMake/usModuleInit.cpp @@ -1,84 +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 - -#include -#include -#include -#include -#include - -US_BEGIN_NAMESPACE - -US_GLOBAL_STATIC_WITH_ARGS(ModuleInfo, moduleInfo, ("@US_MODULE_NAME@", "@US_MODULE_LIBRARY_NAME@", "@US_MODULE_DEPENDS_STR@", "@US_MODULE_VERSION@")) - -class US_ABI_LOCAL ModuleInitializer { - -public: - - ModuleInitializer() - { - std::string location = ModuleUtils::GetLibraryPath(moduleInfo()->libName, reinterpret_cast(moduleInfo)); - std::string activator_func = "_us_module_activator_instance_"; - activator_func.append(moduleInfo()->name); - - moduleInfo()->location = location; - - if (moduleInfo()->libName.empty()) - { - // make sure we retrieve symbols from the executable, if "libName" is empty - location.clear(); - } - moduleInfo()->activatorHook = reinterpret_cast(ModuleUtils::GetSymbol(location, activator_func.c_str())); - - Register(); - } - - static void Register() - { - ModuleRegistry::Register(moduleInfo()); - } - - ~ModuleInitializer() - { - ModuleRegistry::UnRegister(moduleInfo()); - } - -}; - -US_ABI_LOCAL ModuleContext* GetModuleContext() -{ - // make sure the module is registered - if (moduleInfo()->id == 0) - { - ModuleInitializer::Register(); - } - - return ModuleRegistry::GetModule(moduleInfo()->id)->GetModuleContext(); -} - -US_END_NAMESPACE - -static US_PREPEND_NAMESPACE(ModuleInitializer) coreModule; - - +#include +US_INITIALIZE_MODULE("@US_MODULE_NAME@", "@US_MODULE_LIBRARY_NAME@", "@US_MODULE_DEPENDS_STR@", "@US_MODULE_VERSION@") diff --git a/Core/Code/CppMicroServices/CMakeLists.txt b/Core/Code/CppMicroServices/CMakeLists.txt index 365af4f0b3..9fa225c51f 100644 --- a/Core/Code/CppMicroServices/CMakeLists.txt +++ b/Core/Code/CppMicroServices/CMakeLists.txt @@ -1,316 +1,322 @@ project(CppMicroServices) +set(${PROJECT_NAME}_MAJOR_VERSION 0) +set(${PROJECT_NAME}_MINOR_VERSION 99) +set(${PROJECT_NAME}_PATCH_VERSION 0) +set(${PROJECT_NAME}_VERSION ${${PROJECT_NAME}_MAJOR_VERSION}.${${PROJECT_NAME}_MINOR_VERSION}.${${PROJECT_NAME}_PATCH_VERSION}) + cmake_minimum_required(VERSION 2.8) #----------------------------------------------------------------------------- # Update CMake module path #------------------------------------------------------------------------------ set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/CMake ${CMAKE_MODULE_PATH} ) #----------------------------------------------------------------------------- # CMake function(s) and macro(s) #----------------------------------------------------------------------------- include(MacroParseArguments) include(CheckCXXSourceCompiles) include(usFunctionCheckCompilerFlags) include(usFunctionGetGccVersion) include(usFunctionGenerateModuleInit) #----------------------------------------------------------------------------- # Init output directories #----------------------------------------------------------------------------- set(US_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") set(US_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") set(US_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") foreach(_type ARCHIVE LIBRARY RUNTIME) if(NOT CMAKE_${_type}_OUTPUT_DIRECTORY) set(CMAKE_${_type}_OUTPUT_DIRECTORY ${US_${_type}_OUTPUT_DIRECTORY}) endif() endforeach() #----------------------------------------------------------------------------- # Set a default build type if none was specified #----------------------------------------------------------------------------- if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message(STATUS "Setting build type to 'Debug' as none was specified.") set(CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build." FORCE) # Set the possible values of build type for cmake-gui set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif() #----------------------------------------------------------------------------- # CMake options #----------------------------------------------------------------------------- function(us_cache_var _var_name _var_default _var_type _var_help) set(_advanced 0) set(_force) foreach(_argn ${ARGN}) if(_argn STREQUAL ADVANCED) set(_advanced 1) elseif(_argn STREQUAL FORCE) set(_force FORCE) endif() endforeach() if(US_IS_EMBEDDED) if(NOT DEFINED ${_var_name} OR _force) set(${_var_name} ${_var_default} PARENT_SCOPE) endif() else() set(${_var_name} ${_var_default} CACHE ${_var_type} "${_var_help}" ${_force}) if(_advanced) mark_as_advanced(${_var_name}) endif() endif() endfunction() # Determine if we are being build inside a larger project if(NOT DEFINED US_IS_EMBEDDED) if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) set(US_IS_EMBEDDED 0) else() set(US_IS_EMBEDDED 1) set(CppMicroServices_EXPORTS 1) endif() endif() us_cache_var(US_ENABLE_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_BUILD_SHARED_LIBS ON BOOL "Build shared libraries") us_cache_var(US_BUILD_TESTING OFF BOOL "Build tests") if(MSVC10) # Visual Studio 2010 has 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) + 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) + 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) + us_cache_var(US_BASECLASS_LIBRARIES "${${US_BASECLASS_PACKAGE}_${_suffix}}" STRING "${bc_lib_doc}" FORCE) break() endif() endforeach() if(NOT US_BASECLASS_NAME) message(FATAL_ERROR "US_BASECLASS_NAME not set") elseif(NOT US_BASECLASS_HEADER) message(FATAL_ERROR "US_BASECLASS_HEADER not set") endif() endif() if(US_ENABLE_SERVICE_FACTORY_SUPPORT AND US_BASECLASS_NAME AND NOT US_BASECLASS_HEADER) message(FATAL_ERROR "US_ENABLE_SERVICE_FACTORY_SUPPORT requires a US_BASECLASS_HEADER value") endif() endif() set(_us_baseclass_default 0) if(NOT US_BASECLASS_NAME) message(WARNING "Using build in base class \"::${US_NAMESPACE}::Base\"") set(_us_baseclass_default 1) set(US_BASECLASS_NAME "${US_NAMESPACE}::Base") set(US_BASECLASS_HEADER "usBase.h") endif() if(US_BUILD_TESTING AND US_BASECLASS_NAME AND NOT US_BASECLASS_HEADER) message(FATAL_ERROR "US_BUILD_TESTING requires a US_BASECLASS_HEADER value") endif() set(US_BASECLASS_INCLUDE "#include <${US_BASECLASS_HEADER}>") string(REPLACE "::" ";" _bc_token "${US_BASECLASS_NAME}") list(GET _bc_token -1 _bc_name) list(REMOVE_AT _bc_token -1) set(US_BASECLASS_FORWARD_DECLARATION "") foreach(_namespace_tok ${_bc_token}) if(_namespace_tok) set(US_BASECLASS_FORWARD_DECLARATION "${US_BASECLASS_FORWARD_DECLARATION}namespace ${_namespace_tok} { ") endif() endforeach() set(US_BASECLASS_FORWARD_DECLARATION "${US_BASECLASS_FORWARD_DECLARATION}class ${_bc_name}; ") foreach(_namespace_tok ${_bc_token}) if(_namespace_tok) set(US_BASECLASS_FORWARD_DECLARATION "${US_BASECLASS_FORWARD_DECLARATION}}") endif() endforeach() #----------------------------------------------------------------------------- # US C/CXX Flags #----------------------------------------------------------------------------- set(US_C_FLAGS "${COVERAGE_C_FLAGS} ${ADDITIONAL_C_FLAGS}") set(US_CXX_FLAGS "${COVERAGE_CXX_FLAGS} ${ADDITIONAL_CXX_FLAGS}") # This is used as a preprocessor define set(US_USE_CXX11 ${US_USE_C++11}) if(CMAKE_COMPILER_IS_GNUCXX) set(cflags "-Wall -Wextra -Wpointer-arith -Winvalid-pch -Wcast-align -Wwrite-strings -D_FORTIFY_SOURCE=2") usFunctionCheckCompilerFlags("-fdiagnostics-show-option" cflags) usFunctionCheckCompilerFlags("-Wl,--no-undefined" cflags) if(US_USE_C++11) usFunctionCheckCompilerFlags("-std=c++0x" US_CXX_FLAGS) endif() usFunctionGetGccVersion(${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")) usFunctionCheckCompilerFlags("-fstack-protector-all" cflags) endif() if(MINGW) # suppress warnings about auto imported symbols set(US_CXX_FLAGS "-Wl,--enable-auto-import ${US_CXX_FLAGS}") # we need to define a Windows version set(US_CXX_FLAGS "-D_WIN32_WINNT=0x0500 ${US_CXX_FLAGS}") else() # Enable visibility support if(NOT ${GCC_VERSION} VERSION_LESS "4.5") usFunctionCheckCompilerFlags("-fvisibility=hidden -fvisibility-inlines-hidden" US_CXX_FLAGS) endif() endif() set(US_C_FLAGS "${cflags} ${US_C_FLAGS}") set(US_CXX_FLAGS "${cflags} -Woverloaded-virtual -Wold-style-cast -Wstrict-null-sentinel -Wsign-promo ${US_CXX_FLAGS}") elseif(MSVC90 OR MSVC10) set(US_CXX_FLAGS "/MP ${US_CXX_FLAGS}") endif() if(NOT US_IS_EMBEDDED) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${US_CXX_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${US_C_FLAGS}") endif() #----------------------------------------------------------------------------- # US 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}) + list(APPEND US_INTERNAL_INCLUDE_DIRS ${US_BASECLASS_INCLUDE_DIRS}) endif() # link libraries for third party libs if(US_IS_EMBEDDED) set(US_LINK_LIBRARIES ${US_EMBEDDING_LIBRARY}) else() set(US_LINK_LIBRARIES ${PROJECT_NAME}) endif() # link libraries for the CppMicroServices lib set(_link_libraries ) if(UNIX) list(APPEND _link_libraries dl) endif() list(APPEND US_LINK_LIBRARIES ${_link_libraries}) if(US_ENABLE_SERVICE_FACTORY_SUPPORT) list(APPEND US_LINK_LIBRARIES ${US_BASECLASS_LIBRARIES}) endif() set(US_LINK_DIRS ) if(US_ENABLE_SERVICE_FACTORY_SUPPORT) list(APPEND US_LINK_DIRS ${US_BASECLASS_LIBRARY_DIRS}) endif() #----------------------------------------------------------------------------- # Source directory #----------------------------------------------------------------------------- +set(us_config_h_file "${PROJECT_BINARY_DIR}/include/usConfig.h") +configure_file(usConfig.h.in ${us_config_h_file}) + add_subdirectory(src) #----------------------------------------------------------------------------- # US testing #----------------------------------------------------------------------------- if(US_BUILD_TESTING) enable_testing() add_subdirectory(test) endif() #----------------------------------------------------------------------------- # Documentation #----------------------------------------------------------------------------- add_subdirectory(documentation) #----------------------------------------------------------------------------- # Last configuration steps #----------------------------------------------------------------------------- -configure_file(usConfig.h.in ${PROJECT_BINARY_DIR}/include/usConfig.h) - configure_file(${PROJECT_NAME}Config.cmake.in ${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake @ONLY) diff --git a/Core/Code/CppMicroServices/README.md b/Core/Code/CppMicroServices/README.md new file mode 100644 index 0000000000..dd47f2e310 --- /dev/null +++ b/Core/Code/CppMicroServices/README.md @@ -0,0 +1,81 @@ +C++ Micro Services +================== + +Introduction +------------ + +The C++ Micro Services library provides a dynamic service registry based on the +service layer as specified in the OSGi R4.2 specifications. It enables users to +realize a service oriented approach within their software stack. + +The advantages include higher reuse of components, looser coupling, better organization of +responsibilities, cleaner API contracts, etc. + +Requirements +------------ + +This is a pure C++ implementation of the OSGi service model and does not have any third-party +library dependencies. + +Supported Platforms +------------------- + +The library should compile on many different platforms. Below is a list of tested compiler/OS combinations: + + - GCC 4.5 (Ubuntu 11.04 and MacOS X 10.6) + - Visual Studio 2008 and 2010 + - Clang 3.0 (Ubuntu 11.04 and MacOS X 10.6) + +Quick Start +----------- + +Essentially, the C++ Micro Services library provides you with a powerful dynamic service registry. +Each shared or static library has an associated `ModuleContext` object, through which the service +registry is accessed. + +To query the registry for a service object implementing one or more specific interfaces, the code +would look like this: + +```cpp +#include +#include + +using namespace us; + +void UseService(ModuleContext* context) +{ + ServiceReference serviceRef = context->GetServiceReference(); + if (serviceRef) + { + SomeInterface* service = context->GetService(serviceRef); + if (service) { /* do something */ } + } +} +``` + +Registering a service object against a certain interface looks like this: + +```cpp +#include +#include + +using namespace us; + +void RegisterSomeService(ModuleContext* context, SomeInterface* service) +{ + context->RegisterService(service); +} +``` + +The OSGi service model additionally allows to annotate services with properties and using these +properties during service look-ups. It also allows to track the life-cycle of service objects. +Please see the [Documentation](http://cppmicroservices.org/doc_latest/index.html) for more +examples and tutorials and the API reference. There is also a blog post about +[OSGi Lite for C++](http://blog.cppmicroservices.org/2012/04/15/osgi-lite-for-c++). + +Build Instructions +------------------ + +Please visit the [Build Instructions][bi_master] page online. + +[bi_master]: http://cppmicroservices.org/doc_latest/BuildInstructions.html diff --git a/Core/Code/CppMicroServices/documentation/CMakeLists.txt b/Core/Code/CppMicroServices/documentation/CMakeLists.txt index cde8b91f7c..8ce17b7663 100644 --- a/Core/Code/CppMicroServices/documentation/CMakeLists.txt +++ b/Core/Code/CppMicroServices/documentation/CMakeLists.txt @@ -1,37 +1,65 @@ if(US_BUILD_TESTING) include(usFunctionCompileSnippets) # Compile source code snippets add_subdirectory(snippets) endif() if(NOT US_IS_EMBEDDED) find_package(Doxygen) if(DOXYGEN_FOUND) + + option(US_DOCUMENTATION_FOR_WEBPAGE "Build Doxygen documentation for the webpage" OFF) + set(US_DOXYGEN_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR} CACHE PATH "Doxygen output directory") + mark_as_advanced(US_DOCUMENTATION_FOR_WEBPAGE US_DOXYGEN_OUTPUT_DIR) set(US_HAVE_DOT "NO") if(DOXYGEN_DOT_EXECUTABLE) set(US_HAVE_DOT "YES") endif() if(NOT DEFINED US_DOXYGEN_DOT_NUM_THREADS) set(US_DOXYGEN_DOT_NUM_THREADS 4) endif() - if(US_IS_EMBEDDED) - set(US_DOXYGEN_MAIN_PAGE_CMD "\\page \\1") + # We are in standalone mode, so we generate a "mainpage" + set(US_DOXYGEN_MAIN_PAGE_CMD "\\mainpage") + set(US_DOXYGEN_ENABLED_SECTIONS "us_standalone") + + if(US_DOCUMENTATION_FOR_WEBPAGE) + configure_file(doxygen/header.html + ${CMAKE_CURRENT_BINARY_DIR}/header.html COPY_ONLY) + set(US_DOXYGEN_HEADER header.html) + + configure_file(doxygen/footer.html + ${CMAKE_CURRENT_BINARY_DIR}/footer.html COPY_ONLY) + set(US_DOXYGEN_FOOTER footer.html) + + configure_file(doxygen/doxygen.css + ${CMAKE_CURRENT_BINARY_DIR}/doxygen.css COPY_ONLY) + set(US_DOXYGEN_CSS doxygen.css) + + set(US_DOXYGEN_OUTPUT_DIR ${PROJECT_SOURCE_DIR}/gh-pages) + if(${PROJECT_NAME}_MINOR_VERSION EQUAL 99) + set(US_DOXYGEN_HTML_OUTPUT "doc_latest") + else() + set(US_DOXYGEN_HTML_OUTPUT "doc_${${PROJECT_NAME}_MAJOR_VERSION}_${${PROJECT_NAME}_MINOR_VERSION}") + endif() else() - set(US_DOXYGEN_MAIN_PAGE_CMD "\\mainpage") + set(US_DOXYGEN_HEADER ) + set(US_DOXYGEN_FOOTER ) + set(US_DOXYGEN_CSS ) + set(US_DOXYGEN_HTML_OUTPUT "html") endif() - + configure_file(doxygen.conf.in ${CMAKE_CURRENT_BINARY_DIR}/doxygen.conf) add_custom_target(doc ${DOXYGEN} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.conf WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} ) endif() endif() diff --git a/Core/Code/CppMicroServices/documentation/doxygen.conf.in b/Core/Code/CppMicroServices/documentation/doxygen.conf.in index 11c18184e0..e248754c37 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen.conf.in +++ b/Core/Code/CppMicroServices/documentation/doxygen.conf.in @@ -1,1765 +1,1804 @@ -# Doxyfile 1.7.5.1 +# Doxyfile 1.8.0-20120408 # 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 = 0.99 +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 = @PROJECT_BINARY_DIR@/documentation +OUTPUT_DIRECTORY = @US_DOXYGEN_OUTPUT_DIR@ # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, # Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English # messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, # Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, # Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful if your file system # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 2 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = "FIXME=\par Fix Me's:\n" \ - "embmainpage{1}=@US_DOXYGEN_MAIN_PAGE_CMD@" + "embmainpage{1}=@US_DOXYGEN_MAIN_PAGE_CMD@" \ + "standalone=\if us_standalone" \ + "endstandalone=\endif" + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding +# "class=itcl::class" will allow you to use the command class in the +# itcl::class meaning. + +TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given extension. # Doxygen has a built-in mapping, but you can override or extend it using this # tag. The format is ext=language, where ext is a file extension, and language # is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, # C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make # doxygen treat .inc files as Fortran files (default is PHP), and .f files as C # (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions # you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. EXTENSION_MAPPING = +# If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all +# comments according to the Markdown format, which allows for more readable +# documentation. See http://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you +# can mix doxygen, HTML, and XML commands with Markdown formatting. +# Disable only in case of backward compatibilities issues. + +MARKDOWN_SUPPORT = YES + # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also makes the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = YES # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate getter # and setter methods for a property. Setting this option to YES (the default) # will make doxygen replace the get and set methods by a property in the # documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and # unions are shown inside the group in which they are included (e.g. using # @ingroup) instead of on a separate page (for HTML and Man pages) or # section (for LaTeX and RTF). INLINE_GROUPED_CLASSES = NO # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and # unions with only public data fields will be shown inline in the documentation # of the scope in which they are defined (i.e. file, namespace, or group # documentation), provided this scope is documented. If set to NO (the default), # structs, classes, and unions are shown on a separate page (for HTML and Man # pages) or section (for LaTeX and RTF). INLINE_SIMPLE_STRUCTS = NO # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO # The SYMBOL_CACHE_SIZE determines the size of the internal cache use to # determine which symbols to keep in memory and which to flush to disk. # When the cache is full, less often used symbols will be written to disk. # For small to medium size projects (<1000 input files) the default value is # probably good enough. For larger projects a too small cache size can cause # doxygen to be busy swapping symbols to and from disk most of the time # causing a significant performance penalty. # If the system has enough physical memory increasing the cache will improve the # performance by keeping more symbols in memory. Note that the value works on # a logarithmic scale so increasing the size by one will roughly double the # memory usage. The cache size is given by this formula: # 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, -# corresponding to a cache size of 2^16 = 65536 symbols +# corresponding to a cache size of 2^16 = 65536 symbols. SYMBOL_CACHE_SIZE = 0 +# Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be +# set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given +# their name and scope. Since this can be an expensive process and often the +# same symbol appear multiple times in the code, doxygen keeps a cache of +# pre-resolved symbols. If the cache is too small doxygen will become slower. +# If the cache is too large, memory is wasted. The cache size is given by this +# formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols. + +LOOKUP_CACHE_SIZE = 0 + #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO +# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal scope will be included in the documentation. + +EXTRACT_PACKAGE = NO + # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = NO # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespaces are hidden. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. -HIDE_FRIEND_COMPOUNDS = @MITK_DOXYGEN_HIDE_FRIEND_COMPOUNDS@ +HIDE_FRIEND_COMPOUNDS = YES # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = NO # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # will list include files with double quotes in the documentation # rather than with sharp brackets. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen # will sort the (brief and detailed) documentation of class members so that # constructors and destructors are listed first. If set to NO (the default) # the constructors will appear in the respective orders defined by # SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. # This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO # and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = YES # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to # do proper type resolution of all parameters of a function it will reject a # match between the prototype and the implementation of a member function even # if there is only one candidate or it is obvious which candidate to choose # by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen # will still accept a match between prototype and implementation in such cases. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. -ENABLED_SECTIONS = +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 -# 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 = 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 = NO +SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. The create the layout file # that represents doxygen's defaults, run doxygen with the -l option. # You can optionally specify a file name after the option, if omitted # DoxygenLayout.xml will be used as the name of the layout file. LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files # containing the references data. This must be a list of .bib files. The # .bib extension is automatically appended if omitted. Using this command # requires the bibtex tool to be installed. See also # http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style -# of the bibliography can be controlled using LATEX_BIB_STYLE. +# 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 = @PROJECT_SOURCE_DIR@ # 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 \ - *.txx \ - *.tpp \ - *.cxx \ - *.cmake + *.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 +# 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 directory from which doxygen is run. +# Note that relative paths are relative to the directory from which doxygen is +# run. -EXCLUDE = @PROJECT_SOURCE_DIR@/documentation/snippets/ \ - @PROJECT_SOURCE_DIR@/test/ +EXCLUDE = @PROJECT_SOURCE_DIR@/README.md \ + @PROJECT_SOURCE_DIR@/documentation/snippets/ \ + @PROJECT_SOURCE_DIR@/test/ \ + @PROJECT_SOURCE_DIR@/gh-pages \ + @PROJECT_SOURCE_DIR@/.git/ -# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# 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/* +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 = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = @PROJECT_SOURCE_DIR@/documentation/snippets/ # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = YES # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). -IMAGE_PATH = +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 = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) # and it is also possible to disable source filtering for a specific pattern # using *.ext= (so without naming a filter). This option only has effect when # FILTER_SOURCE_FILES is enabled. FILTER_SOURCE_PATTERNS = #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = YES # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. # Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. -VERBATIM_HEADERS = YES +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 = html +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 adviced to generate a default header using "doxygen -w html +# 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 = +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 = +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 -# stylesheet in the HTML output directory as well, or it will be erased! +# style sheet in the HTML output directory as well, or it will be erased! -HTML_STYLESHEET = +HTML_STYLESHEET = @US_DOXYGEN_CSS@ # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that # the files will be copied as-is; there are no commands or markers available. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. -# Doxygen will adjust the colors in the stylesheet and background images +# 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 = NO # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated # that can be used as input for Qt's qhelpgenerator to generate a # Qt Compressed Help (.qch) of the generated HTML documentation. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to # add. For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see # # Qt Help Project / Custom Filters. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's # filter section matches. # # Qt Help Project / Filter Attributes. QHP_SECT_FILTER_ATTRS = # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files # will be generated, which together with the HTML files, form an Eclipse help # plugin. To install this plugin and make it available under the help contents # menu in Eclipse, the contents of the directory containing the HTML and XML # files needs to be copied into the plugins directory of eclipse. The name of # the directory within the plugins directory should be the same as # the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before # the help appears. GENERATE_ECLIPSEHELP = NO # A unique identifier for the eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have # this name. ECLIPSE_DOC_ID = org.doxygen.Project -# The DISABLE_INDEX tag can be used to turn on/off the condensed index at -# top of each HTML page. The value NO (the default) enables the index and -# the value YES disables it. +# 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 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 - # 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 +GENERATE_TREEVIEW = NO -# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, -# and Class Hierarchy pages using a tree view instead of an ordered list. +# 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. -USE_INLINE_TREES = NO +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 also need to install MathJax separately and +# 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.org site, so you can quickly see the result without installing -# MathJax, but it is strongly recommended to install a local copy of MathJax -# before deployment. +# 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 stylesheet definitions from file. Syntax is similar to doxygen's +# 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 = +PREDEFINED = US_PREPEND_NAMESPACE(x)=x \ + US_BEGIN_NAMESPACE= \ + US_END_NAMESPACE= \ + "US_BASECLASS_NAME=@US_BASECLASS_NAME@" \ + US_EXPORT= # 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 = US_BASECLASS_NAME +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. -# Optionally an initial location of the external documentation -# can be added for each tagfile. The format of a tag file without -# this location is as follows: +# 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. If a location is present for each tag, the installdox tool -# does not have to be run to correct the links. -# 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. +# 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 = +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 = +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 -# the CLASS_DIAGRAMS tag to NO. +# 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, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# 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 = YES +DIRECTORY_GRAPH = NO # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are svg, png, jpg, or gif. # If left blank png will be used. If you choose svg you need to set # HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible in IE 9+ (other browsers do not have this requirement). DOT_IMAGE_FORMAT = png # If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to # enable generation of interactive SVG images that allow zooming and panning. # Note that this requires a modern browser other than Internet Explorer. # Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you # need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible. Older versions of IE do not have SVG support. INTERACTIVE_SVG = NO # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = @US_DOXYGEN_DOT_PATH@ # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the # \mscfile command). MSCFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = NO # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = NO # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices.dox b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices.dox index 888beb624a..6da53ccf88 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices.dox +++ b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices.dox @@ -1,27 +1,69 @@ /** \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_EmulateSingleton + +*/ + +/** + \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. +\standalone +\section MainPage_BI Build Instructions + +How to build the C++ Micro Services library is explained in detail on the \ref BuildInstructions page. +\endstandalone + +\section Examples + +- \ref MicroServices_DictionaryService + +\section Tutorials + Following is a list of use cases and common patterns -- \subpage MicroServices_EmulateSingleton +- \ref MicroServices_TheModuleContext +- \ref MicroServices_EmulateSingleton */ diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox index f5c89649c7..0b3094f105 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox +++ b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox @@ -1,90 +1,91 @@ /** \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 MITK Micro Services can be used to emulate the singleton pattern using a non-singleton class. This +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 MITK micro services API. The changes +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 itk::LightObject: All service implementations (not their interfaces) must inherit from itk::LightObject. + - Inherit us::Base: All service implementations (not their interfaces) must inherit from us::Base or from the base + class as specified in the CMake configuration. In the implementation above, the class SingletonOneService provides the implementation as well as the interface. - Friend activator: We move the responsibility of constructing instances of SingletonOneService from the GetInstance() method to the module activator. - Service interface declaration: Because the SingletonOneService class introduces a new service interface, it must - be registered under a unique name using the helper macro MITK_DECLARE_SERVICE_INTERFACE. + 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 mitk::ModuleContext or mitk::ServiceTracker API. The +services and hence should be retrieved by clients using the ModuleContext or ServiceTracker API. The GetInstance() method is for migration purposes only. \snippet uServices-singleton/SingletonOne.cpp ss1d The SingletonTwoService::GetInstance() method is implemented exactly as in SingletonOneService. Because we know that the module activator guarantees that a SingletonTwoService instance will always be available during the life-time of a SingletonOneService instance (see below), we can assert a non-null pointer. Otherwise, we would have to handle the null-pointer case. The order of construction/registration and destruction/unregistration of our singletons (or any other services) is defined in the Load() and Unload() methods of the module activator. \snippet uServices-singleton/main.cpp 0 The Unload() method is defined as: \snippet uServices-singleton/main.cpp 1 */ diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md new file mode 100644 index 0000000000..9f45bdabf9 --- /dev/null +++ b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md @@ -0,0 +1,36 @@ +The %Module Context {#MicroServices_TheModuleContext} +=================== + +In the context of the C++ Micro Services library, we will call all supported "shared library" types +(DLL, DSO, DyLib, etc.) uniformly a *module*. A module accesses the C++ Micro Services API via a +ModuleContext object. While multiple modules could use the same ModuleContext, it is highly recommended +that each module gets its own (this will enable module specific service usage tracking and also allows +the C++ Micro Services framework to properly cleanup resources after a module has been unloaded). + +### Creating a %ModuleContext + +To create a ModuleContext object for a specific library, you have two options. If your project uses +CMake as the build system, use the supplied `usFunctionGenerateModuleInit` CMake function to automatically +create a source file and add it to your module's sources: + + set(module_srcs ) + usFunctionGenerateModuleInit(module_srcs + NAME "My Module" + LIBRARY_NAME "mylibname" + VERSION "1.0.0" + ) + add_library(mylib ${module_srcs}) + +If you do not use CMake, you have to add a call to the macro `US_INITIALIZE_MODULE` in one of the source +files of your module: + +\snippet uServices-modulecontext/main.cpp InitializeModule + +### Getting a %ModuleContext + +To retrieve the module specific ModuleContext object from anywhere in your module, use the +`GetModuleContext` function: + +\snippet uServices-modulecontext/main.cpp GetModuleContext + +Please note that the call to `GetModuleContext` will fail if you did not create a module specific context. diff --git a/Core/Code/CppMicroServices/documentation/doxygen/doxygen.css b/Core/Code/CppMicroServices/documentation/doxygen/doxygen.css new file mode 100644 index 0000000000..6d43eb7a9a --- /dev/null +++ b/Core/Code/CppMicroServices/documentation/doxygen/doxygen.css @@ -0,0 +1,1103 @@ +/* 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%; +} + +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; +} + +.fragment { + font-family: monospace, fixed; + font-size: 105%; +} + +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.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: 8px; + 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, .retval .paramname { + font-weight: bold; + vertical-align: top; +} + +.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.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 +{ + margin-left:-7px; + padding-left: 3px; + border-left:4px solid; + border-color: #D0C000; +} + +dl.warning, dl.attention +{ + margin-left:-7px; + padding-left: 3px; + border-left:4px solid; + border-color: #FF0000; +} + +dl.pre, dl.post, dl.invariant +{ + margin-left:-7px; + padding-left: 3px; + border-left:4px solid; + border-color: #00D000; +} + +dl.deprecated +{ + margin-left:-7px; + padding-left: 3px; + border-left:4px solid; + border-color: #505050; +} + +dl.todo +{ + margin-left:-7px; + padding-left: 3px; + border-left:4px solid; + border-color: #00C0E0; +} + +dl.test +{ + margin-left:-7px; + padding-left: 3px; + border-left:4px solid; + border-color: #3030E0; +} + +dl.bug +{ + margin-left:-7px; + 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; + } + pre.fragment + { + overflow: visible; + 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+ */ + } +} + +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 new file mode 100644 index 0000000000..827280b91e --- /dev/null +++ b/Core/Code/CppMicroServices/documentation/doxygen/examples/MicroServices_DictionaryService.md @@ -0,0 +1,29 @@ +Implementing A Dictionary Service {#MicroServices_DictionaryService} +================================= + +This example demonstrates how to implement a service object. First, we must define the service interface +and then we define an implementation of that interface. In this particular example, we will create a +dictionary service that we can use to check if a word exists, which indicates if the word is spelled +correctly or not. + +We start by defining the dictionary interface (for example in a file called DictionaryService.h): + +\include uServices-dictionaryservice/DictionaryService.h + +The service interface is quite simple, with only one method that needs to be implemented. Notice that the +file does only contain the interface declaration and no actual code. + +In the following source code, the module uses its module context to register the dictionary service. +We implement the dictionary service as an inner class of the module activator class, but we could have also +put it in a separate file. Also note that there is no need to explicityl export any symbols from the module. + +\snippet uServices-dictionaryservice/main.cpp Activator + +Note that we do not need to unregister the service in the `Unload` method, because it will be done automatically +for us during static de-initialization of the module. + +In the last line, we "export" the module activator, assuming that it is contained in a module named +`DictionaryServiceModule`. We can get the highest ranking service implementation for the DictionaryService interface +by querying the service registry via the module context: + +\snippet uServices-dictionaryservice/main.cpp GetDictionaryService diff --git a/Core/Code/CppMicroServices/documentation/doxygen/footer.html b/Core/Code/CppMicroServices/documentation/doxygen/footer.html new file mode 100644 index 0000000000..38c8204a29 --- /dev/null +++ b/Core/Code/CppMicroServices/documentation/doxygen/footer.html @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/Core/Code/CppMicroServices/documentation/doxygen/header.html b/Core/Code/CppMicroServices/documentation/doxygen/header.html new file mode 100644 index 0000000000..847964d749 --- /dev/null +++ b/Core/Code/CppMicroServices/documentation/doxygen/header.html @@ -0,0 +1,27 @@ +--- +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 new file mode 100644 index 0000000000..e7f055886a --- /dev/null +++ b/Core/Code/CppMicroServices/documentation/doxygen/standalone/BuildInstructions.md @@ -0,0 +1,77 @@ +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. Please note that static mode is experimental + and has not received extensive testing yet. +- **US_BUILD_TESTING** + Build unit tests and code snippets. +- **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 + +### 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/uServices-activator/main.cpp b/Core/Code/CppMicroServices/documentation/snippets/uServices-activator/main.cpp index b754c987ba..35d4e6aeb9 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-activator/main.cpp +++ b/Core/Code/CppMicroServices/documentation/snippets/uServices-activator/main.cpp @@ -1,28 +1,27 @@ -#include #include US_USE_NAMESPACE //! [0] class MyActivator : public ModuleActivator { public: void Load(ModuleContext* /*context*/) { /* register stuff */ } void Unload(ModuleContext* /*context*/) { /* cleanup */ } }; US_EXPORT_MODULE_ACTIVATOR(mylibname, MyActivator) //![0] int main(int /*argc*/, char* /*argv*/[]) { MyActivator ma; return 0; } diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/DictionaryService.h b/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/DictionaryService.h new file mode 100644 index 0000000000..304d76c6c3 --- /dev/null +++ b/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/DictionaryService.h @@ -0,0 +1,27 @@ +#ifndef DICTIONARYSERVICE_H +#define DICTIONARYSERVICE_H + +#include + +#include + +/** + * A simple service interface that defines a dictionary service. + * A dictionary service simply verifies the existence of a word. + **/ +struct DictionaryService +{ + virtual ~DictionaryService() {} + + /** + * Check for the existence of a word. + * @param word the word to be checked. + * @return true if the word is in the dictionary, + * false otherwise. + **/ + virtual bool checkWord(const std::string& word) = 0; +}; + +US_DECLARE_SERVICE_INTERFACE(DictionaryService, "DictionaryService/1.0") + +#endif // DICTIONARYSERVICE_H diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp b/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp new file mode 100644 index 0000000000..3fd7bf4df5 --- /dev/null +++ b/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp @@ -0,0 +1,119 @@ + +//! [Activator] +#include "DictionaryService.h" + +#include +#include +#include + +// Replace that include with your own base class declaration +#include US_BASECLASS_HEADER + +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module activator that uses the module + * context to register an English language dictionary service + * with the C++ Micro Services registry during static initialization + * of the module. The dictionary service interface is + * defined in a separate file and is implemented by a nested class. + */ +class US_ABI_LOCAL MyActivator : public ModuleActivator +{ + +private: + + /** + * A private inner class that implements a dictionary service; + * see DictionaryService for details of the service. + */ + class DictionaryImpl : public US_BASECLASS_NAME, public DictionaryService + { + // The set of words contained in the dictionary. + US_UNORDERED_SET_TYPE m_dictionary; + + public: + + DictionaryImpl() + { + m_dictionary.insert("welcome"); + m_dictionary.insert("to"); + m_dictionary.insert("the"); + m_dictionary.insert("micro"); + m_dictionary.insert("services"); + m_dictionary.insert("tutorial"); + } + + /** + * Implements DictionaryService.checkWord(). Determines + * if the passed in word is contained in the dictionary. + * @param word the word to be checked. + * @return true if the word is in the dictionary, + * false otherwise. + **/ + bool checkWord(const std::string& word) + { + std::string lword(word); + std::transform(lword.begin(), lword.end(), lword.begin(), ::tolower); + + return m_dictionary.find(lword) != m_dictionary.end(); + } + }; + + std::auto_ptr m_dictionaryService; + + +public: + + /** + * Implements ModuleActivator::Load(). Registers an + * instance of a dictionary service using the module context; + * attaches properties to the service that can be queried + * when performing a service look-up. + * @param context the context for the module. + */ + void Load(ModuleContext* context) + { + m_dictionaryService.reset(new DictionaryImpl); + ServiceProperties props; + props["Language"] = std::string("English"); + context->RegisterService(m_dictionaryService.get(), props); + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unregister any registered services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + // NOTE: The service is automatically unregistered + } + +}; + +US_EXPORT_MODULE_ACTIVATOR(DictionaryServiceModule, MyActivator) +//![Activator] + +#include + +US_INITIALIZE_MODULE("DictionaryServiceModule", "", "", "1.0.0") + +int main(int /*argc*/, char* /*argv*/[]) +{ + //![GetDictionaryService] + ServiceReference dictionaryServiceRef = GetModuleContext()->GetServiceReference(); + if (dictionaryServiceRef) + { + DictionaryService* dictionaryService = GetModuleContext()->GetService(dictionaryServiceRef); + if (dictionaryService) + { + std::cout << "Dictionary contains 'Tutorial': " << dictionaryService->checkWord("Tutorial") << std::endl; + } + } + //![GetDictionaryService] + return 0; +} diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp b/Core/Code/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp new file mode 100644 index 0000000000..2afb314c9a --- /dev/null +++ b/Core/Code/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp @@ -0,0 +1,27 @@ +#include + +//! [InitializeModule] +#include + +US_INITIALIZE_MODULE("My Module", "mylibname", "", "1.0.0") +//! [InitializeModule] + +//! [GetModuleContext] +#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] + +int main(int /*argc*/, char* /*argv*/[]) +{ + RetrieveModuleContext(); + return 0; +} diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h b/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h index 9c52c9dd4d..a8aa153e56 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h +++ b/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h @@ -1,67 +1,66 @@ #ifndef SINGLETONONE_H #define SINGLETONONE_H #include #include #include #include #include US_BASECLASS_HEADER -namespace mitk { class ModuleContext; } //![s1] class SingletonOne { public: static SingletonOne& GetInstance(); // Just some member int a; private: SingletonOne(); ~SingletonOne(); // Disable copy constructor and assignment operator. SingletonOne(const SingletonOne&); SingletonOne& operator=(const SingletonOne&); }; //![s1] class SingletonTwoService; //![ss1] class SingletonOneService : public US_BASECLASS_NAME { public: // This will return a SingletonOneService instance with the // lowest service id at the time this method was called the first // time and returned a non-null value (which is usually the instance // which was registered first). A null-pointer is returned if no // instance was registered yet. static SingletonOneService* GetInstance(); int a; private: // Only our module activator class should be able to instantiate // a SingletonOneService object. friend class MyActivator; SingletonOneService(); ~SingletonOneService(); // Disable copy constructor and assignment operator. SingletonOneService(const SingletonOneService&); SingletonOneService& operator=(const SingletonOneService&); }; US_DECLARE_SERVICE_INTERFACE(SingletonOneService, "org.cppmicroservices.snippet.SingletonOneService") //![ss1] #endif // SINGLETONONE_H diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake b/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake index 63d0db051e..640356da1a 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake +++ b/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake @@ -1,12 +1,11 @@ set(snippet_src_files main.cpp SingletonOne.cpp SingletonTwo.cpp ) usFunctionGenerateModuleInit(snippet_src_files NAME "uServices_singleton" - LIBRARY_NAME "" - DEPENDS "" + EXECUTABLE ) diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp b/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp index ea5ef7ed07..b9257272cd 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp +++ b/Core/Code/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(mitk::ModuleContext*) + // the shared library after the call to Unload(ModuleContext*) // has returned. // Since SingletonOneService needs a non-null SingletonTwoService // instance in its destructor, we explicitly unregister and delete the // SingletonOneService instance here. This way, the SingletonOneService // destructor will still get a valid SingletonTwoService instance. m_SingletonOneReg.Unregister(); delete m_SingletonOne; // For singletonTwoService, we could rely on the automatic unregistering // by the service registry and on automatic deletion if you used // smart pointer reference counting. You must not delete service instances // in this method without unregistering them first. m_SingletonTwoReg.Unregister(); delete m_SingletonTwo; } //![1] private: SingletonOneService* m_SingletonOne; SingletonTwoService* m_SingletonTwo; ServiceRegistration m_SingletonOneReg; ServiceRegistration m_SingletonTwoReg; }; US_EXPORT_MODULE_ACTIVATOR(uServices_singleton, MyActivator) int main() { } diff --git a/Core/Code/CppMicroServices/src/CMakeLists.txt b/Core/Code/CppMicroServices/src/CMakeLists.txt index 78808ae0e1..e74ca24272 100644 --- a/Core/Code/CppMicroServices/src/CMakeLists.txt +++ b/Core/Code/CppMicroServices/src/CMakeLists.txt @@ -1,168 +1,164 @@ #----------------------------------------------------------------------------- # US source files #----------------------------------------------------------------------------- set(_srcs util/usAny.cpp util/usThreads.cpp util/usUtils.cpp service/usLDAPExpr.cpp service/usLDAPFilter.cpp service/usServiceException.cpp service/usServiceEvent.cpp service/usServiceListenerEntry.cpp service/usServiceListenerEntry_p.h service/usServiceListeners.cpp service/usServiceListeners_p.h service/usServiceProperties.cpp service/usServiceReference.cpp service/usServiceReferencePrivate.cpp service/usServiceRegistration.cpp service/usServiceRegistrationPrivate.cpp service/usServiceRegistry.cpp service/usServiceRegistry_p.h module/usCoreModuleContext_p.h module/usCoreModuleContext.cpp module/usModuleContext.cpp module/usModule.cpp module/usModuleEvent.cpp module/usModuleInfo.cpp module/usModulePrivate.cpp module/usModuleRegistry.cpp module/usModuleUtils.cpp module/usModuleVersion.cpp ) set(_private_headers - util/usAtomicInt.h - util/usExportMacros.h - util/usFunctor.h - util/usStaticInit.h - util/usThreads.h - util/usUtils.h + util/usAtomicInt_p.h + util/usExportMacros_p.h + util/usFunctor_p.h + util/usStaticInit_p.h + util/usThreads_p.h + util/usUtils_p.h service/usServiceTracker.tpp service/usServiceTrackerPrivate.h service/usServiceTrackerPrivate.tpp - service/usTrackedService.h - service/usTrackedServiceListener.h + service/usTrackedService_p.h + service/usTrackedServiceListener_p.h service/usTrackedService.tpp - module/usModuleAbstractTracked.h + module/usModuleAbstractTracked_p.h module/usModuleAbstractTracked.tpp - module/usModuleUtils.h + module/usModuleUtils_p.h ) set(_public_headers util/usAny.h util/usSharedData.h service/usLDAPFilter.h service/usServiceEvent.h service/usServiceException.h service/usServiceInterface.h service/usServiceProperties.h service/usServiceReference.h service/usServiceRegistration.h service/usServiceTracker.h service/usServiceTrackerCustomizer.h module/usGetModuleContext.h module/usModule.h module/usModuleActivator.h module/usModuleContext.h module/usModuleEvent.h module/usModuleInfo.h + module/usModuleInitialization.h module/usModuleRegistry.h - module/usModuleUtils.h module/usModuleVersion.h ) if(_us_baseclass_default) list(APPEND _public_headers util/usBase.h) endif() -if(US_ENABLE_THREADING_SUPPORT) - list(APPEND _public_headers util/usThreads.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() if(US_BUILD_SHARED_LIBS) usFunctionGenerateModuleInit(_srcs NAME ${PROJECT_NAME} VERSION "0.9.0") endif() add_library(${PROJECT_NAME} ${_srcs} ${_public_headers} ${_private_headers}) set_property(TARGET ${PROJECT_NAME} PROPERTY FRAMEWORK 1) if(US_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 PUBLIC_HEADER ${US_PUBLIC_HEADERS} ${us_config_h_file}) set_property(TARGET ${PROJECT_NAME} PROPERTY PRIVATE_HEADER ${_private_headers}) else() set(US_PUBLIC_HEADERS ${US_PUBLIC_HEADERS} PARENT_SCOPE) set(US_PRIVATE_HEADERS ${US_PRIVATE_HEADERS} PARENT_SCOPE) endif() #----------------------------------------------------------------------------- # Install support (only if not in embedded mode) #----------------------------------------------------------------------------- if(NOT US_IS_EMBEDDED) install(TARGETS ${PROJECT_NAME} FRAMEWORK DESTINATION . RUNTIME DESTINATION bin LIBRARY DESTINATION lib ARCHIVE DESTINATION lib PUBLIC_HEADER DESTINATION include PRIVATE_HEADER DESTINATION include) endif() diff --git a/Core/Code/CppMicroServices/src/module/usGetModuleContext.h b/Core/Code/CppMicroServices/src/module/usGetModuleContext.h index 93365aa7d7..85b5a9e5f4 100644 --- a/Core/Code/CppMicroServices/src/module/usGetModuleContext.h +++ b/Core/Code/CppMicroServices/src/module/usGetModuleContext.h @@ -1,50 +1,50 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USGETMODULECONTEXT_H #define USGETMODULECONTEXT_H -#include +#include US_BEGIN_NAMESPACE class ModuleContext; /** * Returns the module context of the calling module. * * This function allows easy access to the own ModuleContext instance from - * inside a US module. + * inside a C++ Micro Services module. * * \internal * * Note that the corresponding function definition is provided for each - * module by the mitkModuleInit.cpp file. This file is customized via CMake - * configure_file(...) and automatically compiled into each US module. + * module by the usModuleInit.cpp file. This file is customized via CMake + * configure_file(...) and automatically compiled into each module. * Consequently, the GetModuleContext function is not exported, since each * module gets its "own version". */ US_ABI_LOCAL ModuleContext* GetModuleContext(); US_END_NAMESPACE #endif // USGETMODULECONTEXT_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.tpp b/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.tpp index cb7dcb5bc7..a40324c462 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.tpp +++ b/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.tpp @@ -1,314 +1,314 @@ /*============================================================================= 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_BEGIN_NAMESPACE template const bool ModuleAbstractTracked::DEBUG = false; template ModuleAbstractTracked::ModuleAbstractTracked() { closed = false; } template ModuleAbstractTracked::~ModuleAbstractTracked() { } template void ModuleAbstractTracked::SetInitial(const std::list& initiallist) { initial = initiallist; if (DEBUG) { for(typename std::list::const_iterator item = initiallist.begin(); item != initiallist.end(); ++item) { US_DEBUG << "ModuleAbstractTracked::setInitial: " << (*item); } } } template void ModuleAbstractTracked::TrackInitial() { while (true) { S item(0); { typename Self::Lock l(this); if (closed || (initial.size() == 0)) { /* * if there are no more initial items */ return; /* we are done */ } /* * move the first item from the initial list to the adding list * within this synchronized block. */ item = initial.front(); initial.pop_front(); if (tracked[item]) { /* if we are already tracking this item */ US_DEBUG(DEBUG) << "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) << "ModuleAbstractTracked::trackInitial[already adding]: " << item; continue; /* skip this item */ } adding.push_back(item); } US_DEBUG(DEBUG) << "ModuleAbstractTracked::trackInitial: " << item; TrackAdding(item, R()); /* * Begin tracking it. We call trackAdding * since we have already put the item in the * adding list. */ } } template void ModuleAbstractTracked::Close() { closed = true; } template void ModuleAbstractTracked::Track(S item, R related) { T object(0); { typename Self::Lock l(this); if (closed) { return; } object = tracked[item]; if (!object) { /* we are not tracking the item */ if (std::find(adding.begin(), adding.end(),item) != adding.end()) { /* if this item is already in the process of being added. */ US_DEBUG(DEBUG) << "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) << "ModuleAbstractTracked::track[modified]: " << item; Modified(); /* increment modification count */ } } if (!object) { /* we are not tracking the item */ TrackAdding(item, related); } else { /* Call customizer outside of synchronized region */ CustomizerModified(item, related, object); /* * If the customizer throws an unchecked exception, it is safe to * let it propagate */ } } template void ModuleAbstractTracked::Untrack(S item, R related) { T object(0); { typename Self::Lock l(this); std::size_t initialSize = initial.size(); initial.remove(item); if (initialSize != initial.size()) { /* if this item is already in the list * of initial references to process */ US_DEBUG(DEBUG) << "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) << "ModuleAbstractTracked::untrack[being added]: " << item; return; /* * in case the item is untracked while in the process of * adding */ } object = tracked[item]; /* * must remove from tracker before * calling customizer callback */ tracked.erase(item); if (!object) { /* are we actually tracking the item */ return; } Modified(); /* increment modification count */ } US_DEBUG(DEBUG) << "ModuleAbstractTracked::untrack[removed]: " << item; /* Call customizer outside of synchronized region */ CustomizerRemoved(item, related, object); /* * If the customizer throws an unchecked exception, it is safe to let it * propagate */ } template std::size_t ModuleAbstractTracked::Size() const { return tracked.size(); } template bool ModuleAbstractTracked::IsEmpty() const { return tracked.empty(); } template T ModuleAbstractTracked::GetCustomizedObject(S item) const { typename TrackingMap::const_iterator i = tracked.find(item); if (i != tracked.end()) return i->second; return T(); } template void ModuleAbstractTracked::GetTracked(std::list& items) const { for (typename TrackingMap::const_iterator i = tracked.begin(); i != tracked.end(); ++i) { items.push_back(i->first); } } template void ModuleAbstractTracked::Modified() { trackingCount.Ref(); } template int ModuleAbstractTracked::GetTrackingCount() const { return trackingCount; } template void ModuleAbstractTracked::CopyEntries(TrackingMap& map) const { map.insert(tracked.begin(), tracked.end()); } template bool ModuleAbstractTracked::CustomizerAddingFinal(S item, const T& custom) { typename Self::Lock l(this); std::size_t addingSize = adding.size(); adding.remove(item); if (addingSize != adding.size() && !closed) { /* * if the item was not untracked during the customizer * callback */ if (custom) { tracked[item] = custom; Modified(); /* increment modification count */ this->NotifyAll(); /* notify any waiters */ } return false; } else { return true; } } template void ModuleAbstractTracked::TrackAdding(S item, R related) { US_DEBUG(DEBUG) << "ModuleAbstractTracked::trackAdding:" << item; T object(0); bool becameUntracked = false; /* Call customizer outside of synchronized region */ try { object = CustomizerAdding(item, related); becameUntracked = this->CustomizerAddingFinal(item, object); } catch (...) { /* * If the customizer throws an exception, it will * propagate after the cleanup code. */ this->CustomizerAddingFinal(item, object); throw; } /* * The item became untracked during the customizer callback. */ if (becameUntracked && object) { US_DEBUG(DEBUG) << "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.h b/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked_p.h similarity index 99% rename from Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.h rename to Core/Code/CppMicroServices/src/module/usModuleAbstractTracked_p.h index af4ddb5f65..a0751c4881 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.h +++ b/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked_p.h @@ -1,291 +1,291 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USMODULEABSTRACTTRACKED_H #define USMODULEABSTRACTTRACKED_H #include -#include "usAtomicInt.h" +#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 US module system. * * Abstract class to track items. If a Tracker is reused (closed then reopened), * then a new ModuleAbstractTracked object is used. This class acts as a map of tracked * item -> customized object. Subclasses of this class will act as the listener * object for the tracker. This class is used to synchronize access to the * tracked items. This is not a public class. It is only for use by the * implementation of the Tracker class. * * @tparam S The tracked item. It is the key. * @tparam T The value mapped to the tracked item. * @tparam R The reason the tracked item is being tracked or untracked. * @ThreadSafe */ template class ModuleAbstractTracked : public US_DEFAULT_THREADING > { public: /* set this to true to compile in debug messages */ static const bool DEBUG; // = false; typedef std::map TrackingMap; /** * ModuleAbstractTracked constructor. */ ModuleAbstractTracked(); virtual ~ModuleAbstractTracked(); /** * Set initial list of items into tracker before events begin to be * received. * * This method must be called from Tracker's open method while synchronized * on this object in the same synchronized block as the add listener call. * * @param list The initial list of items to be tracked. null * entries in the list are ignored. * @GuardedBy this */ void SetInitial(const std::list& list); /** * Track the initial list of items. This is called after events can begin to * be received. * * This method must be called from Tracker's open method while not * synchronized on this object after the add listener call. * */ void TrackInitial(); /** * Called by the owning Tracker object when it is closed. */ void Close(); /** * Begin to track an item. * * @param item S to be tracked. * @param related Action related object. */ void Track(S item, R related); /** * Discontinue tracking the item. * * @param item S to be untracked. * @param related Action related object. */ void Untrack(S item, R related); /** * Returns the number of tracked items. * * @return The number of tracked items. * * @GuardedBy this */ std::size_t Size() const; /** * Returns if the tracker is empty. * * @return Whether the tracker is empty. * * @GuardedBy this */ bool IsEmpty() const; /** * Return the customized object for the specified item * * @param item The item to lookup in the map * @return The customized object for the specified item. * * @GuardedBy this */ T GetCustomizedObject(S item) const; /** * Return the list of tracked items. * * @return The tracked items. * @GuardedBy this */ void GetTracked(std::list& items) const; /** * Increment the modification count. If this method is overridden, the * overriding method MUST call this method to increment the tracking count. * * @GuardedBy this */ virtual void Modified(); /** * Returns the tracking count for this ServiceTracker object. * * The tracking count is initialized to 0 when this object is opened. Every * time an item is added, modified or removed from this object the tracking * count is incremented. * * @GuardedBy this * @return The tracking count for this object. */ int GetTrackingCount() const; /** * Copy the tracked items and associated values into the specified map. * * @param map The map into which to copy the tracked items and associated * values. This map must not be a user provided map so that user code * is not executed while synchronized on this. * @return The specified map. * @GuardedBy this */ void CopyEntries(TrackingMap& map) const; /** * Call the specific customizer adding method. This method must not be * called while synchronized on this object. * * @param item S to be tracked. * @param related Action related object. * @return Customized object for the tracked item or null if * the item is not to be tracked. */ virtual T CustomizerAdding(S item, const R& related) = 0; /** * Call the specific customizer modified method. This method must not be * called while synchronized on this object. * * @param item Tracked item. * @param related Action related object. * @param object Customized object for the tracked item. */ virtual void CustomizerModified(S item, const R& related, T object) = 0; /** * Call the specific customizer removed method. This method must not be * called while synchronized on this object. * * @param item Tracked item. * @param related Action related object. * @param object Customized object for the tracked item. */ virtual void CustomizerRemoved(S item, const R& related, T object) = 0; /** * List of items in the process of being added. This is used to deal with * nesting of events. Since events may be synchronously delivered, events * can be nested. For example, when processing the adding of a service and * the customizer causes the service to be unregistered, notification to the * nested call to untrack that the service was unregistered can be made to * the track method. * * Since the std::vector implementation is not synchronized, all access to * this list must be protected by the same synchronized object for * thread-safety. * * @GuardedBy this */ std::list adding; /** * true if the tracked object is closed. * * This field is volatile because it is set by one thread and read by * another. */ volatile bool closed; /** * Initial list of items for the tracker. This is used to correctly process * the initial items which could be modified before they are tracked. This * is necessary since the initial set of tracked items are not "announced" * by events and therefore the event which makes the item untracked could be * delivered before we track the item. * * An item must not be in both the initial and adding lists at the same * time. An item must be moved from the initial list to the adding list * "atomically" before we begin tracking it. * * Since the LinkedList implementation is not synchronized, all access to * this list must be protected by the same synchronized object for * thread-safety. * * @GuardedBy this */ std::list initial; /** * Common logic to add an item to the tracker used by track and * trackInitial. The specified item must have been placed in the adding list * before calling this method. * * @param item S to be tracked. * @param related Action related object. */ void TrackAdding(S item, R related); private: typedef ModuleAbstractTracked Self; /** * Map of tracked items to customized objects. * * @GuardedBy this */ TrackingMap tracked; /** * Modification count. This field is initialized to zero and incremented by * modified. * * @GuardedBy this */ AtomicInt trackingCount; bool CustomizerAddingFinal(S item, const T& custom); }; US_END_NAMESPACE #include "usModuleAbstractTracked.tpp" #endif // USMODULEABSTRACTTRACKED_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleActivator.h b/Core/Code/CppMicroServices/src/module/usModuleActivator.h index 991cfa2b4c..b83d4d3059 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleActivator.h +++ b/Core/Code/CppMicroServices/src/module/usModuleActivator.h @@ -1,131 +1,148 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USMODULEACTIVATOR_H_ #define USMODULEACTIVATOR_H_ #include US_BEGIN_NAMESPACE class ModuleContext; /** * \ingroup MicroServices * * Customizes the starting and stopping of a US module. *

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

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

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

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

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

* This method must complete and return to its caller in a timely manner. * * @param context The execution context of the module being unloaded. * @throws std::exception If this method throws an exception, the * module is still marked as unloaded, and the framework will remove * the module's listeners, unregister all services registered by the * module, and release all services used by the module. */ virtual void Unload(ModuleContext* context) = 0; }; US_END_NAMESPACE +/** + * \ingroup MicroServices + * + * \def US_EXPORT_MODULE_ACTIVATOR(moduleName, type) + * \brief Export a module activator class. + * + * \param _module_libname The physical name of the module, withou prefix or suffix. + * \param _activator_type The fully-qualified type-name of the module activator class. + * + * Call this macro after the definition of your module activator to make it + * accessible by the CppMicroServices library. + * + * Example: + * \snippet uServices-activator/main.cpp 0 + */ #define US_MODULE_ACTIVATOR_INSTANCE_FUNCTION(type) \ struct ScopedPointer \ { \ ScopedPointer(US_PREPEND_NAMESPACE(ModuleActivator)* activator = 0) : m_Activator(activator) {} \ ~ScopedPointer() { delete m_Activator; } \ US_PREPEND_NAMESPACE(ModuleActivator)* m_Activator; \ }; \ \ static ScopedPointer activatorPtr; \ if (activatorPtr.m_Activator == 0) activatorPtr.m_Activator = new type; \ return activatorPtr.m_Activator; #ifdef US_BUILD_SHARED_LIBS - #define US_EXPORT_MODULE_ACTIVATOR(moduleName, type) \ - extern "C" US_ABI_EXPORT US_PREPEND_NAMESPACE(ModuleActivator)* _us_module_activator_instance_ ## moduleName () \ + #include + + #define US_EXPORT_MODULE_ACTIVATOR(_module_libname, _activator_type) \ + extern "C" US_ABI_EXPORT US_PREPEND_NAMESPACE(ModuleActivator)* _us_module_activator_instance_ ## _module_libname () \ { \ - US_MODULE_ACTIVATOR_INSTANCE_FUNCTION(type) \ + US_MODULE_ACTIVATOR_INSTANCE_FUNCTION(_activator_type) \ } #else - #define US_EXPORT_MODULE_ACTIVATOR(moduleName, type) \ - US_PREPEND_NAMESPACE(ModuleActivator)* _us_module_activator_instance_ ## moduleName () \ + #define US_EXPORT_MODULE_ACTIVATOR(_module_libname, _activator_type) \ + US_PREPEND_NAMESPACE(ModuleActivator)* _us_module_activator_instance_ ## _module_libname () \ { \ - US_MODULE_ACTIVATOR_INSTANCE_FUNCTION(type) \ + US_MODULE_ACTIVATOR_INSTANCE_FUNCTION(_activator_type) \ } #endif #endif /* USMODULEACTIVATOR_H_ */ diff --git a/Core/Code/CppMicroServices/src/module/usModuleContext.h b/Core/Code/CppMicroServices/src/module/usModuleContext.h index 098d1a534e..63b00ced85 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleContext.h +++ b/Core/Code/CppMicroServices/src/module/usModuleContext.h @@ -1,638 +1,638 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USMODULECONTEXT_H_ #define USMODULECONTEXT_H_ -#include "usUtils.h" +#include "usUtils_p.h" #include "usServiceInterface.h" #include "usServiceEvent.h" #include "usServiceRegistration.h" #include "usServiceException.h" #include "usModuleEvent.h" US_BEGIN_NAMESPACE typedef US_SERVICE_LISTENER_FUNCTOR ServiceListener; typedef US_MODULE_LISTENER_FUNCTOR ModuleListener; class ModuleContextPrivate; /** * \ingroup MicroServices * * A module's execution context within the framework. The context is used to * grant access to other methods so that this module can interact with the * Micro Services Framework. * *

* ModuleContext methods allow a module to: *

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

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

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

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

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

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

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

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

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

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

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

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

* The specified filter expression is used to select the * registered services whose service properties contain keys and values - * which satisfy the filter expression. See {@link LDAPFilter} for a description + * 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. + * {@link ServiceConstants#OBJECTCLASS() objectClass} property. *
  • If the specified filter is not empty, the * filter expression must match the service. *
* * @param clazz The class name with which the service was registered or * an empty string for all services. * @param filter The filter expression or empty for all * services. * @return A list of ServiceReference objects or * an empty list if no services are registered which satisfy the * search. * @throws std::invalid_argument If the specified filter * contains an invalid filter expression that cannot be parsed. * @throws std::logic_error If this ModuleContext is no longer valid. */ std::list GetServiceReferences(const std::string& clazz, const std::string& filter = std::string()); /** * Returns a list of ServiceReference objects. The returned * list contains services that * were registered under the interface id of the template argument S * and match the specified filter expression. * *

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

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

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

* If multiple such services exist, the service with the highest ranking (as - * specified in its {@link ServiceConstants::SERVICE_RANKING} property) is returned. + * 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 {@link ServiceConstants::SERVICE_ID} property); that is, the + * specified in its ServiceConstants::SERVICE_ID() property); that is, the * service that was registered first is returned. * * @param clazz The class name with which the service was registered. * @return A ServiceReference object, or an invalid ServiceReference if * no services are registered which implement the named class. * @throws std::logic_error If this ModuleContext is no longer valid. * @throws ServiceException If no service was registered under the given class name. * @see #GetServiceReferences(const std::string&, const std::string&) */ ServiceReference GetServiceReference(const std::string& clazz); /** * Returns a ServiceReference object for a service that * implements and was registered under the specified template class argument. * *

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

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

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

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

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

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

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

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

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

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

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

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

* The callback is called if the filter criteria is met. To filter based * upon the class of the service, the filter should reference the - * {@link ServiceConstants#OBJECTCLASS} property. If filter is + * 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 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), 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 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)); } /** * 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 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)); } /** * 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 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)); } private: friend class Module; friend class ModulePrivate; ModuleContext(ModulePrivate* module); // purposely not implemented ModuleContext(const ModuleContext&); ModuleContext& operator=(const ModuleContext&); ModuleContextPrivate * const d; }; US_END_NAMESPACE #endif /* USMODULECONTEXT_H_ */ diff --git a/Core/Code/CppMicroServices/src/module/usModuleEvent.h b/Core/Code/CppMicroServices/src/module/usModuleEvent.h index 0369735e6b..0e1f076758 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleEvent.h +++ b/Core/Code/CppMicroServices/src/module/usModuleEvent.h @@ -1,162 +1,162 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USMODULEEVENT_H #define USMODULEEVENT_H #include #include "usSharedData.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4251) #endif US_BEGIN_NAMESPACE class Module; class ModuleEventData; /** * \ingroup MicroServices * * An event from the Micro Services framework describing a module lifecycle change. *

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

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

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

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

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

    *
  • {@link #LOADING} *
  • {@link #LOADED} *
  • {@link #UNLOADING} *
  • {@link #UNLOADED} *
* * @return The type of lifecycle event. */ Type GetType() const; }; US_END_NAMESPACE #ifdef _MSC_VER #pragma warning(pop) #endif /** * \ingroup MicroServices * @{ */ US_EXPORT std::ostream& operator<<(std::ostream& os, US_PREPEND_NAMESPACE(ModuleEvent::Type) eventType); US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ModuleEvent)& event); /** @}*/ #endif // USMODULEEVENT_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleInfo.h b/Core/Code/CppMicroServices/src/module/usModuleInfo.h index 9f0f99ae2f..3d373651e8 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleInfo.h +++ b/Core/Code/CppMicroServices/src/module/usModuleInfo.h @@ -1,68 +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 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 US module system. */ struct US_EXPORT ModuleInfo { ModuleInfo(const std::string& name, const std::string& libName, const std::string& moduleDeps, const std::string& version); typedef ModuleActivator*(*ModuleActivatorHook)(void); std::string name; std::string libName; std::string moduleDeps; std::string version; std::string location; long id; ModuleActivatorHook activatorHook; }; US_END_NAMESPACE #ifdef _MSC_VER # pragma warning(pop) #endif #endif // USMODULEINFO_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleInitialization.h b/Core/Code/CppMicroServices/src/module/usModuleInitialization.h new file mode 100644 index 0000000000..be931c1a63 --- /dev/null +++ b/Core/Code/CppMicroServices/src/module/usModuleInitialization.h @@ -0,0 +1,123 @@ +/*============================================================================= + + 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 + * + * \def US_INITIALIZE_MODULE(_module_name, _module_libname, _module_depends, _module_version) + * \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 in one of its source files. + * + * Example call for a module with file-name "libmylibname.so". + * \code + * US_INITIALIZE_MODULE("My Service Implementation", "mylibname", "", "1.0.0") + * \endcode + * + * \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 "...". + */ +#define US_INITIALIZE_MODULE(_module_name, _module_libname, _module_depends, _module_version) \ +US_BEGIN_NAMESPACE \ +\ +/* Declare a file scoped ModuleInfo object */ \ +US_GLOBAL_STATIC_WITH_ARGS(ModuleInfo, moduleInfo, (_module_name, _module_libname, _module_depends, _module_version)) \ +\ +/* This class is used to statically initialize the library within the C++ Micro services \ + library. looks up a library specific C-style function a */ \ +class US_ABI_LOCAL ModuleInitializer { \ +\ +public: \ +\ + ModuleInitializer() \ + { \ + std::string location = ModuleUtils::GetLibraryPath(moduleInfo()->libName, \ + reinterpret_cast(moduleInfo)); \ + std::string activator_func = "_us_module_activator_instance_"; \ + if(moduleInfo()->libName.empty()) \ + { \ + activator_func.append(moduleInfo()->name); \ + } \ + else \ + { \ + activator_func.append(moduleInfo()->libName); \ + } \ +\ + moduleInfo()->location = location;\ +\ + if (moduleInfo()->libName.empty()) \ + { \ + /* make sure we retrieve symbols from the executable, if "libName" is empty */ \ + location.clear(); \ + } \ + moduleInfo()->activatorHook = reinterpret_cast(ModuleUtils::GetSymbol(location, activator_func.c_str())); \ +\ + Register(); \ + } \ +\ + static void Register() \ + { \ + ModuleRegistry::Register(moduleInfo()); \ + } \ +\ + ~ModuleInitializer() \ + { \ + ModuleRegistry::UnRegister(moduleInfo()); \ + } \ +\ +}; \ +\ +US_ABI_LOCAL ModuleContext* GetModuleContext() \ +{ \ + /* make sure the module is registered */ \ + if (moduleInfo()->id == 0) \ + { \ + ModuleInitializer::Register(); \ + } \ +\ + return ModuleRegistry::GetModule(moduleInfo()->id)->GetModuleContext(); \ +} \ +\ +US_END_NAMESPACE \ +\ +static US_PREPEND_NAMESPACE(ModuleInitializer) _InitializeModule; \ + + +#endif // USMODULEINITIALIZATION_H diff --git a/Core/Code/CppMicroServices/src/module/usModulePrivate.h b/Core/Code/CppMicroServices/src/module/usModulePrivate.h index b33d3d2157..250569eebd 100644 --- a/Core/Code/CppMicroServices/src/module/usModulePrivate.h +++ b/Core/Code/CppMicroServices/src/module/usModulePrivate.h @@ -1,91 +1,91 @@ /*============================================================================= 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 "usModuleRegistry.h" #include "usModuleVersion.h" #include "usModuleInfo.h" -#include "usAtomicInt.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(); CoreModuleContext* const coreCtx; std::vector requiresIds; std::vector requiresLibs; /** * Module version */ ModuleVersion version; ModuleInfo info; /** * ModuleContext for the module */ ModuleContext* moduleContext; ModuleActivator* moduleActivator; std::map properties; Module* const q; private: static AtomicInt idCounter; // purposely not implemented ModulePrivate(const ModulePrivate&); ModulePrivate& operator=(const ModulePrivate&); }; US_END_NAMESPACE #endif // USMODULEPRIVATE_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleRegistry.cpp b/Core/Code/CppMicroServices/src/module/usModuleRegistry.cpp index 4180978d12..fe432c9106 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleRegistry.cpp +++ b/Core/Code/CppMicroServices/src/module/usModuleRegistry.cpp @@ -1,255 +1,255 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include "usModuleRegistry.h" #include "usModule.h" #include "usModuleInfo.h" #include "usModuleContext.h" #include "usModuleActivator.h" #include "usCoreModuleContext_p.h" -#include "usStaticInit.h" +#include "usStaticInit_p.h" #include US_BEGIN_NAMESPACE typedef US_UNORDERED_MAP_TYPE ModuleMap; US_GLOBAL_STATIC(CoreModuleContext, coreModuleContext) template struct ModuleDeleter { void operator()(GlobalStatic& globalStatic) const { ModuleMap* moduleMap = globalStatic.pointer; for (ModuleMap::const_iterator i = moduleMap->begin(); i != moduleMap->end(); ++i) { delete i->second; } DefaultGlobalStaticDeleter defaultDeleter; defaultDeleter(globalStatic); } }; /** * Table of all installed modules in this framework. * Key is the module id. */ US_GLOBAL_STATIC_WITH_DELETER(ModuleMap, modules, ModuleDeleter) typedef Mutex MutexType; typedef MutexLock MutexLocker; /** * Lock for protecting the modules object */ US_GLOBAL_STATIC(MutexType, modulesLock) /** * Lock for protecting the register count */ US_GLOBAL_STATIC(MutexType, countLock) void ModuleRegistry::Register(ModuleInfo* info) { static long regCount = 0; if (info->id > 0) { // The module was already registered Module* module = 0; { MutexLocker lock(*modulesLock()); module = modules()->operator[](info->id); assert(module != 0); } module->Start(); } else { Module* module = 0; // check if the module is reloaded { MutexLocker lock(*modulesLock()); ModuleMap* map = modules(); for (ModuleMap::const_iterator i = map->begin(); i != map->end(); ++i) { if (i->second->GetLocation() == info->location) { module = i->second; info->id = module->GetModuleId(); } } } if (!module) { module = new Module(); countLock()->Lock(); info->id = ++regCount; countLock()->Unlock(); module->Init(coreModuleContext(), info); MutexLocker lock(*modulesLock()); ModuleMap* map = modules(); map->insert(std::make_pair(info->id, module)); } else { module->Init(coreModuleContext(), info); } module->Start(); } } void ModuleRegistry::UnRegister(const ModuleInfo* info) { // If we are unregistering the core module, we just call // the module activators Unload() method (if there is a // module activator). Since we cannot be sure that the // ModuleContext for the core library is still valid, we // just pass a null-pointer. Using the module context during // static deinitalization time of the core library makes // no sense anyway. if (info->id == 1 && info->activatorHook) { info->activatorHook()->Unload(0); return; } Module* curr = 0; { MutexLocker lock(*modulesLock()); curr = modules()->operator[](info->id); assert(curr != 0); } curr->Stop(); curr->Uninit(); } Module* ModuleRegistry::GetModule(long id) { MutexLocker lock(*modulesLock()); ModuleMap::const_iterator iter = modules()->find(id); if (iter != modules()->end()) { return iter->second; } return 0; } Module* ModuleRegistry::GetModule(const std::string& name) { MutexLocker lock(*modulesLock()); ModuleMap::const_iterator iter = modules()->begin(); ModuleMap::const_iterator iterEnd = modules()->end(); for (; iter != iterEnd; ++iter) { if (iter->second->GetName() == name) { return iter->second; } } return 0; } void ModuleRegistry::GetModules(std::vector& m) { MutexLocker lock(*modulesLock()); ModuleMap* map = modules(); ModuleMap::const_iterator iter = map->begin(); ModuleMap::const_iterator iterEnd = map->end(); for (; iter != iterEnd; ++iter) { m.push_back(iter->second); } } void ModuleRegistry::GetLoadedModules(std::vector& m) { MutexLocker lock(*modulesLock()); ModuleMap::const_iterator iter = modules()->begin(); ModuleMap::const_iterator iterEnd = modules()->end(); for (; iter != iterEnd; ++iter) { if (iter->second->IsLoaded()) { m.push_back(iter->second); } } } typedef std::list StaticInstanceFunctionList; template struct StaticModuleDeleter { void operator()(GlobalStatic& globalStatic) const { StaticInstanceFunctionList* funcList = globalStatic.pointer; for (StaticInstanceFunctionList::const_reverse_iterator i = funcList->rbegin(); i != funcList->rend(); ++i) { (*i)()->Unload(ModuleRegistry::GetModule(1)->GetModuleContext()); } DefaultGlobalStaticDeleter defaultDeleter; defaultDeleter(globalStatic); } }; /** * List of all static modules in this framework. */ US_GLOBAL_STATIC_WITH_DELETER(StaticInstanceFunctionList, staticInstanceFunctionList, StaticModuleDeleter) /** * Lock for protecting the modules object */ US_GLOBAL_STATIC(MutexType, staticInstanceFunctionListLock) void RegisterStaticModuleActivatorInstanceFunction(ModuleActivatorInstanceFunction func) { MutexLocker lock(*staticInstanceFunctionListLock()); staticInstanceFunctionList()->push_back(func); } void UnregisterStaticModuleActivatorInstanceFunction(ModuleActivatorInstanceFunction func) { MutexLocker lock(*staticInstanceFunctionListLock()); staticInstanceFunctionList()->remove(func); } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/module/usModuleRegistry.h b/Core/Code/CppMicroServices/src/module/usModuleRegistry.h index 826aed5fc5..d6a0dd3581 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleRegistry.h +++ b/Core/Code/CppMicroServices/src/module/usModuleRegistry.h @@ -1,121 +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. =============================================================================*/ #ifndef USMODULEREGISTRY_H #define USMODULEREGISTRY_H #include #include -#include +#include US_BEGIN_NAMESPACE class Module; struct ModuleInfo; struct ModuleActivator; /** * \ingroup MicroServices * * Here we handle all the modules that are loaded in the framework. */ class US_EXPORT ModuleRegistry { public: /** * Get the module that has the specified module identifier. * * @param id The identifier of the module to get. * @return Module or null * if the module was not found. */ static Module* GetModule(long id); /** * Get the module that has specified module name. * * @param name The name of the module to get. * @return Module or null. */ static Module* GetModule(const std::string& name); /** * Get all known modules. * * @return A Module list with modules. */ static void GetModules(std::vector& modules); /** * Get all modules currently in module state LOADED. * * @return A List of Modules. */ static void GetLoadedModules(std::vector& modules); private: friend class ModuleInitializer; // disabled ModuleRegistry(); static void Register(ModuleInfo* info); static void UnRegister(const ModuleInfo* info); }; typedef ModuleActivator* (*ModuleActivatorInstanceFunction)(); void US_EXPORT RegisterStaticModuleActivatorInstanceFunction(ModuleActivatorInstanceFunction func); void US_EXPORT UnregisterStaticModuleActivatorInstanceFunction(ModuleActivatorInstanceFunction func); US_END_NAMESPACE #define US_MODULE_LOAD(moduleName, context) \ _us_module_activator_instance_ ## moduleName ()->Load(context); #define US_MODULE_UNLOAD(moduleName, context) \ _us_module_activator_instance_ ## moduleName ()->Unload(context); #define US_MODULE_IMPORT(moduleName) \ extern ::US_PREPEND_NAMESPACE(ModuleActivator)* _us_module_activator_instance_##moduleName(); \ class Static##moduleName##ModuleInstance \ { \ public: \ Static##moduleName##ModuleInstance() \ { \ RegisterStaticModuleActivatorInstanceFunction(_us_module_activator_instance_##moduleName); \ _us_module_activator_instance_##moduleName()->Load(::US_PREPEND_NAMESPACE(GetModuleContext)()); \ } \ ~Static##moduleName##ModuleInstance() \ { \ UnregisterStaticModuleActivatorInstanceFunction(_us_module_activator_instance_##moduleName); \ _us_module_activator_instance_##moduleName()->Unload(::US_PREPEND_NAMESPACE(GetModuleContext)()); \ } \ }; \ static Static##moduleName##ModuleInstance static##moduleName##Instance; #endif // USMODULEREGISTRY_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleUtils.cpp b/Core/Code/CppMicroServices/src/module/usModuleUtils.cpp index 807519389f..4cea854204 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleUtils.cpp +++ b/Core/Code/CppMicroServices/src/module/usModuleUtils.cpp @@ -1,155 +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 "usModuleUtils.h" -#include +#include "usModuleUtils_p.h" +#include US_BEGIN_NAMESPACE #ifdef __GNUC__ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include std::string GetLibraryPath_impl(const std::string& /*libName*/, void* symbol) { Dl_info info; if (dladdr(symbol, &info)) { return info.dli_fname; } else { US_DEBUG << GetLastErrorStr(); } return ""; } void* GetSymbol_impl(const std::string& libName, const char* symbol) { void* selfHandle = 0; if (libName.empty()) { // Get the handle of the executable selfHandle = dlopen(0, RTLD_LAZY); } else { selfHandle = dlopen(libName.c_str(), RTLD_LAZY); } if (selfHandle) { void* addr = dlsym(selfHandle, symbol); dlclose(selfHandle); return addr; } else { US_DEBUG << GetLastErrorStr(); } return 0; } #elif _WIN32 #include std::string GetLibraryPath_impl(const std::string& libName, void *symbol) { HMODULE handle = 0; if (libName.empty()) { // get the handle for the executable handle = GetModuleHandle(0); } else { handle = GetModuleHandle(libName.c_str()); } if (!handle) { US_DEBUG << "GetLibraryPath_impl():GetModuleHandle() " << GetLastErrorStr(); return ""; } char modulePath[512]; if (GetModuleFileName(handle, modulePath, 512)) { return modulePath; } US_DEBUG << "GetLibraryPath_impl():GetModuleFileName() " << GetLastErrorStr(); return ""; } void* GetSymbol_impl(const std::string& libName, const char* symbol) { HMODULE handle = NULL; if (libName.empty()) { handle = GetModuleHandle(NULL); } else { handle = GetModuleHandle(libName.c_str()); } if (!handle) { US_DEBUG << "GetSymbol_impl():GetModuleHandle() " << GetLastErrorStr(); return 0; } void* addr = (void*)GetProcAddress(handle, symbol); if (!addr) { US_DEBUG << "GetSymbol_impl():GetProcAddress(handle," << symbol << ") " << GetLastErrorStr(); } return addr; } #else std::string GetLibraryPath_impl(const std::string& libName, void* symbol) { return ""; } void* GetSymbol_impl(const std::string& libName, const char* symbol) { return 0; } #endif std::string ModuleUtils::GetLibraryPath(const std::string& libName, void* symbol) { return GetLibraryPath_impl(libName, symbol); } void* ModuleUtils::GetSymbol(const std::string& libName, const char* symbol) { return GetSymbol_impl(libName, symbol); } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/module/usModuleUtils.h b/Core/Code/CppMicroServices/src/module/usModuleUtils_p.h similarity index 97% rename from Core/Code/CppMicroServices/src/module/usModuleUtils.h rename to Core/Code/CppMicroServices/src/module/usModuleUtils_p.h index a38ba51da6..bc4943e1e6 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleUtils.h +++ b/Core/Code/CppMicroServices/src/module/usModuleUtils_p.h @@ -1,45 +1,45 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USMODULEUTILS_H #define USMODULEUTILS_H -#include +#include #include US_BEGIN_NAMESPACE /** * This class is not intended to be used directly. It is exported to support * the US module system. */ struct US_EXPORT ModuleUtils { static std::string GetLibraryPath(const std::string& libName, void* symbol); static void* GetSymbol(const std::string& libName, const char* symbol); }; US_END_NAMESPACE #endif // USMODULEUTILS_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleVersion.h b/Core/Code/CppMicroServices/src/module/usModuleVersion.h index dea038f26a..06fe5c59a1 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleVersion.h +++ b/Core/Code/CppMicroServices/src/module/usModuleVersion.h @@ -1,263 +1,263 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USMODULEVERSION_H #define USMODULEVERSION_H -#include +#include #include #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4251) #endif US_BEGIN_NAMESPACE /** * \ingroup MicroServices * * Version identifier for US modules. * *

* Version identifiers have four components. *

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

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

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

* Here is the grammar for version strings. * *

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

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

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

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

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

* A version is considered to be equal to another version if the * majorVersion, minorVersion and microVersion components are equal and the qualifier component * is equal. * * @param object The ModuleVersion object to be compared. * @return A negative integer, zero, or a positive integer if this object is * less than, equal to, or greater than the specified * ModuleVersion object. */ int Compare(const ModuleVersion& object) const; }; US_END_NAMESPACE #ifdef _MSC_VER # pragma warning(pop) #endif /** * \ingroup MicroServices */ US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ModuleVersion)& v); #endif // USMODULEVERSION_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceException.h b/Core/Code/CppMicroServices/src/service/usServiceException.h index 7213499358..4f455913dd 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceException.h +++ b/Core/Code/CppMicroServices/src/service/usServiceException.h @@ -1,127 +1,126 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USSERVICEEXCEPTION_H #define USSERVICEEXCEPTION_H #include -#include +#include #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4275) #endif US_BEGIN_NAMESPACE /** * \ingroup MicroServices * * A service exception used to indicate that a service problem occurred. * *

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

* This exception conforms to the general purpose exception chaining mechanism. */ class US_EXPORT ServiceException : public std::runtime_error { public: enum Type { /** * No exception type is unspecified. */ UNSPECIFIED = 0, /** * The service has been unregistered. */ UNREGISTERED = 1, /** * The service factory produced an invalid service object. */ FACTORY_ERROR = 2, /** * The service factory threw an exception. */ FACTORY_EXCEPTION = 3, /** * An error occurred invoking a remote service. */ REMOTE = 5, /** * The service factory resulted in a recursive call to itself for the * requesting module. */ FACTORY_RECURSION = 6 }; /** * Creates a ServiceException with the specified message, * type and exception cause. * * @param msg The associated message. * @param type The type for this exception. - * @param cause The cause of this exception. */ ServiceException(const std::string& msg, const Type& type = UNSPECIFIED); ServiceException(const ServiceException& o); ServiceException& operator=(const ServiceException& o); ~ServiceException() throw() { } /** * Returns the type for this exception or UNSPECIFIED if the * type was unspecified or unknown. * * @return The type of this exception. */ Type GetType() const; private: /** * Type of service exception. */ Type type; }; US_END_NAMESPACE #ifdef _MSC_VER #pragma warning(pop) #endif /** * \ingroup MicroServices * @{ */ US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceException)& exc); /** @}*/ #endif // USSERVICEEXCEPTION_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceListenerEntry_p.h b/Core/Code/CppMicroServices/src/service/usServiceListenerEntry_p.h index 0405371878..c51f6217fd 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceListenerEntry_p.h +++ b/Core/Code/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 #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, const std::string& filter = ""); Module* GetModule() const; std::string GetFilter() const; LDAPExpr GetLDAPExpr() const; LDAPExpr::LocalCache& GetLocalCache() const; void CallDelegate(const ServiceEvent& event) const; private: US_HASH_FUNCTION_FRIEND(ServiceListenerEntry); ExplicitlySharedDataPointer d; }; US_END_NAMESPACE #ifdef _MSC_VER #pragma warning(pop) #endif US_HASH_FUNCTION_NAMESPACE_BEGIN US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceListenerEntry)) return US_HASH_FUNCTION(const US_PREPEND_NAMESPACE(ServiceListenerEntryData)*, arg.d.ConstData()); US_HASH_FUNCTION_END US_HASH_FUNCTION_NAMESPACE_END #endif // USSERVICELISTENERENTRY_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceListeners.cpp b/Core/Code/CppMicroServices/src/service/usServiceListeners.cpp index 39d24ce341..12220f4c6b 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceListeners.cpp +++ b/Core/Code/CppMicroServices/src/service/usServiceListeners.cpp @@ -1,289 +1,289 @@ /*============================================================================= 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.h" +#include "usUtils_p.h" #include "usServiceListeners_p.h" #include "usServiceReferencePrivate.h" #include "usModule.h" //#include US_BEGIN_NAMESPACE const int ServiceListeners::OBJECTCLASS_IX = 0; const int ServiceListeners::SERVICE_ID_IX = 1; ServiceListeners::ServiceListeners() { hashedServiceKeys.push_back(ServiceConstants::OBJECTCLASS()); hashedServiceKeys.push_back(ServiceConstants::SERVICE_ID()); } void ServiceListeners::AddServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, const std::string& filter) { MutexLocker lock(mutex); ServiceListenerEntry sle(mc->GetModule(), listener, filter); if (serviceSet.find(sle) != serviceSet.end()) { RemoveServiceListener_unlocked(sle); } serviceSet.insert(sle); CheckSimple(sle); } void ServiceListeners::RemoveServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener) { ServiceListenerEntry entryToRemove(mc->GetModule(), listener); 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) { MutexLocker lock(moduleListenerMapMutex); std::list& listeners = moduleListenerMap[mc]; if (std::find_if(listeners.begin(), listeners.end(), std::bind1st(ModuleListenerCompare(), listener)) == listeners.end()) { listeners.push_back(listener); } } void ServiceListeners::RemoveModuleListener(ModuleContext* mc, const ModuleListener& listener) { MutexLocker lock(moduleListenerMapMutex); moduleListenerMap[mc].remove_if(std::bind1st(ModuleListenerCompare(), listener)); } 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)(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_ERROR << "Service listener" #ifdef US_MODULE_SUPPORT_ENABLED << " in " << l->GetModule()->GetName() #endif << " threw an exception!"; } } } //US_DEBUG << "Notified " << n << " listeners"; } void ServiceListeners::GetMatchingServiceListeners(const ServiceReference& sr, ServiceListenerEntries& set, bool lockProps) { MutexLocker lock(mutex); // Check complicated or empty listener filters int n = 0; for (std::list::const_iterator sse = complicatedListeners.begin(); sse != complicatedListeners.end(); ++sse) { ++n; if (sse->GetLDAPExpr().IsNull() || sse->GetLDAPExpr().Evaluate(sr.d->GetProperties(), false)) { set.insert(*sse); } } //US_DEBUG << "Added " << set.size() << " out of " << n // << " listeners with complicated filters"; // Check the cache const std::list c(any_cast > (sr.d->GetProperty(ServiceConstants::OBJECTCLASS(), lockProps))); for (std::list::const_iterator objClass = c.begin(); objClass != c.end(); ++objClass) { AddToSet(set, OBJECTCLASS_IX, *objClass); } long service_id = any_cast(sr.d->GetProperty(ServiceConstants::SERVICE_ID(), lockProps)); std::stringstream ss; ss << service_id; AddToSet(set, SERVICE_ID_IX, ss.str()); } void ServiceListeners::RemoveFromCache(const ServiceListenerEntry& sle) { if (!sle.GetLocalCache().empty()) { for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) { CacheType& keymap = cache[i]; std::vector& l = sle.GetLocalCache()[i]; for (std::vector::const_iterator it = l.begin(); it != l.end(); ++it) { std::list& sles = keymap[*it]; sles.remove(sle); if (sles.empty()) { keymap.erase(*it); } } } } else { complicatedListeners.remove(sle); } } void ServiceListeners::CheckSimple(const ServiceListenerEntry& sle) { if (sle.GetLDAPExpr().IsNull()) { complicatedListeners.push_back(sle); } else { LDAPExpr::LocalCache local_cache; if (sle.GetLDAPExpr().IsSimple(hashedServiceKeys, local_cache, false)) { sle.GetLocalCache() = local_cache; for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) { for (std::vector::const_iterator it = local_cache[i].begin(); it != local_cache[i].end(); ++it) { std::list& sles = cache[i][*it]; sles.push_back(sle); } } } else { //US_DEBUG << "Too complicated filter: " << sle.GetFilter(); complicatedListeners.push_back(sle); } } } void ServiceListeners::AddToSet(ServiceListenerEntries& set, int cache_ix, const std::string& val) { std::list& l = cache[cache_ix][val]; if (!l.empty()) { //US_DEBUG << hashedServiceKeys[cache_ix] << " matches " << l.size(); for (std::list::const_iterator entry = l.begin(); entry != l.end(); ++entry) { set.insert(*entry); } } else { //US_DEBUG << hashedServiceKeys[cache_ix] << " matches none"; } } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceProperties.h b/Core/Code/CppMicroServices/src/service/usServiceProperties.h index 94adc70f50..3d8d773259 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceProperties.h +++ b/Core/Code/CppMicroServices/src/service/usServiceProperties.h @@ -1,198 +1,200 @@ /*============================================================================= 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 +#include #include "usAny.h" - +/// \cond US_BEGIN_NAMESPACE struct ci_char_traits : public std::char_traits // just inherit all the other functions // that we don't need to override { static bool eq(char c1, char c2) { return std::toupper(c1) == std::toupper(c2); } static bool ne(char c1, char c2) { return std::toupper(c1) != std::toupper(c2); } static bool lt(char c1, char c2) { return std::toupper(c1) < std::toupper(c2); } static bool gt(char c1, char c2) { return std::toupper(c1) > std::toupper(c2); } static int compare(const char* s1, const char* s2, std::size_t n) { while (n-- > 0) { if (lt(*s1, *s2)) return -1; if (gt(*s1, *s2)) return 1; ++s1; ++s2; } return 0; } static const char* find(const char* s, int n, char a) { while (n-- > 0 && std::toupper(*s) != std::toupper(a)) { ++s; } return s; } }; class ci_string : public std::basic_string { private: typedef std::basic_string Super; public: inline ci_string() : Super() {} inline ci_string(const ci_string& cistr) : Super(cistr) {} inline ci_string(const ci_string& cistr, size_t pos, size_t n) : Super(cistr, pos, n) {} inline ci_string(const char* s, size_t n) : Super(s, n) {} inline ci_string(const char* s) : Super(s) {} inline ci_string(size_t n, char c) : Super(n, c) {} inline ci_string(const std::string& str) : Super(str.begin(), str.end()) {} template ci_string(InputIterator b, InputIterator e) : Super(b, e) {} inline operator std::string () const { return std::string(begin(), end()); } }; US_END_NAMESPACE US_HASH_FUNCTION_NAMESPACE_BEGIN US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ci_string)) std::string ls(arg); std::transform(ls.begin(), ls.end(), ls.begin(), ::tolower); using namespace US_HASH_FUNCTION_NAMESPACE; return US_HASH_FUNCTION(std::string, ls); US_HASH_FUNCTION_END US_HASH_FUNCTION_NAMESPACE_END +/// \endcond + US_BEGIN_NAMESPACE /** * \ingroup MicroServices * * A hash table based map class with case-insensitive keys. This class * uses ci_string as key type and Any as values. Due * to the conversion capabilities of ci_string, std::string objects * can be used transparantly to insert or retrieve key-value pairs. * *

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

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

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

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

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

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

* If the supplied property value is not of type int, it is * deemed to have a ranking value of zero. */ US_EXPORT const std::string& SERVICE_RANKING(); // = "service.ranking" } US_END_NAMESPACE #endif // US_SERVICE_PROPERTIES_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceReference.h b/Core/Code/CppMicroServices/src/service/usServiceReference.h index 4b2b7c644d..456191c375 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceReference.h +++ b/Core/Code/CppMicroServices/src/service/usServiceReference.h @@ -1,226 +1,226 @@ /*============================================================================= 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 #include #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4396) #endif US_BEGIN_NAMESPACE class Module; class ServiceRegistrationPrivate; class ServiceReferencePrivate; /** * \ingroup MicroServices * * A reference to a service. * *

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

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

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

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

* Property keys are case-insensitive. * *

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

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

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

* If this ServiceReference and the specified - * ServiceReference have the same {@link ServiceProperties::SERVICE_ID - * service id} they are equal. This ServiceReference is less + * ServiceReference have the same \link ServiceConstants::SERVICE_ID() + * service id\endlink they are equal. This ServiceReference is less * than the specified ServiceReference if it has a lower - * {@link ServiceProperties::SERVICE_RANKING service ranking} and greater if it has a + * {@link ServiceConstants::SERVICE_RANKING service ranking} and greater if it has a * higher service ranking. Otherwise, if this ServiceReference * and the specified ServiceReference have the same - * {@link ServiceProperties::SERVICE_RANKING service ranking}, this + * {@link ServiceConstants::SERVICE_RANKING service ranking}, this * ServiceReference is less than the specified * ServiceReference if it has a higher - * {@link ServiceProperties::SERVICE_ID service id} and greater if it has a lower + * {@link ServiceConstants::SERVICE_ID service id} and greater if it has a lower * service id. * * @param reference The ServiceReference to be compared. * @return Returns a false or true if this * ServiceReference is less than or greater * than the specified ServiceReference. */ bool operator<(const ServiceReference& reference) const; bool operator==(const ServiceReference& reference) const; ServiceReference& operator=(const ServiceReference& reference); private: friend class ModulePrivate; friend class ModuleContext; friend class ServiceFilter; friend class ServiceRegistrationPrivate; friend class ServiceListeners; friend class LDAPFilter; template friend class ServiceTracker; template friend class ServiceTrackerPrivate; template friend class ModuleAbstractTracked; US_HASH_FUNCTION_FRIEND(ServiceReference); std::size_t Hash() const; ServiceReference(ServiceRegistrationPrivate* reg); ServiceReferencePrivate* d; }; US_END_NAMESPACE #ifdef _MSC_VER #pragma warning(pop) #endif US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceReference)& serviceRef); US_HASH_FUNCTION_NAMESPACE_BEGIN US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceReference)) return arg.Hash(); US_HASH_FUNCTION_END US_HASH_FUNCTION_NAMESPACE_END #endif // USSERVICEREFERENCE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.h b/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.h index a8b83b3b91..5dfc241a84 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.h +++ b/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.h @@ -1,118 +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. =============================================================================*/ #ifndef USSERVICEREFERENCEPRIVATE_H #define USSERVICEREFERENCEPRIVATE_H -#include "usAtomicInt.h" +#include "usAtomicInt_p.h" #include "usServiceProperties.h" US_BEGIN_NAMESPACE class Module; class ServiceRegistrationPrivate; class ServiceReferencePrivate; /** * \ingroup MicroServices */ class ServiceReferencePrivate { public: ServiceReferencePrivate(ServiceRegistrationPrivate* reg); ~ServiceReferencePrivate(); /** * Get the service object. * * @param module requester of service. * @return Service requested or null in case of failure. */ US_BASECLASS_NAME* GetService(Module* module); /** * Unget the service object. * * @param module Module who wants remove service. * @param checkRefCounter If true decrement refence counter and remove service * if we reach zero. If false remove service without * checking refence counter. * @return True if service was remove or false if only refence counter was * decremented. */ bool UngetService(Module* module, bool checkRefCounter); /** * Get all properties registered with this service. * * @return A ServiceProperties object containing properties or being empty * if service has been removed. */ ServiceProperties GetProperties() const; /** * Returns the property value to which the specified property key is mapped * in the properties ServiceProperties object of the service * referenced by this ServiceReference object. * *

* Property keys are case-insensitive. * *

* This method must continue to return property values after the service has * been unregistered. This is so references to unregistered services can * still be interrogated. * * @param key The property key. * @param lock If true, access of the properties of the service * referenced by this ServiceReference object will be * synchronized. * @return The property value to which the key is mapped; an invalid Any * if there is no property named after the key. */ Any GetProperty(const std::string& key, bool lock) const; /** * Reference count for implicitly shared private implementation. */ AtomicInt ref; /** * Link to registration object for this reference. */ ServiceRegistrationPrivate* const registration; private: // purposely not implemented ServiceReferencePrivate(const ServiceReferencePrivate&); ServiceReferencePrivate& operator=(const ServiceReferencePrivate&); }; US_END_NAMESPACE #endif // USSERVICEREFERENCEPRIVATE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistration.h b/Core/Code/CppMicroServices/src/service/usServiceRegistration.h index 1592de8a4a..4861cb051d 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistration.h +++ b/Core/Code/CppMicroServices/src/service/usServiceRegistration.h @@ -1,191 +1,191 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USSERVICEREGISTRATION_H #define USSERVICEREGISTRATION_H #include "usServiceProperties.h" #include "usServiceReference.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4396) #endif US_BEGIN_NAMESPACE class ModulePrivate; /** * \ingroup MicroServices * * A registered service. * *

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

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

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

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

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

    *
  1. The service is removed from the framework service registry so that * it can no longer be obtained. *
  2. A service event of type {@link ServiceEvent#UNREGISTERING} is fired * so that modules using this service can release their use of the service. * Once delivery of the service event is complete, the * ServiceRegistration objects for the service may no longer be * used to get a service object for the service. *
  3. For each module whose use count for this service is greater than * zero:
    * The module's use count for this service is set to zero.
    * If the service was registered with a {@link ServiceFactory} object, the * ServiceFactory#UngetService method is called to release * the service object for the module. *
* * @throws std::logic_error If this * ServiceRegistration object has already been * unregistered or if it is invalid. * @see ModuleContext#UngetService * @see ServiceFactory#UngetService */ void Unregister(); bool operator<(const ServiceRegistration& o) const; bool operator==(const ServiceRegistration& registration) const; ServiceRegistration& operator=(const ServiceRegistration& registration); protected: friend class ServiceRegistry; friend class ServiceReferencePrivate; US_HASH_FUNCTION_FRIEND(ServiceRegistration); ServiceRegistration(ServiceRegistrationPrivate* registrationPrivate); ServiceRegistration(ModulePrivate* module, US_BASECLASS_NAME* service, const ServiceProperties& props); ServiceRegistrationPrivate* d; }; US_END_NAMESPACE #ifdef _MSC_VER #pragma warning(pop) #endif US_HASH_FUNCTION_NAMESPACE_BEGIN US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceRegistration)) return US_HASH_FUNCTION(US_PREPEND_NAMESPACE(ServiceRegistrationPrivate)*, arg.d); US_HASH_FUNCTION_END US_HASH_FUNCTION_NAMESPACE_END inline std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceRegistration)& /*reg*/) { return os << "US_PREPEND_NAMESPACE(ServiceRegistration) object"; } #endif // USSERVICEREGISTRATION_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.h b/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.h index ed3486094c..a2099c07f0 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.h +++ b/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.h @@ -1,143 +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. =============================================================================*/ #ifndef USSERVICEREGISTRATIONPRIVATE_H #define USSERVICEREGISTRATIONPRIVATE_H #include "usServiceReference.h" #include "usServiceProperties.h" -#include "usAtomicInt.h" +#include "usAtomicInt_p.h" US_BEGIN_NAMESPACE class ModulePrivate; class ServiceRegistration; /** * \ingroup MicroServices */ class ServiceRegistrationPrivate { protected: friend class ServiceRegistration; // The ServiceReferencePrivate class holds a pointer to a // ServiceRegistrationPrivate instance and needs to manipulate // its reference count. This way it can keep the ServiceRegistrationPrivate // instance alive and keep returning service properties for // unregistered service instances. friend class ServiceReferencePrivate; /** * Reference count for implicitly shared private implementation. */ AtomicInt ref; /** * Service or ServiceFactory object. */ US_BASECLASS_NAME* service; public: typedef Mutex MutexType; typedef MutexLock MutexLocker; typedef US_UNORDERED_MAP_TYPE ModuleToRefsMap; typedef US_UNORDERED_MAP_TYPE ModuleToServicesMap; /** * Modules dependent on this service. Integer is used as * reference counter, counting number of unbalanced getService(). */ ModuleToRefsMap dependents; /** * Object instances that factory has produced. */ ModuleToServicesMap serviceInstances; /** * Module registering this service. */ ModulePrivate* module; /** * Reference object to this service registration. */ ServiceReference reference; /** * Service properties. */ ServiceProperties properties; /** * Is service available. I.e., if true then holders * of a ServiceReference for the service are allowed to get it. */ volatile bool available; /** * Avoid recursive unregistrations. I.e., if true then * unregistration of this service has started but is not yet * finished. */ volatile bool unregistering; /** * Lock object for synchronous event delivery. */ MutexType eventLock; // needs to be recursive MutexType propsLock; ServiceRegistrationPrivate(ModulePrivate* module, US_BASECLASS_NAME* service, const ServiceProperties& props); ~ServiceRegistrationPrivate(); /** * Check if a module uses this service * * @param p Module to check * @return true if module uses this service */ bool IsUsedByModule(Module* m); US_BASECLASS_NAME* GetService(); private: // purposely not implemented ServiceRegistrationPrivate(const ServiceRegistrationPrivate&); ServiceRegistrationPrivate& operator=(const ServiceRegistrationPrivate&); }; US_END_NAMESPACE #endif // USSERVICEREGISTRATIONPRIVATE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistry_p.h b/Core/Code/CppMicroServices/src/service/usServiceRegistry_p.h index f160948bd9..6235296cd6 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistry_p.h +++ b/Core/Code/CppMicroServices/src/service/usServiceRegistry_p.h @@ -1,196 +1,196 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USSERVICEREGISTRY_H #define USSERVICEREGISTRY_H #include #include "usServiceRegistration.h" #include "usServiceProperties.h" -#include "usThreads.h" +#include "usThreads_p.h" US_BEGIN_NAMESPACE class CoreModuleContext; class ModulePrivate; /** * Here we handle all the US services that are registered. */ class ServiceRegistry { public: typedef Mutex MutexType; mutable MutexType mutex; /** * Creates a new ServiceProperties object containing in * with the keys converted to lower case. * * @param classes A list of class names which will be added to the * created ServiceProperties object under the key * ModuleConstants::OBJECTCLASS. * @param sid A service id which will be used instead of a default one. */ static ServiceProperties CreateServiceProperties(const ServiceProperties& in, const std::list& classes = std::list(), long sid = -1); typedef US_UNORDERED_MAP_TYPE > MapServiceClasses; typedef US_UNORDERED_MAP_TYPE > MapClassServices; /** * All registered services in the current framework. * Mapping of registered service to class names under which * the service is registerd. */ MapServiceClasses services; std::list serviceRegistrations; /** * Mapping of classname to registered service. * The List of registered services are ordered with the highest * ranked service first. */ MapClassServices classServices; CoreModuleContext* core; ServiceRegistry(CoreModuleContext* coreCtx); ~ServiceRegistry(); void Clear(); /** * Register a service in the framework wide register. * * @param module The module registering the service. * @param classes The class names under which the service can be located. * @param service The service object. * @param properties The properties for this service. * @return A ServiceRegistration object. * @exception std::invalid_argument If one of the following is true: *
    *
  • The service object is 0.
  • *
  • The service parameter is not a ServiceFactory or an * instance of all the named classes in the classes parameter.
  • *
*/ ServiceRegistration RegisterService(ModulePrivate* module, const std::list& clazzes, US_BASECLASS_NAME* service, const ServiceProperties& properties); /** * Service ranking changed, reorder registered services * according to ranking. * * @param serviceRegistration The ServiceRegistrationPrivate object. * @param rank New rank of object. */ void UpdateServiceRegistrationOrder(const ServiceRegistration& sr, const std::list& classes); /** * Checks that a given service object is an instance of the given * class name. * * @param service The service object to check. * @param cls The class name to check for. */ bool CheckServiceClass(US_BASECLASS_NAME* service, const std::string& cls) const; /** * Get all services implementing a certain class. * Only used internally by the framework. * * @param clazz The class name of the requested service. * @return A sorted list of {@link ServiceRegistrationPrivate} objects. */ void Get(const std::string& clazz, std::list& serviceRegs) const; /** * Get a service implementing a certain class. * * @param module The module requesting reference * @param clazz The class name of the requested service. * @return A {@link ServiceReference} object. */ ServiceReference Get(ModulePrivate* module, const std::string& clazz) const; /** * Get all services implementing a certain class and then * filter these with a property filter. * * @param clazz The class name of requested service. * @param filter The property filter. * @param module The module requesting reference. * @return A list of {@link ServiceReference} object. */ void Get(const std::string& clazz, const std::string& filter, ModulePrivate* module, std::list& serviceRefs) const; /** * Remove a registered service. * * @param sr The ServiceRegistration object that is registered. */ void RemoveServiceRegistration(const ServiceRegistration& sr) ; /** * Get all services that a module has registered. * * @param p The module * @return A set of {@link ServiceRegistration} objects */ void GetRegisteredByModule(ModulePrivate* m, std::list& serviceRegs) const; /** * Get all services that a module uses. * * @param p The module * @return A set of {@link ServiceRegistration} objects */ void GetUsedByModule(Module* m, std::list& serviceRegs) const; private: void Get_unlocked(const std::string& clazz, const std::string& filter, ModulePrivate* module, std::list& serviceRefs) const; // purposely not implemented ServiceRegistry(const ServiceRegistry&); ServiceRegistry& operator=(const ServiceRegistry&); }; US_END_NAMESPACE #endif // USSERVICEREGISTRY_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceTracker.h b/Core/Code/CppMicroServices/src/service/usServiceTracker.h index 3bdd535921..0a08b98e84 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceTracker.h +++ b/Core/Code/CppMicroServices/src/service/usServiceTracker.h @@ -1,433 +1,433 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USSERVICETRACKER_H #define USSERVICETRACKER_H #include #include "usServiceReference.h" #include "usServiceTrackerCustomizer.h" #include "usLDAPFilter.h" US_BEGIN_NAMESPACE template class TrackedService; template class ServiceTrackerPrivate; class ModuleContext; /** * \ingroup MicroServices * * The ServiceTracker class simplifies using services from the * framework's service registry. *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* This method can be overridden in a subclass. If the default * implementation of \link AddingService(const ServiceReference&) AddingService\endlink * method was used, this method must unget the service. * * @param reference The reference to removed service. * @param service The service object for the removed service. - * @see ServiceTrackerCustomizer::RemovedService(const ServiceReference&, itk::LighObject*) + * @see ServiceTrackerCustomizer::RemovedService(const ServiceReference&, T) */ void RemovedService(const ServiceReference& reference, T service); private: typedef ServiceTracker _ServiceTracker; typedef TrackedService _TrackedService; typedef ServiceTrackerPrivate _ServiceTrackerPrivate; typedef ServiceTrackerCustomizer _ServiceTrackerCustomizer; friend class TrackedService; friend class ServiceTrackerPrivate; _ServiceTrackerPrivate* const d; }; US_END_NAMESPACE #include "usServiceTracker.tpp" #endif // USSERVICETRACKER_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceTracker.tpp b/Core/Code/CppMicroServices/src/service/usServiceTracker.tpp index 165a8a758c..742291b621 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceTracker.tpp +++ b/Core/Code/CppMicroServices/src/service/usServiceTracker.tpp @@ -1,448 +1,448 @@ /*============================================================================= 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.h" +#include "usTrackedService_p.h" #include "usServiceException.h" #include "usModuleContext.h" #include #include US_BEGIN_NAMESPACE template ServiceTracker::~ServiceTracker() { Close(); delete d; } #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4355) #endif template ServiceTracker::ServiceTracker(ModuleContext* context, const ServiceReference& reference, _ServiceTrackerCustomizer* customizer) : d(new _ServiceTrackerPrivate(this, context, reference, customizer)) { } template ServiceTracker::ServiceTracker(ModuleContext* context, const std::string& clazz, _ServiceTrackerCustomizer* customizer) : d(new _ServiceTrackerPrivate(this, context, clazz, customizer)) { } template ServiceTracker::ServiceTracker(ModuleContext* context, const LDAPFilter& filter, _ServiceTrackerCustomizer* customizer) : d(new _ServiceTrackerPrivate(this, context, filter, customizer)) { } template ServiceTracker::ServiceTracker(ModuleContext *context, ServiceTrackerCustomizer *customizer) : d(new _ServiceTrackerPrivate(this, context, us_service_interface_iid(), customizer)) { const char* clazz = us_service_interface_iid(); if (clazz == 0) throw ServiceException("The service interface class has no US_DECLARE_SERVICE_INTERFACE macro"); } #ifdef _MSC_VER #pragma warning(pop) #endif template void ServiceTracker::Open() { _TrackedService* t; { typename _ServiceTrackerPrivate::Lock l(d); if (d->trackedService) { return; } US_DEBUG(d->DEBUG) << "ServiceTracker::Open: " << d->filter; t = new _TrackedService(this, d->customizer); { typename _TrackedService::Lock l(*t); try { d->context->AddServiceListener(t, &_TrackedService::ServiceChanged, d->listenerFilter); std::list references; if (!d->trackClass.empty()) { references = d->GetInitialReferences(d->trackClass, std::string()); } else { if (d->trackReference.GetModule() != 0) { references.push_back(d->trackReference); } else { /* user supplied filter */ references = d->GetInitialReferences(std::string(), (d->listenerFilter.empty()) ? d->filter.ToString() : d->listenerFilter); } } /* set tracked with the initial references */ t->SetInitial(references); } catch (const std::invalid_argument& e) { throw std::runtime_error(std::string("unexpected std::invalid_argument exception: ") + e.what()); } } d->trackedService = t; } /* Call tracked outside of synchronized region */ t->TrackInitial(); /* process the initial references */ } template void ServiceTracker::Close() { _TrackedService* outgoing; std::list references; { typename _ServiceTrackerPrivate::Lock l(d); outgoing = d->trackedService; if (outgoing == 0) { return; } US_DEBUG(d->DEBUG) << "ServiceTracker::close:" << d->filter; outgoing->Close(); GetServiceReferences(references); d->trackedService = 0; try { d->context->RemoveServiceListener(outgoing, &_TrackedService::ServiceChanged); } catch (const std::logic_error& /*e*/) { /* In case the context was stopped. */ } } d->Modified(); /* clear the cache */ { typename _TrackedService::Lock l(outgoing); outgoing->NotifyAll(); /* wake up any waiters */ } for(std::list::const_iterator ref = references.begin(); ref != references.end(); ++ref) { outgoing->Untrack(*ref, ServiceEvent()); } if (d->DEBUG) { typename _ServiceTrackerPrivate::Lock l(d); if ((d->cachedReference.GetModule() == 0) && (d->cachedService == 0)) { US_DEBUG(true) << "ServiceTracker::close[cached cleared]:" << d->filter; } } delete outgoing; d->trackedService = 0; } template T ServiceTracker::WaitForService(unsigned long timeoutMillis) { T object = GetService(); while (object == 0) { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return 0; } { typename _TrackedService::Lock l(t); if (t->Size() == 0) { t->Wait(timeoutMillis); } } object = GetService(); } return object; } template void ServiceTracker::GetServiceReferences(std::list& refs) const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return; } { typename _TrackedService::Lock l(t); d->GetServiceReferences_unlocked(refs, t); } } template ServiceReference ServiceTracker::GetServiceReference() const { ServiceReference reference(0); { typename _ServiceTrackerPrivate::Lock l(d); reference = d->cachedReference; } if (reference.GetModule() != 0) { US_DEBUG(d->DEBUG) << "ServiceTracker::getServiceReference[cached]:" << d->filter; return reference; } US_DEBUG(d->DEBUG) << "ServiceTracker::getServiceReference:" << d->filter; std::list references; GetServiceReferences(references); int length = references.size(); if (length == 0) { /* if no service is being tracked */ throw ServiceException("No service is being tracked"); } std::list::const_iterator selectedRef; if (length > 1) { /* if more than one service, select highest ranking */ std::vector rankings(length); int count = 0; int maxRanking = std::numeric_limits::min(); std::list::const_iterator refIter = references.begin(); for (int 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 (int i = 0; i < length; i++) { if (rankings[i] == maxRanking) { Any idAny = refIter->GetProperty(ServiceConstants::SERVICE_ID()); long int id = 0; if (idAny.Type() == typeid(long int)) { id = any_cast(idAny); } if (id < minId) { selectedRef = refIter; minId = id; } } ++refIter; } } } { typename _ServiceTrackerPrivate::Lock l(d); d->cachedReference = *selectedRef; return d->cachedReference; } } template T ServiceTracker::GetService(const ServiceReference& reference) const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return 0; } { typename _TrackedService::Lock l(t); return t->GetCustomizedObject(reference); } } template void ServiceTracker::GetServices(std::list& services) const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return; } { typename _TrackedService::Lock l(t); std::list references; d->GetServiceReferences_unlocked(references, t); for(std::list::const_iterator ref = references.begin(); ref != references.end(); ++ref) { services.push_back(t->GetCustomizedObject(*ref)); } } } template T ServiceTracker::GetService() const { T service = d->cachedService; if (service != 0) { US_DEBUG(d->DEBUG) << "ServiceTracker::getService[cached]:" << d->filter; return service; } US_DEBUG(d->DEBUG) << "ServiceTracker::getService:" << d->filter; try { ServiceReference reference = GetServiceReference(); if (reference.GetModule() == 0) { return 0; } return d->cachedService = GetService(reference); } catch (const ServiceException&) { return 0; } } template void ServiceTracker::Remove(const ServiceReference& reference) { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return; } t->Untrack(reference, ServiceEvent()); } template int ServiceTracker::Size() const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return 0; } { typename _TrackedService::Lock l(t); return t->Size(); } } template int ServiceTracker::GetTrackingCount() const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return -1; } { typename _TrackedService::Lock l(t); return t->GetTrackingCount(); } } template void ServiceTracker::GetTracked(TrackingMap& map) const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return; } { typename _TrackedService::Lock l(t); t->CopyEntries(map); } } template bool ServiceTracker::IsEmpty() const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return true; } { typename _TrackedService::Lock l(t); return t->IsEmpty(); } } template T ServiceTracker::AddingService(const ServiceReference& reference) { return dynamic_cast(d->context->GetService(reference)); } template void ServiceTracker::ModifiedService(const ServiceReference& /*reference*/, T /*service*/) { /* do nothing */ } template void ServiceTracker::RemovedService(const ServiceReference& reference, T /*service*/) { d->context->UngetService(reference); } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.tpp b/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.tpp index f34434c7c9..5346e14b40 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.tpp +++ b/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.tpp @@ -1,144 +1,144 @@ /*============================================================================= 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.h" +#include "usTrackedService_p.h" #include "usModuleContext.h" #include "usLDAPFilter.h" #include US_BEGIN_NAMESPACE template const bool ServiceTrackerPrivate::DEBUG = true; template ServiceTrackerPrivate::ServiceTrackerPrivate( ServiceTracker* st, ModuleContext* context, const ServiceReference& reference, ServiceTrackerCustomizer* customizer) : context(context), customizer(customizer), trackReference(reference), trackedService(0), cachedReference(0), cachedService(0), q_ptr(st) { this->customizer = customizer ? customizer : q_func(); std::stringstream ss; ss << "(" << ServiceConstants::SERVICE_ID() << "=" << any_cast(reference.GetProperty(ServiceConstants::SERVICE_ID())) << ")"; this->listenerFilter = ss.str(); try { this->filter = LDAPFilter(listenerFilter); } catch (const std::invalid_argument& e) { /* * we could only get this exception if the ServiceReference was * invalid */ std::invalid_argument ia(std::string("unexpected std::invalid_argument exception: ") + e.what()); throw ia; } } template ServiceTrackerPrivate::ServiceTrackerPrivate( ServiceTracker* st, ModuleContext* context, const std::string& clazz, ServiceTrackerCustomizer* customizer) : context(context), customizer(customizer), trackClass(clazz), trackReference(0), trackedService(0), cachedReference(0), cachedService(0), q_ptr(st) { this->customizer = customizer ? customizer : q_func(); this->listenerFilter = std::string("(") + US_PREPEND_NAMESPACE(ServiceConstants)::OBJECTCLASS() + "=" + clazz + ")"; try { this->filter = LDAPFilter(listenerFilter); } catch (const std::invalid_argument& e) { /* * we could only get this exception if the clazz argument was * malformed */ std::invalid_argument ia( std::string("unexpected std::invalid_argument exception: ") + e.what()); throw ia; } } template ServiceTrackerPrivate::ServiceTrackerPrivate( ServiceTracker* st, ModuleContext* context, const LDAPFilter& filter, ServiceTrackerCustomizer* customizer) : context(context), filter(filter), customizer(customizer), listenerFilter(filter.ToString()), trackReference(0), trackedService(0), cachedReference(0), cachedService(0), q_ptr(st) { this->customizer = customizer ? customizer : q_func(); if (context == 0) { throw std::invalid_argument("The module context cannot be null."); } } template ServiceTrackerPrivate::~ServiceTrackerPrivate() { } template std::list ServiceTrackerPrivate::GetInitialReferences( const std::string& className, const std::string& filterString) { return context->GetServiceReferences(className, filterString); } template void ServiceTrackerPrivate::GetServiceReferences_unlocked(std::list& refs, TrackedService* t) const { if (t->Size() == 0) { return; } t->GetTracked(refs); } template TrackedService* ServiceTrackerPrivate::Tracked() const { return trackedService; } template void ServiceTrackerPrivate::Modified() { cachedReference = 0; /* clear cached value */ cachedService = 0; /* clear cached value */ US_DEBUG(DEBUG) << "ServiceTracker::Modified(): " << filter; } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usTrackedServiceListener.h b/Core/Code/CppMicroServices/src/service/usTrackedServiceListener_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/service/usTrackedServiceListener.h rename to Core/Code/CppMicroServices/src/service/usTrackedServiceListener_p.h diff --git a/Core/Code/CppMicroServices/src/service/usTrackedService.h b/Core/Code/CppMicroServices/src/service/usTrackedService_p.h similarity index 97% rename from Core/Code/CppMicroServices/src/service/usTrackedService.h rename to Core/Code/CppMicroServices/src/service/usTrackedService_p.h index fc63cc6a06..41295a1c68 100644 --- a/Core/Code/CppMicroServices/src/service/usTrackedService.h +++ b/Core/Code/CppMicroServices/src/service/usTrackedService_p.h @@ -1,107 +1,107 @@ /*============================================================================= 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.h" -#include "usModuleAbstractTracked.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 US module system. */ template class TrackedService : public TrackedServiceListener, public ModuleAbstractTracked { public: TrackedService(ServiceTracker* serviceTracker, ServiceTrackerCustomizer* customizer); /** * Method connected to service events for the * ServiceTracker class. This method must NOT be * synchronized to avoid deadlock potential. * * @param event ServiceEvent object from the framework. */ void ServiceChanged(const ServiceEvent event); private: typedef ModuleAbstractTracked Superclass; ServiceTracker* serviceTracker; ServiceTrackerCustomizer* customizer; /** * Increment the tracking count and tell the tracker there was a * modification. * * @GuardedBy this */ void Modified(); /** * Call the specific customizer adding method. This method must not be * called while synchronized on this object. * * @param item Item to be tracked. * @param related Action related object. * @return Customized object for the tracked item or null * if the item is not to be tracked. */ T CustomizerAdding(ServiceReference item, const ServiceEvent& related); /** * Call the specific customizer modified method. This method must not be * called while synchronized on this object. * * @param item Tracked item. * @param related Action related object. * @param object Customized object for the tracked item. */ void CustomizerModified(ServiceReference item, const ServiceEvent& related, T object) ; /** * Call the specific customizer removed method. This method must not be * called while synchronized on this object. * * @param item Tracked item. * @param related Action related object. * @param object Customized object for the tracked item. */ void CustomizerRemoved(ServiceReference item, const ServiceEvent& related, T object) ; }; US_END_NAMESPACE #include "usTrackedService.tpp" #endif // USTRACKEDSERVICE_H diff --git a/Core/Code/CppMicroServices/src/util/usAny.cpp b/Core/Code/CppMicroServices/src/util/usAny.cpp index 6b9b08d7bf..fbfd8eb1ab 100644 --- a/Core/Code/CppMicroServices/src/util/usAny.cpp +++ b/Core/Code/CppMicroServices/src/util/usAny.cpp @@ -1,55 +1,56 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usAny.h" US_BEGIN_NAMESPACE template std::string container_to_string(Iterator i1, Iterator i2) { std::stringstream ss; ss << "("; const Iterator begin = i1; for ( ; i1 != i2; ++i1) { if (i1 == begin) ss << *i1; else ss << "," << *i1; } + ss << ")"; return ss.str(); } std::string any_value_to_string(const std::vector& val) { return container_to_string(val.begin(), val.end()); } std::string any_value_to_string(const std::list& val) { return container_to_string(val.begin(), val.end()); } std::string any_value_to_string(const std::vector& val) { return container_to_string(val.begin(), val.end()); } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/util/usAny.h b/Core/Code/CppMicroServices/src/util/usAny.h index 5c946d670c..867c6523cd 100644 --- a/Core/Code/CppMicroServices/src/util/usAny.h +++ b/Core/Code/CppMicroServices/src/util/usAny.h @@ -1,398 +1,400 @@ /*============================================================================= 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 US. */ class Any { public: /** * Creates an empty any type. */ Any(): _content(0) { } /** * Creates an Any which stores the init parameter inside. * * \param value The content of the Any * * Example: * \code * Any a(13); * Any a(string("12345")); * \endcode */ template Any(const ValueType& value) : _content(new Holder(value)) { } /** * Copy constructor, works with empty Anys and initialized Any values. * * \param other The Any to copy */ Any(const Any& other) : _content(other._content ? other._content->Clone() : 0) { } ~Any() { delete _content; } /** * Swaps the content of the two Anys. * * \param rhs The Any to swap this Any with. */ Any& Swap(Any& rhs) { std::swap(_content, rhs._content); return *this; } /** * Assignment operator for all types != Any. * * \param rhs The value which should be assigned to this Any. * * Example: * \code * Any a = 13; * Any a = string("12345"); * \endcode */ template Any& operator = (const ValueType& rhs) { Any(rhs).Swap(*this); return *this; } /** * Assignment operator for Any. * * \param rhs The Any which should be assigned to this Any. */ Any& operator = (const Any& rhs) { Any(rhs).Swap(*this); return *this; } /** * returns true if the Any is empty */ bool Empty() const { return !_content; } /** * Returns a string representation for the content. * * Custom types should either provide a std::ostream& operator<<(std::ostream& os, const CustomType& ct) * function or specialize the any_value_to_string template function for meaningful output. */ std::string ToString() const { return _content->ToString(); } /** * Returns the type information of the stored content. * If the Any is empty typeid(void) is returned. * It is suggested to always query an Any for its type info before trying to extract * data via an any_cast/ref_any_cast. */ const std::type_info& Type() const { return _content ? _content->Type() : typeid(void); } private: class Placeholder { public: virtual ~Placeholder() { } virtual std::string ToString() const = 0; virtual const std::type_info& Type() const = 0; virtual Placeholder* Clone() const = 0; }; template class Holder: public Placeholder { public: Holder(const ValueType& value) : _held(value) { } virtual std::string ToString() const { return any_value_to_string(_held); } virtual const std::type_info& Type() const { return typeid(ValueType); } virtual Placeholder* Clone() const { return new Holder(_held); } ValueType _held; private: // intentionally left unimplemented Holder& operator=(const Holder &); }; private: template friend ValueType* any_cast(Any*); template friend ValueType* unsafe_any_cast(Any*); Placeholder* _content; }; class BadAnyCastException : public std::bad_cast { public: BadAnyCastException(const std::string& msg = "") : std::bad_cast(), _msg(msg) {} ~BadAnyCastException() throw() {} virtual const char * what() const throw() { if (_msg.empty()) return "US_PREPEND_NAMESPACE(BadAnyCastException): " "failed conversion using US_PREPEND_NAMESPACE(any_cast)"; else return _msg.c_str(); } private: std::string _msg; }; /** * any_cast operator used to extract the ValueType from an Any*. Will return a pointer * to the stored value. * * Example Usage: * \code * MyType* pTmp = any_cast(pAny) * \endcode * Will return NULL if the cast fails, i.e. types don't match. */ template ValueType* any_cast(Any* operand) { return operand && operand->Type() == typeid(ValueType) ? &static_cast*>(operand->_content)->_held : 0; } /** * any_cast operator used to extract a const ValueType pointer from an const Any*. Will return a const pointer * to the stored value. * * Example Usage: * \code * const MyType* pTmp = any_cast(pAny) * \endcode * Will return NULL if the cast fails, i.e. types don't match. */ template const ValueType* any_cast(const Any* operand) { return any_cast(const_cast(operand)); } /** * any_cast operator used to extract a copy of the ValueType from an const Any&. * * Example Usage: * \code * MyType tmp = any_cast(anAny) * \endcode * Will throw a BadCastException if the cast fails. * Dont use an any_cast in combination with references, i.e. MyType& tmp = ... or const MyType& = ... * Some compilers will accept this code although a copy is returned. Use the ref_any_cast in * these cases. */ template ValueType any_cast(const Any& operand) { ValueType* result = any_cast(const_cast(&operand)); if (!result) throw BadAnyCastException("Failed to convert between const Any types"); return *result; } /** * any_cast operator used to extract a copy of the ValueType from an Any&. * * Example Usage: * \code * MyType tmp = any_cast(anAny) * \endcode * Will throw a BadCastException if the cast fails. * Dont use an any_cast in combination with references, i.e. MyType& tmp = ... or const MyType& tmp = ... * Some compilers will accept this code although a copy is returned. Use the ref_any_cast in * these cases. */ template ValueType any_cast(Any& operand) { ValueType* result = any_cast(&operand); if (!result) throw BadAnyCastException("Failed to convert between Any types"); return *result; } /** * ref_any_cast operator used to return a const reference to the internal data. * * Example Usage: * \code * const MyType& tmp = ref_any_cast(anAny); * \endcode */ template const ValueType& ref_any_cast(const Any & operand) { ValueType* result = any_cast(const_cast(&operand)); if (!result) throw BadAnyCastException("RefAnyCast: Failed to convert between const Any types"); return *result; } /** * ref_any_cast operator used to return a reference to the internal data. * * Example Usage: * \code * MyType& tmp = ref_any_cast(anAny); * \endcode */ template ValueType& ref_any_cast(Any& operand) { ValueType* result = any_cast(&operand); if (!result) throw BadAnyCastException("RefAnyCast: Failed to convert between Any types"); return *result; } /** * \internal * * The "unsafe" versions of any_cast are not part of the * public interface and may be removed at any time. They are * required where we know what type is stored in the any and can't * use typeid() comparison, e.g., when our types may travel across * different shared libraries. */ template ValueType* unsafe_any_cast(Any* operand) { return &static_cast*>(operand->_content)->_held; } /** * \internal * * The "unsafe" versions of any_cast are not part of the * public interface and may be removed at any time. They are * required where we know what type is stored in the any and can't * use typeid() comparison, e.g., when our types may travel across * different shared libraries. */ template const ValueType* unsafe_any_cast(const Any* operand) { return any_cast(const_cast(operand)); } US_EXPORT std::string any_value_to_string(const std::vector& val); template std::string any_value_to_string(const T& val) { std::stringstream ss; ss << val; return ss.str(); } US_END_NAMESPACE inline std::ostream& operator<< (std::ostream& os, const US_PREPEND_NAMESPACE(Any)& any) { return os << any.ToString(); } #endif // US_ANY_H diff --git a/Core/Code/CppMicroServices/src/util/usAtomicInt.h b/Core/Code/CppMicroServices/src/util/usAtomicInt_p.h similarity index 98% rename from Core/Code/CppMicroServices/src/util/usAtomicInt.h rename to Core/Code/CppMicroServices/src/util/usAtomicInt_p.h index 3ed5c2859a..4bc954ec02 100644 --- a/Core/Code/CppMicroServices/src/util/usAtomicInt.h +++ b/Core/Code/CppMicroServices/src/util/usAtomicInt_p.h @@ -1,83 +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. =============================================================================*/ #ifndef USATOMICINT_H #define USATOMICINT_H #include -#include "usThreads.h" +#include "usThreads_p.h" US_BEGIN_NAMESPACE /** * This class acts as an atomic integer. * * The integer value represented by this class can be incremented * and decremented atomically. This is often useful in reference * counting scenarios to minimize locking overhead in multi-threaded * environments. */ class AtomicInt : private US_DEFAULT_THREADING { public: AtomicInt(int value = 0) : m_ReferenceCount(value) {} /** * Increase the reference count atomically by 1. * * \return true if the new value is unequal to zero, false * otherwise. */ inline bool Ref() const { return AtomicIncrement(m_ReferenceCount) != 0; } /** * Decrease the reference count atomically by 1. * * \return true if the new value is unequal to zero, false * otherwise. */ inline bool Deref() const { return AtomicDecrement(m_ReferenceCount) != 0; } /** * Returns the current value. * */ inline operator int() const { IntType curr(0); AtomicAssign(curr, m_ReferenceCount); return curr; } private: mutable IntType m_ReferenceCount; }; US_END_NAMESPACE #endif // USATOMICINT_H diff --git a/Core/Code/CppMicroServices/src/util/usExportMacros.h b/Core/Code/CppMicroServices/src/util/usExportMacros_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usExportMacros.h rename to Core/Code/CppMicroServices/src/util/usExportMacros_p.h diff --git a/Core/Code/CppMicroServices/src/util/usFunctor.h b/Core/Code/CppMicroServices/src/util/usFunctor_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usFunctor.h rename to Core/Code/CppMicroServices/src/util/usFunctor_p.h diff --git a/Core/Code/CppMicroServices/src/util/usSharedData.h b/Core/Code/CppMicroServices/src/util/usSharedData.h index dfca6fb58b..31e90a595e 100644 --- a/Core/Code/CppMicroServices/src/util/usSharedData.h +++ b/Core/Code/CppMicroServices/src/util/usSharedData.h @@ -1,267 +1,276 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Modified version of qshareddata.h from Qt 4.7.3 for CppMicroServices. Original copyright (c) Nokia Corporation. Usage covered by the GNU Lesser General Public License version 2.1 (http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html) and the Nokia Qt LGPL Exception version 1.1 (file LGPL_EXCEPTION.txt in Qt 4.7.3 package). =========================================================================*/ #ifndef USSHAREDDATA_H #define USSHAREDDATA_H -#include "usAtomicInt.h" +#include "usAtomicInt_p.h" #include #include -#include +#include US_BEGIN_NAMESPACE +/** + * \ingroup MicroServicesUtils + */ class SharedData { public: mutable AtomicInt ref; inline SharedData() : ref(0) { } inline SharedData(const SharedData&) : ref(0) { } private: // using the assignment operator would lead to corruption in the ref-counting SharedData& operator=(const SharedData&); }; +/** + * \ingroup MicroServicesUtils + */ template class SharedDataPointer { public: typedef T Type; typedef T* pointer; inline void Detach() { if (d && d->ref != 1) Detach_helper(); } inline T& operator*() { Detach(); return *d; } inline const T& operator*() const { return *d; } inline T* operator->() { Detach(); return d; } inline const T* operator->() const { return d; } inline operator T*() { Detach(); return d; } inline operator const T*() const { return d; } inline T* Data() { Detach(); return d; } inline const T* Data() const { return d; } inline const T* ConstData() const { return d; } inline bool operator==(const SharedDataPointer& other) const { return d == other.d; } inline bool operator!=(const SharedDataPointer& other) const { return d != other.d; } inline SharedDataPointer() : d(0) { } inline ~SharedDataPointer() { if (d && !d->ref.Deref()) delete d; } explicit SharedDataPointer(T* data); inline SharedDataPointer(const SharedDataPointer& o) : d(o.d) { if (d) d->ref.Ref(); } inline SharedDataPointer & operator=(const SharedDataPointer& o) { if (o.d != d) { if (o.d) o.d->ref.Ref(); T *old = d; d = o.d; if (old && !old->ref.Deref()) delete old; } return *this; } inline SharedDataPointer &operator=(T *o) { if (o != d) { if (o) o->ref.Ref(); T *old = d; d = o; if (old && !old->ref.Deref()) delete old; } return *this; } inline bool operator!() const { return !d; } inline void Swap(SharedDataPointer& other) { using std::swap; swap(d, other.d); } protected: T* Clone(); private: void Detach_helper(); T *d; }; +/** + * \ingroup MicroServicesUtils + */ template class ExplicitlySharedDataPointer { public: typedef T Type; typedef T* pointer; inline T& operator*() const { return *d; } inline T* operator->() { return d; } inline T* operator->() const { return d; } inline T* Data() const { return d; } inline const T* ConstData() const { return d; } inline void Detach() { if (d && d->ref != 1) Detach_helper(); } inline void Reset() { if(d && !d->ref.Deref()) delete d; d = 0; } inline operator bool () const { return d != 0; } inline bool operator==(const ExplicitlySharedDataPointer& other) const { return d == other.d; } inline bool operator!=(const ExplicitlySharedDataPointer& other) const { return d != other.d; } inline bool operator==(const T* ptr) const { return d == ptr; } inline bool operator!=(const T* ptr) const { return d != ptr; } inline ExplicitlySharedDataPointer() { d = 0; } inline ~ExplicitlySharedDataPointer() { if (d && !d->ref.Deref()) delete d; } explicit ExplicitlySharedDataPointer(T* data); inline ExplicitlySharedDataPointer(const ExplicitlySharedDataPointer &o) : d(o.d) { if (d) d->ref.Ref(); } template inline ExplicitlySharedDataPointer(const ExplicitlySharedDataPointer& o) : d(static_cast(o.Data())) { if(d) d->ref.Ref(); } inline ExplicitlySharedDataPointer& operator=(const ExplicitlySharedDataPointer& o) { if (o.d != d) { if (o.d) o.d->ref.Ref(); T *old = d; d = o.d; if (old && !old->ref.Deref()) delete old; } return *this; } inline ExplicitlySharedDataPointer& operator=(T* o) { if (o != d) { if (o) o->ref.Ref(); T *old = d; d = o; if (old && !old->ref.Deref()) delete old; } return *this; } inline bool operator!() const { return !d; } inline void Swap(ExplicitlySharedDataPointer& other) { using std::swap; swap(d, other.d); } protected: T* Clone(); private: void Detach_helper(); T *d; }; template SharedDataPointer::SharedDataPointer(T* adata) : d(adata) { if (d) d->ref.Ref(); } template T* SharedDataPointer::Clone() { return new T(*d); } template void SharedDataPointer::Detach_helper() { T *x = Clone(); x->ref.Ref(); if (!d->ref.Deref()) delete d; d = x; } template T* ExplicitlySharedDataPointer::Clone() { return new T(*d); } template void ExplicitlySharedDataPointer::Detach_helper() { T *x = Clone(); x->ref.Ref(); if (!d->ref.Deref()) delete d; d = x; } template ExplicitlySharedDataPointer::ExplicitlySharedDataPointer(T* adata) : d(adata) { if (d) d->ref.Ref(); } template void swap(US_PREPEND_NAMESPACE(SharedDataPointer& p1, US_PREPEND_NAMESPACE(SharedDataPointer& p2) { p1.Swap(p2); } template void swap(US_PREPEND_NAMESPACE(ExplicitlySharedDataPointer& p1, US_PREPEND_NAMESPACE(ExplicitlySharedDataPointer& p2) { p1.Swap(p2); } US_END_NAMESPACE #endif // USSHAREDDATA_H diff --git a/Core/Code/CppMicroServices/src/util/usStaticInit.h b/Core/Code/CppMicroServices/src/util/usStaticInit_p.h similarity index 99% rename from Core/Code/CppMicroServices/src/util/usStaticInit.h rename to Core/Code/CppMicroServices/src/util/usStaticInit_p.h index f639104efb..b69d45c61d 100644 --- a/Core/Code/CppMicroServices/src/util/usStaticInit.h +++ b/Core/Code/CppMicroServices/src/util/usStaticInit_p.h @@ -1,166 +1,166 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Extracted from qglobal.h from Qt 4.7.3 and adapted for CppMicroServices. Original copyright (c) Nokia Corporation. Usage covered by the GNU Lesser General Public License version 2.1 (http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html) and the Nokia Qt LGPL Exception version 1.1 (file LGPL_EXCEPTION.txt in Qt 4.7.3 package). =========================================================================*/ #ifndef US_STATIC_INIT_H #define US_STATIC_INIT_H #include -#include "usThreads.h" +#include "usThreads_p.h" US_BEGIN_NAMESPACE // POD for US_GLOBAL_STATIC template class GlobalStatic : public US_DEFAULT_THREADING > { public: GlobalStatic(T* p = 0, bool destroyed = false) : pointer(p), destroyed(destroyed) {} T* pointer; bool destroyed; private: // purposely not implemented GlobalStatic(const GlobalStatic&); GlobalStatic& operator=(const GlobalStatic&); }; template struct DefaultGlobalStaticDeleter { void operator()(GlobalStatic& globalStatic) const { delete globalStatic.pointer; globalStatic.pointer = 0; globalStatic.destroyed = true; } }; // Created as a function-local static to delete a GlobalStatic template class Deleter = DefaultGlobalStaticDeleter> class GlobalStaticDeleter { public: GlobalStatic &globalStatic; GlobalStaticDeleter(GlobalStatic &_globalStatic) : globalStatic(_globalStatic) { } inline ~GlobalStaticDeleter() { Deleter deleter; deleter(globalStatic); } }; US_END_NAMESPACE #define US_GLOBAL_STATIC_INIT(TYPE, NAME) \ static US_PREPEND_NAMESPACE(GlobalStatic)& this_##NAME() \ { \ static US_PREPEND_NAMESPACE(GlobalStatic) l; \ return l; \ } #define US_GLOBAL_STATIC(TYPE, NAME) \ US_GLOBAL_STATIC_INIT(TYPE, NAME) \ static TYPE *NAME() \ { \ if (!this_##NAME().pointer && !this_##NAME().destroyed) \ { \ TYPE *x = new TYPE; \ bool ok = false; \ { \ US_PREPEND_NAMESPACE(GlobalStatic)::Lock lock(this_##NAME()); \ if (!this_##NAME().pointer) \ { \ this_##NAME().pointer = x; \ ok = true; \ } \ } \ if (!ok) \ delete x; \ else \ static US_PREPEND_NAMESPACE(GlobalStaticDeleter) cleanup(this_##NAME()); \ } \ return this_##NAME().pointer; \ } #define US_GLOBAL_STATIC_WITH_DELETER(TYPE, NAME, DELETER) \ US_GLOBAL_STATIC_INIT(TYPE, NAME) \ static TYPE *NAME() \ { \ if (!this_##NAME().pointer && !this_##NAME().destroyed) \ { \ TYPE *x = new TYPE; \ bool ok = false; \ { \ US_PREPEND_NAMESPACE(GlobalStatic)::Lock lock(this_##NAME()); \ if (!this_##NAME().pointer) \ { \ this_##NAME().pointer = x; \ ok = true; \ } \ } \ if (!ok) \ delete x; \ else \ static US_PREPEND_NAMESPACE(GlobalStaticDeleter) cleanup(this_##NAME()); \ } \ return this_##NAME().pointer; \ } #define US_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ARGS) \ US_GLOBAL_STATIC_INIT(TYPE, NAME) \ static TYPE *NAME() \ { \ if (!this_##NAME().pointer && !this_##NAME().destroyed) \ { \ TYPE *x = new TYPE ARGS; \ bool ok = false; \ { \ US_PREPEND_NAMESPACE(GlobalStatic)::Lock lock(this_##NAME()); \ if (!this_##NAME().pointer) \ { \ this_##NAME().pointer = x; \ ok = true; \ } \ } \ if (!ok) \ delete x; \ else \ static US_PREPEND_NAMESPACE(GlobalStaticDeleter) cleanup(this_##NAME()); \ } \ return this_##NAME().pointer; \ } #endif // US_STATIC_INIT_H diff --git a/Core/Code/CppMicroServices/src/util/usThreads.cpp b/Core/Code/CppMicroServices/src/util/usThreads.cpp index 5ce01ae03d..f26bc0c023 100644 --- a/Core/Code/CppMicroServices/src/util/usThreads.cpp +++ b/Core/Code/CppMicroServices/src/util/usThreads.cpp @@ -1,255 +1,255 @@ /*============================================================================= 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.h" +#include "usThreads_p.h" -#include "usUtils.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.h b/Core/Code/CppMicroServices/src/util/usThreads_p.h similarity index 99% rename from Core/Code/CppMicroServices/src/util/usThreads.h rename to Core/Code/CppMicroServices/src/util/usThreads_p.h index df96473022..0e3cbf2403 100644 --- a/Core/Code/CppMicroServices/src/util/usThreads.h +++ b/Core/Code/CppMicroServices/src/util/usThreads_p.h @@ -1,432 +1,431 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USTHREADINGMODEL_H #define USTHREADINGMODEL_H #include -#include "usExportMacros.h" +#include "usExportMacros_p.h" #ifdef US_ENABLE_THREADING_SUPPORT // Atomic compiler intrinsics #if defined(US_PLATFORM_APPLE) // OSAtomic.h optimizations only used in 10.5 and later #include #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 #include #define US_ATOMIC_OPTIMIZATION_APPLE #endif #elif defined(__GLIBCPP__) || defined(__GLIBCXX__) #if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) # include #else # include #endif #define US_ATOMIC_OPTIMIZATION_GNUC #endif // Mutex support #ifdef US_PLATFORM_WINDOWS - #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef NOMINMAX #define NOMINMAX #endif #include #define US_THREADS_MUTEX(x) HANDLE (x); #define US_THREADS_MUTEX_INIT(x) #define US_THREADS_MUTEX_CTOR(x) : x(::CreateMutex(NULL, FALSE, NULL)) #define US_THREADS_MUTEX_DELETE(x) ::CloseHandle (x) #define US_THREADS_MUTEX_LOCK(x) ::WaitForSingleObject (x, INFINITE) #define US_THREADS_MUTEX_UNLOCK(x) ::ReleaseMutex (x) #define US_THREADS_LONG LONG #define US_ATOMIC_OPTIMIZATION #define US_ATOMIC_INCREMENT(x) IntType n = InterlockedIncrement(x) #define US_ATOMIC_DECREMENT(x) IntType n = InterlockedDecrement(x) #define US_ATOMIC_ASSIGN(l, r) InterlockedExchange(l, r) #elif defined(US_PLATFORM_POSIX) #include #define US_THREADS_MUTEX(x) pthread_mutex_t (x); #define US_THREADS_MUTEX_INIT(x) ::pthread_mutex_init(&x, 0) #define US_THREADS_MUTEX_CTOR(x) : x() #define US_THREADS_MUTEX_DELETE(x) ::pthread_mutex_destroy (&x) #define US_THREADS_MUTEX_LOCK(x) ::pthread_mutex_lock (&x) #define US_THREADS_MUTEX_UNLOCK(x) ::pthread_mutex_unlock (&x) #define US_ATOMIC_OPTIMIZATION #if defined(US_ATOMIC_OPTIMIZATION_APPLE) #if defined (__LP64__) && __LP64__ #define US_THREADS_LONG volatile int64_t #define US_ATOMIC_INCREMENT(x) IntType n = OSAtomicIncrement64Barrier(x) #define US_ATOMIC_DECREMENT(x) IntType n = OSAtomicDecrement64Barrier(x) #define US_ATOMIC_ASSIGN(l, v) OSAtomicCompareAndSwap64Barrier(*l, v, l) #else #define US_THREADS_LONG volatile int32_t #define US_ATOMIC_INCREMENT(x) IntType n = OSAtomicIncrement32Barrier(x) #define US_ATOMIC_DECREMENT(x) IntType n = OSAtomicDecrement32Barrier(x) #define US_ATOMIC_ASSIGN(l, v) OSAtomicCompareAndSwap32Barrier(*l, v, l) #endif #elif defined(US_ATOMIC_OPTIMIZATION_GNUC) #define US_THREADS_LONG _Atomic_word #define US_ATOMIC_INCREMENT(x) IntType n = __sync_add_and_fetch(x, 1) #define US_ATOMIC_DECREMENT(x) IntType n = __sync_add_and_fetch(x, -1) #define US_ATOMIC_ASSIGN(l, v) __sync_val_compare_and_swap(l, *l, v) #else #define US_THREADS_LONG long #undef US_ATOMIC_OPTIMIZATION #define US_ATOMIC_INCREMENT(x) m_AtomicMtx.Lock(); \ IntType n = ++(*x); \ m_AtomicMtx.Unlock() #define US_ATOMIC_DECREMENT(x) m_AtomicMtx.Lock(); \ IntType n = --(*x); \ m_AtomicMtx.Unlock() #define US_ATOMIC_ASSIGN(l, v) m_AtomicMtx.Lock(); \ *l = v; \ m_AtomicMtx.Unlock() #endif #endif #else // single threaded #define US_THREADS_MUTEX(x) #define US_THREADS_MUTEX_INIT(x) #define US_THREADS_MUTEX_CTOR(x) #define US_THREADS_MUTEX_DELETE(x) #define US_THREADS_MUTEX_LOCK(x) #define US_THREADS_MUTEX_UNLOCK(x) #define US_THREADS_LONG #endif #ifndef US_DEFAULT_MUTEX #define US_DEFAULT_MUTEX US_PREPEND_NAMESPACE(Mutex) #endif US_BEGIN_NAMESPACE class Mutex { public: Mutex() US_THREADS_MUTEX_CTOR(m_Mtx) { US_THREADS_MUTEX_INIT(m_Mtx); } ~Mutex() { US_THREADS_MUTEX_DELETE(m_Mtx); } void Lock() { US_THREADS_MUTEX_LOCK(m_Mtx); } void Unlock() { US_THREADS_MUTEX_UNLOCK(m_Mtx); } private: friend class WaitCondition; // Copy-constructor not implemented. Mutex(const Mutex &); // Copy-assignement operator not implemented. Mutex & operator = (const Mutex &); US_THREADS_MUTEX(m_Mtx) }; template class MutexLock { public: typedef MutexPolicy MutexType; MutexLock(MutexType& mtx) : m_Mtx(&mtx) { m_Mtx->Lock(); } ~MutexLock() { m_Mtx->Unlock(); } private: MutexType* m_Mtx; // purposely not implemented MutexLock(const MutexLock&); MutexLock& operator=(const MutexLock&); }; typedef MutexLock<> DefaultMutexLock; /** * \brief A thread synchronization object used to suspend execution until some * condition on shared data is met. * * A thread calls Wait() to suspend its execution until the condition is * met. Each call to Notify() from an executing thread will then cause a single * waiting thread to be released. A call to Notify() means, "signal * that the condition is true." NotifyAll() releases all threads waiting on * the condition variable. * * The WaitCondition implementation is consistent with the standard * definition and use of condition variables in pthreads and other common * thread libraries. * * IMPORTANT: A condition variable always requires an associated mutex * object. The mutex object is used to avoid a dangerous race condition when * Wait() and Notify() are called simultaneously from two different * threads. * * On systems using pthreads, this implementation abstracts the * standard calls to the pthread condition variable. On Win32 * systems, there is no system provided condition variable. This * class implements a condition variable using a critical section, a * semphore, an event and a number of counters. The implementation is * almost an extract translation of the implementation presented by * Douglas C Schmidt and Irfan Pyarali in "Strategies for Implementing * POSIX Condition Variables on Win32". This article can be found at * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html * */ class US_EXPORT WaitCondition { public: typedef US_DEFAULT_MUTEX MutexType; WaitCondition(); ~WaitCondition(); /** Suspend execution of this thread until the condition is signaled. The * argument is a SimpleMutex object that must be locked prior to calling * this method. */ bool Wait(MutexType& mutex, unsigned long time = 0); bool Wait(MutexType* mutex, unsigned long time = 0); /** Notify that the condition is true and release one waiting thread */ void Notify(); /** Notify that the condition is true and release all waiting threads */ void NotifyAll(); private: // purposely not implemented WaitCondition(const WaitCondition& other); const WaitCondition& operator=(const WaitCondition&); #ifdef US_ENABLE_THREADING_SUPPORT #ifdef US_PLATFORM_POSIX pthread_cond_t m_WaitCondition; #else int m_NumberOfWaiters; // number of waiting threads CRITICAL_SECTION m_NumberOfWaitersLock; // Serialize access to // m_NumberOfWaiters HANDLE m_Semaphore; // Semaphore to queue threads HANDLE m_WaitersAreDone; // Auto-reset event used by the // broadcast/signal thread to // wait for all the waiting // threads to wake up and // release the semaphore std::size_t m_WasNotifyAll; // Keeps track of whether we // were broadcasting or signaling #endif #endif }; US_END_NAMESPACE #ifdef US_ENABLE_THREADING_SUPPORT US_BEGIN_NAMESPACE template class MultiThreaded { mutable MutexPolicy m_Mtx; WaitCondition m_Cond; #if !defined(US_ATOMIC_OPTIMIZATION) mutable MutexPolicy m_AtomicMtx; #endif public: MultiThreaded() : m_Mtx(), m_Cond() {} MultiThreaded(const MultiThreaded&) : m_Mtx(), m_Cond() {} virtual ~MultiThreaded() {} class Lock; friend class Lock; class Lock { public: // Lock object explicit Lock(const MultiThreaded& host) : m_Host(host) { m_Host.m_Mtx.Lock(); } // Lock object explicit Lock(const MultiThreaded* host) : m_Host(*host) { m_Host.m_Mtx.Lock(); } // Unlock object ~Lock() { m_Host.m_Mtx.Unlock(); } private: // private by design Lock(); Lock(const Lock&); Lock& operator=(const Lock&); const MultiThreaded& m_Host; }; typedef volatile Host VolatileType; typedef US_THREADS_LONG IntType; bool Wait(unsigned long timeoutMillis = 0) { return m_Cond.Wait(m_Mtx, timeoutMillis); } void Notify() { m_Cond.Notify(); } void NotifyAll() { m_Cond.NotifyAll(); } IntType AtomicIncrement(volatile IntType& lval) const { US_ATOMIC_INCREMENT(&lval); return n; } IntType AtomicDecrement(volatile IntType& lval) const { US_ATOMIC_DECREMENT(&lval); return n; } void AtomicAssign(volatile IntType& lval, const IntType val) const { US_ATOMIC_ASSIGN(&lval, val); } }; US_END_NAMESPACE #endif US_BEGIN_NAMESPACE template class SingleThreaded { public: virtual ~SingleThreaded() {} // Dummy Lock class struct Lock { Lock() {} explicit Lock(const SingleThreaded&) {} explicit Lock(const SingleThreaded*) {} }; typedef Host VolatileType; typedef int IntType; bool Wait(unsigned long = 0) { return false; } void Notify() {} void NotifyAll() {} static IntType AtomicAdd(volatile IntType& lval, const IntType val) { return lval += val; } static IntType AtomicSubtract(volatile IntType& lval, const IntType val) { return lval -= val; } static IntType AtomicMultiply(volatile IntType& lval, const IntType val) { return lval *= val; } static IntType AtomicDivide(volatile IntType& lval, const IntType val) { return lval /= val; } static IntType AtomicIncrement(volatile IntType& lval) { return ++lval; } static IntType AtomicDecrement(volatile IntType& lval) { return --lval; } static void AtomicAssign(volatile IntType & lval, const IntType val) { lval = val; } static void AtomicAssign(IntType & lval, volatile IntType & val) { lval = val; } }; US_END_NAMESPACE #endif // USTHREADINGMODEL_H diff --git a/Core/Code/CppMicroServices/src/util/usUtils.cpp b/Core/Code/CppMicroServices/src/util/usUtils.cpp index 801f0a8a59..c1d364c4ae 100644 --- a/Core/Code/CppMicroServices/src/util/usUtils.cpp +++ b/Core/Code/CppMicroServices/src/util/usUtils.cpp @@ -1,63 +1,63 @@ /*============================================================================= 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.h" +#include "usUtils_p.h" #ifdef US_PLATFORM_POSIX #include #include #else #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include #endif US_BEGIN_NAMESPACE std::string GetLastErrorStr() { #ifdef US_PLATFORM_POSIX return std::string(strerror(errno)); #else // Retrieve the system error message for the last-error code LPVOID lpMsgBuf; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); std::string errMsg((LPCTSTR)lpMsgBuf); LocalFree(lpMsgBuf); return errMsg; #endif } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/util/usUtils.h b/Core/Code/CppMicroServices/src/util/usUtils_p.h similarity index 99% rename from Core/Code/CppMicroServices/src/util/usUtils.h rename to Core/Code/CppMicroServices/src/util/usUtils_p.h index 156a718867..a78d6a566c 100644 --- a/Core/Code/CppMicroServices/src/util/usUtils.h +++ b/Core/Code/CppMicroServices/src/util/usUtils_p.h @@ -1,179 +1,179 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USUTILS_H #define USUTILS_H #include #include #include #include -#include +#include //------------------------------------------------------------------- // Logging //------------------------------------------------------------------- US_BEGIN_NAMESPACE struct LogMsg { LogMsg() : enabled(true), buffer() {} ~LogMsg() { std::cout << buffer.str() << std::endl; } template LogMsg& operator<<(T t) { if (enabled) { buffer << t; } return *this; } LogMsg& operator()(bool flag) { this->enabled = flag; return *this; } private: bool enabled; std::stringstream buffer; }; US_END_NAMESPACE #define US_DEBUG US_PREPEND_NAMESPACE(LogMsg)() #define US_INFO US_PREPEND_NAMESPACE(LogMsg)() #define US_ERROR US_PREPEND_NAMESPACE(LogMsg)() #define US_WARN US_PREPEND_NAMESPACE(LogMsg)() //------------------------------------------------------------------- // Error handling //------------------------------------------------------------------- US_BEGIN_NAMESPACE US_EXPORT std::string GetLastErrorStr(); US_END_NAMESPACE //------------------------------------------------------------------- // Functors //------------------------------------------------------------------- #include #include #if defined(US_USE_CXX11) || defined(__GNUC__) #ifdef US_USE_CXX11 #include #define US_MODULE_LISTENER_FUNCTOR std::function #define US_SERVICE_LISTENER_FUNCTOR std::function #else #include #define US_MODULE_LISTENER_FUNCTOR std::tr1::function #define US_SERVICE_LISTENER_FUNCTOR std::tr1::function #endif US_BEGIN_NAMESPACE template US_MODULE_LISTENER_FUNCTOR ModuleListenerMemberFunctor(X* x, void (X::*memFn)(const US_PREPEND_NAMESPACE(ModuleEvent))) { return std::bind1st(std::mem_fun(memFn), x); } US_END_NAMESPACE US_BEGIN_NAMESPACE struct ModuleListenerCompare : std::binary_function { bool operator()(const US_MODULE_LISTENER_FUNCTOR& f1, const US_MODULE_LISTENER_FUNCTOR& f2) const { return f1.target() == f2.target(); } }; US_END_NAMESPACE US_BEGIN_NAMESPACE template US_SERVICE_LISTENER_FUNCTOR ServiceListenerMemberFunctor(X* x, void (X::*memFn)(const US_PREPEND_NAMESPACE(ServiceEvent))) { return std::bind1st(std::mem_fun(memFn), x); } US_END_NAMESPACE US_BEGIN_NAMESPACE struct ServiceListenerCompare : std::binary_function { bool operator()(const US_SERVICE_LISTENER_FUNCTOR& f1, const US_SERVICE_LISTENER_FUNCTOR& f2) const { return f1.target() == f2.target(); } }; US_END_NAMESPACE #else #include #define US_MODULE_LISTENER_FUNCTOR US_PREPEND_NAMESPACE(Functor) US_BEGIN_NAMESPACE template US_MODULE_LISTENER_FUNCTOR ModuleListenerMemberFunctor(X* x, MemFn memFn) { return Functor(x, memFn); } US_END_NAMESPACE US_BEGIN_NAMESPACE struct ModuleListenerCompare : std::binary_function { bool operator()(const US_MODULE_LISTENER_FUNCTOR& f1, const US_MODULE_LISTENER_FUNCTOR& f2) const { return f1 == f2; } }; US_END_NAMESPACE #define US_SERVICE_LISTENER_FUNCTOR US_PREPEND_NAMESPACE(Functor) US_BEGIN_NAMESPACE template US_SERVICE_LISTENER_FUNCTOR ServiceListenerMemberFunctor(X* x, MemFn memFn) { return Functor(x, memFn); } US_END_NAMESPACE US_BEGIN_NAMESPACE struct ServiceListenerCompare : std::binary_function { bool operator()(const US_SERVICE_LISTENER_FUNCTOR& f1, const US_SERVICE_LISTENER_FUNCTOR& f2) const { return f1 == f2; } }; US_END_NAMESPACE #endif #endif // USUTILS_H diff --git a/Core/Code/CppMicroServices/test/usModuleTest.cpp b/Core/Code/CppMicroServices/test/usModuleTest.cpp index d72e8efda0..e448a4d5f4 100644 --- a/Core/Code/CppMicroServices/test/usModuleTest.cpp +++ b/Core/Code/CppMicroServices/test/usModuleTest.cpp @@ -1,382 +1,382 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include #include #include #include #include #include #include US_BASECLASS_HEADER #include "usTestUtilSharedLibrary.cpp" #include "usTestingMacros.h" US_USE_NAMESPACE extern ModuleActivator* _us_module_activator_instance_TestModuleA(); class TestModuleListener { public: TestModuleListener(ModuleContext* mc) : mc(mc), serviceEvents(), moduleEvents() {} void ModuleChanged(const ModuleEvent event) { moduleEvents.push_back(event); US_DEBUG << "ModuleEvent:" << event; } void ServiceChanged(const ServiceEvent event) { serviceEvents.push_back(event); US_DEBUG << "ServiceEvent:" << event; } ModuleEvent GetModuleEvent() const { if (moduleEvents.empty()) { return ModuleEvent(); } return moduleEvents.back(); } ServiceEvent GetServiceEvent() const { if (serviceEvents.empty()) { return ServiceEvent(); } return serviceEvents.back(); } bool CheckListenerEvents( bool pexp, ModuleEvent::Type ptype, bool sexp, ServiceEvent::Type stype, Module* moduleX, ServiceReference* servX) { std::vector pEvts; std::vector seEvts; if (pexp) pEvts.push_back(ModuleEvent(ptype, moduleX)); if (sexp) seEvts.push_back(ServiceEvent(stype, *servX)); return CheckListenerEvents(pEvts, seEvts); } bool CheckListenerEvents( const std::vector& pEvts, const std::vector& seEvts) { 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; } } } 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; } } } moduleEvents.clear(); serviceEvents.clear(); return listenState; } private: ModuleContext* const mc; std::vector serviceEvents; std::vector moduleEvents; }; // Verify information from the ModuleInfo struct void frame005a(ModuleContext* mc) { Module* m = mc->GetModule(); // check expected headers US_TEST_CONDITION("CppMicroServicesTestDriver" == m->GetName(), "Test module name"); // US_DEBUG << "Version: " << m->GetVersion(); US_TEST_CONDITION(ModuleVersion(0,1,0) == m->GetVersion(), "Test module version") } // Get context id, location and status of the module void frame010a(ModuleContext* mc) { Module* m = mc->GetModule(); long int contextid = m->GetModuleId(); US_DEBUG << "CONTEXT ID:" << contextid; std::string location = m->GetLocation(); US_DEBUG << "LOCATION:" << location; US_TEST_CONDITION(!location.empty(), "Test for non-empty module location") US_TEST_CONDITION(m->IsLoaded(), "Test for loaded flag") } //---------------------------------------------------------------------------- //Test result of GetService(ServiceReference()). Should throw std::invalid_argument void frame018a(ModuleContext* mc) { try { US_BASECLASS_NAME* obj = mc->GetService(ServiceReference()); US_DEBUG << "Got service object = " << us_service_impl_name(obj) << ", expected std::invalid_argument exception"; US_TEST_FAILED_MSG(<< "Got service object, excpected std::invalid_argument exception") } catch (const std::invalid_argument& ) {} catch (...) { US_TEST_FAILED_MSG(<< "Got wrong exception, expected std::invalid_argument") } } // Load libA and check that it exists and that the service it registers exists, // also check that the expected events occur void frame020a(ModuleContext* mc, TestModuleListener& listener, SharedLibraryHandle& libA) { try { libA.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) } #ifdef US_BUILD_SHARED_LIBS - Module* moduleA = ModuleRegistry::GetModule("TestModuleA"); - US_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for existing moudle TestModuleA") + Module* moduleA = ModuleRegistry::GetModule("TestModuleA Module"); + US_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for existing module TestModuleA") - US_TEST_CONDITION(moduleA->GetName() == "TestModuleA", "Test module name") + US_TEST_CONDITION(moduleA->GetName() == "TestModuleA Module", "Test module name") #endif // Check if libA registered the expected service try { ServiceReference sr1 = mc->GetServiceReference("org.cppmicroservices.TestModuleAService"); US_BASECLASS_NAME* o1 = mc->GetService(sr1); US_TEST_CONDITION(o1 != 0, "Test if service object found"); try { US_TEST_CONDITION(mc->UngetService(sr1), "Test if Service UnGet returns true"); } catch (const std::logic_error le) { US_TEST_FAILED_MSG(<< "UnGetService exception: " << le.what()) } // check the listeners for events std::vector pEvts; #ifdef US_BUILD_SHARED_LIBS pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleA)); pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleA)); #endif std::vector seEvts; seEvts.push_back(ServiceEvent(ServiceEvent::REGISTERED, sr1)); US_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); } catch (const ServiceException& /*se*/) { US_TEST_FAILED_MSG(<< "test module, expected service not found"); } #ifdef US_BUILD_SHARED_LIBS US_TEST_CONDITION(moduleA->IsLoaded() == true, "Test if loaded correctly"); #endif } // Unload libA and check for correct events void frame030b(ModuleContext* mc, TestModuleListener& listener, SharedLibraryHandle& libA) { #ifdef US_BUILD_SHARED_LIBS - Module* moduleA = ModuleRegistry::GetModule("TestModuleA"); + Module* moduleA = ModuleRegistry::GetModule("TestModuleA Module"); US_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for non-null module") #endif ServiceReference sr1 = mc->GetServiceReference("org.cppmicroservices.TestModuleAService"); US_TEST_CONDITION(sr1, "Test for valid service reference") try { libA.Unload(); #ifdef US_BUILD_SHARED_LIBS US_TEST_CONDITION(moduleA->IsLoaded() == false, "Test for unloaded state") #endif } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "UnLoad module exception: " << e.what()) } std::vector pEvts; #ifdef US_BUILD_SHARED_LIBS pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADING, moduleA)); pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADED, moduleA)); #endif std::vector seEvts; seEvts.push_back(ServiceEvent(ServiceEvent::UNREGISTERING, sr1)); 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:"); } } int usModuleTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ModuleTest"); ModuleContext* mc = GetModuleContext(); TestModuleListener listener(mc); try { mc->AddModuleListener(&listener, &TestModuleListener::ModuleChanged); } catch (const std::logic_error& ise) { US_TEST_OUTPUT( << "module listener registration failed " << ise.what() ); throw; } try { mc->AddServiceListener(&listener, &TestModuleListener::ServiceChanged); } catch (const std::logic_error& ise) { US_TEST_OUTPUT( << "service listener registration failed " << ise.what() ); throw; } frame005a(mc); frame010a(mc); frame018a(mc); SharedLibraryHandle libA("TestModuleA" #ifndef US_BUILD_SHARED_LIBS , _us_module_activator_instance_TestModuleA #endif ); 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/usTestUtilSharedLibrary.cpp b/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.cpp index 738c0cd10d..f3ac74c59b 100644 --- a/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.cpp +++ b/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.cpp @@ -1,159 +1,159 @@ /*============================================================================= 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 #if defined(US_PLATFORM_POSIX) #include #elif defined(US_PLATFORM_WINDOWS) #define WIN32_LEAN_AND_MEAN #include #include #else #error Unsupported platform #endif US_BEGIN_NAMESPACE class SharedLibraryHandle { public: SharedLibraryHandle() : m_Handle(0) {} SharedLibraryHandle(const std::string& name, ModuleActivatorInstanceFunction activatorFunc = 0) : m_Name(name), m_ActivatorFunc(activatorFunc), m_Handle(0) {} virtual ~SharedLibraryHandle() {} void Load() { Load(m_Name); } void 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 #else // US_BUILD_SHARED_LIBS m_ActivatorFunc()->Load(GetModuleContext()); #endif m_Name = name; } void 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; } #else // US_BUILD_SHARED_LIBS m_ActivatorFunc()->Unload(GetModuleContext()); #endif } std::string GetAbsolutePath(const std::string& name) { return GetLibraryPath() + "/" + Prefix() + name + Suffix(); } std::string GetAbsolutePath() { return GetLibraryPath() + "/" + Prefix() + m_Name + Suffix(); } static std::string GetLibraryPath() { #ifdef US_PLATFORM_WINDOWS return std::string(US_RUNTIME_OUTPUT_DIRECTORY); #else return std::string(US_LIBRARY_OUTPUT_DIRECTORY); #endif } static std::string Suffix() { #ifdef US_PLATFORM_WINDOWS return ".dll"; #elif defined(US_PLATFORM_APPLE) return ".dylib"; #else return ".so"; #endif } static std::string Prefix() { #if defined(US_PLATFORM_POSIX) return "lib"; #else return ""; #endif } private: SharedLibraryHandle(const SharedLibraryHandle&); SharedLibraryHandle& operator = (const SharedLibraryHandle&); std::string m_Name; ModuleActivatorInstanceFunction m_ActivatorFunc; void* m_Handle; }; US_END_NAMESPACE