diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..cba86d0575 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +*~ +*.o +*.so +CMakeLists.txt.user* +gh-pages +examples/makefile/main diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000000..75bc8fbe53 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,27 @@ +language: cpp +compiler: + - gcc + - clang +env: + - BUILD_CONFIGURATION=1 + - BUILD_CONFIGURATION=3 + - BUILD_CONFIGURATION=5 + - BUILD_CONFIGURATION=7 + - BUILD_CONFIGURATION=9 + - BUILD_CONFIGURATION=11 + - BUILD_CONFIGURATION=13 + - BUILD_CONFIGURATION=15 + - BUILD_CONFIGURATION=17 + - BUILD_CONFIGURATION=19 + - BUILD_CONFIGURATION=21 + - BUILD_CONFIGURATION=23 + - BUILD_CONFIGURATION=25 + - BUILD_CONFIGURATION=27 + - BUILD_CONFIGURATION=29 + - BUILD_CONFIGURATION=31 + +branches: + only: + - master + +script: ctest -S ./CMake/usCTestScript_travis.cmake diff --git a/CMake/CMakePackageConfigHelpers.cmake b/CMake/CMakePackageConfigHelpers.cmake new file mode 100644 index 0000000000..26f6cc264f --- /dev/null +++ b/CMake/CMakePackageConfigHelpers.cmake @@ -0,0 +1,288 @@ +# - CONFIGURE_PACKAGE_CONFIG_FILE(), WRITE_BASIC_PACKAGE_VERSION_FILE() +# +# CONFIGURE_PACKAGE_CONFIG_FILE( INSTALL_DESTINATION +# [PATH_VARS ... ] +# [NO_SET_AND_CHECK_MACRO] +# [NO_CHECK_REQUIRED_COMPONENTS_MACRO]) +# +# CONFIGURE_PACKAGE_CONFIG_FILE() should be used instead of the plain +# configure_file() command when creating the Config.cmake or -config.cmake +# file for installing a project or library. It helps making the resulting package +# relocatable by avoiding hardcoded paths in the installed Config.cmake file. +# +# In a FooConfig.cmake file there may be code like this to make the +# install destinations know to the using project: +# set(FOO_INCLUDE_DIR "@CMAKE_INSTALL_FULL_INCLUDEDIR@" ) +# set(FOO_DATA_DIR "@CMAKE_INSTALL_PREFIX@/@RELATIVE_DATA_INSTALL_DIR@" ) +# set(FOO_ICONS_DIR "@CMAKE_INSTALL_PREFIX@/share/icons" ) +# ...logic to determine installedPrefix from the own location... +# set(FOO_CONFIG_DIR "${installedPrefix}/@CONFIG_INSTALL_DIR@" ) +# All 4 options shown above are not sufficient, since the first 3 hardcode +# the absolute directory locations, and the 4th case works only if the logic +# to determine the installedPrefix is correct, and if CONFIG_INSTALL_DIR contains +# a relative path, which in general cannot be guaranteed. +# This has the effect that the resulting FooConfig.cmake file would work poorly +# under Windows and OSX, where users are used to choose the install location +# of a binary package at install time, independent from how CMAKE_INSTALL_PREFIX +# was set at build/cmake time. +# +# Using CONFIGURE_PACKAGE_CONFIG_FILE() helps. If used correctly, it makes the +# resulting FooConfig.cmake file relocatable. +# Usage: +# 1. write a FooConfig.cmake.in file as you are used to +# 2. insert a line containing only the string "@PACKAGE_INIT@" +# 3. instead of set(FOO_DIR "@SOME_INSTALL_DIR@"), use set(FOO_DIR "@PACKAGE_SOME_INSTALL_DIR@") +# (this must be after the @PACKAGE_INIT@ line) +# 4. instead of using the normal configure_file(), use CONFIGURE_PACKAGE_CONFIG_FILE() +# +# The and arguments are the input and output file, the same way +# as in configure_file(). +# +# The given to INSTALL_DESTINATION must be the destination where the FooConfig.cmake +# file will be installed to. This can either be a relative or absolute path, both work. +# +# The variables to given as PATH_VARS are the variables which contain +# install destinations. For each of them the macro will create a helper variable +# PACKAGE_. These helper variables must be used +# in the FooConfig.cmake.in file for setting the installed location. They are calculated +# by CONFIGURE_PACKAGE_CONFIG_FILE() so that they are always relative to the +# installed location of the package. This works both for relative and also for absolute locations. +# For absolute locations it works only if the absolute location is a subdirectory +# of CMAKE_INSTALL_PREFIX. +# +# By default configure_package_config_file() also generates two helper macros, +# set_and_check() and check_required_components() into the FooConfig.cmake file. +# +# set_and_check() should be used instead of the normal set() +# command for setting directories and file locations. Additionally to setting the +# variable it also checks that the referenced file or directory actually exists +# and fails with a FATAL_ERROR otherwise. This makes sure that the created +# FooConfig.cmake file does not contain wrong references. +# When using the NO_SET_AND_CHECK_MACRO, this macro is not generated into the +# FooConfig.cmake file. +# +# check_required_components() should be called at the end of the +# FooConfig.cmake file if the package supports components. +# This macro checks whether all requested, non-optional components have been found, +# and if this is not the case, sets the Foo_FOUND variable to FALSE, so that the package +# is considered to be not found. +# It does that by testing the Foo__FOUND variables for all requested +# required components. +# When using the NO_CHECK_REQUIRED_COMPONENTS option, this macro is not generated +# into the FooConfig.cmake file. +# +# For an example see below the documentation for WRITE_BASIC_PACKAGE_VERSION_FILE(). +# +# +# WRITE_BASIC_PACKAGE_VERSION_FILE( filename VERSION major.minor.patch COMPATIBILITY (AnyNewerVersion|SameMajorVersion|ExactVersion) ) +# +# Writes a file for use as ConfigVersion.cmake file to . +# See the documentation of find_package() for details on this. +# filename is the output filename, it should be in the build tree. +# major.minor.patch is the version number of the project to be installed +# The COMPATIBILITY mode AnyNewerVersion means that the installed package version +# will be considered compatible if it is newer or exactly the same as the requested version. +# This mode should be used for packages which are fully backward compatible, +# also across major versions. +# If SameMajorVersion is used instead, then the behaviour differs from AnyNewerVersion +# in that the major version number must be the same as requested, e.g. version 2.0 will +# not be considered compatible if 1.0 is requested. +# This mode should be used for packages which guarantee backward compatibility within the +# same major version. +# If ExactVersion is used, then the package is only considered compatible if the requested +# version matches exactly its own version number (not considering the tweak version). +# For example, version 1.2.3 of a package is only considered compatible to requested version 1.2.3. +# This mode is for packages without compatibility guarantees. +# If your project has more elaborated version matching rules, you will need to write your +# own custom ConfigVersion.cmake file instead of using this macro. +# +# Internally, this macro executes configure_file() to create the resulting +# version file. Depending on the COMPATIBLITY, either the file +# BasicConfigVersion-SameMajorVersion.cmake.in or BasicConfigVersion-AnyNewerVersion.cmake.in +# is used. Please note that these two files are internal to CMake and you should +# not call configure_file() on them yourself, but they can be used as starting +# point to create more sophisticted custom ConfigVersion.cmake files. +# +# +# Example using both configure_package_config_file() and write_basic_package_version_file(): +# CMakeLists.txt: +# set(INCLUDE_INSTALL_DIR include/ ... CACHE ) +# set(LIB_INSTALL_DIR lib/ ... CACHE ) +# set(SYSCONFIG_INSTALL_DIR etc/foo/ ... CACHE ) +# ... +# include(CMakePackageConfigHelpers) +# configure_package_config_file(FooConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake +# INSTALL_DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake +# PATH_VARS INCLUDE_INSTALL_DIR SYSCONFIG_INSTALL_DIR) +# write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake +# VERSION 1.2.3 +# COMPATIBILITY SameMajorVersion ) +# install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake +# DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake ) +# +# With a FooConfig.cmake.in: +# set(FOO_VERSION x.y.z) +# ... +# @PACKAGE_INIT@ +# ... +# set_and_check(FOO_INCLUDE_DIR "@PACKAGE_INCLUDE_INSTALL_DIR@") +# set_and_check(FOO_SYSCONFIG_DIR "@PACKAGE_SYSCONFIG_INSTALL_DIR@") +# +# check_required_components(Foo) + +#============================================================================= +# Copyright 2012 Alexander Neundorf +# +# CMake - Cross Platform Makefile Generator +# Copyright 2000-2011 Kitware, Inc., Insight Software Consortium +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the names of Kitware, Inc., the Insight Software Consortium, +# nor the names of their contributors may be used to endorse or promote +# products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# ------------------------------------------------------------------------------ +# +# The above copyright and license notice applies to distributions of +# CMake in source and binary form. Some source files contain additional +# notices of original copyright by their contributors; see each source +# for details. Third-party software packages supplied with CMake under +# compatible licenses provide their own copyright notices documented in +# corresponding subdirectories. +# +#------------------------------------------------------------------------------ +# +# CMake was initially developed by Kitware with the following sponsorship: +# +# * National Library of Medicine at the National Institutes of Health +# as part of the Insight Segmentation and Registration Toolkit (ITK). +# +# * US National Labs (Los Alamos, Livermore, Sandia) ASC Parallel +# Visualization Initiative. +# +# * National Alliance for Medical Image Computing (NAMIC) is funded by the +# National Institutes of Health through the NIH Roadmap for Medical Research, +# Grant U54 EB005149. +# +# * Kitware, Inc. +#============================================================================= + +include(CMakeParseArguments) + +function(CONFIGURE_PACKAGE_CONFIG_FILE _inputFile _outputFile) + set(options NO_SET_AND_CHECK_MACRO NO_CHECK_REQUIRED_COMPONENTS_MACRO) + set(oneValueArgs INSTALL_DESTINATION ) + set(multiValueArgs PATH_VARS ) + + cmake_parse_arguments(CCF "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + + if(CCF_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to CONFIGURE_PACKAGE_CONFIG_FILE(): \"${CCF_UNPARSED_ARGUMENTS}\"") + endif() + + if(NOT CCF_INSTALL_DESTINATION) + message(FATAL_ERROR "No INSTALL_DESTINATION given to CONFIGURE_PACKAGE_CONFIG_FILE()") + endif() + + if(IS_ABSOLUTE "${CCF_INSTALL_DESTINATION}") + set(absInstallDir "${CCF_INSTALL_DESTINATION}") + else() + set(absInstallDir "${CMAKE_INSTALL_PREFIX}/${CCF_INSTALL_DESTINATION}") + endif() + + file(RELATIVE_PATH PACKAGE_RELATIVE_PATH "${absInstallDir}" "${CMAKE_INSTALL_PREFIX}" ) + + foreach(var ${CCF_PATH_VARS}) + if(NOT DEFINED ${var}) + message(FATAL_ERROR "Variable ${var} does not exist") + else() + if(IS_ABSOLUTE "${${var}}") + string(REPLACE "${CMAKE_INSTALL_PREFIX}" "\${PACKAGE_PREFIX_DIR}" + PACKAGE_${var} "${${var}}") + else() + set(PACKAGE_${var} "\${PACKAGE_PREFIX_DIR}/${${var}}") + endif() + endif() + endforeach() + + get_filename_component(inputFileName "${_inputFile}" NAME) + + set(PACKAGE_INIT " +####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() ####### +####### Any changes to this file will be overwritten by the next CMake run #### +####### The input file was ${inputFileName} ######## + +get_filename_component(PACKAGE_PREFIX_DIR \"\${CMAKE_CURRENT_LIST_DIR}/${PACKAGE_RELATIVE_PATH}\" ABSOLUTE) +") + + if("${absInstallDir}" MATCHES "^(/usr)?/lib(64)?/.+") + # Handle "/usr move" symlinks created by some Linux distros. + set(PACKAGE_INIT "${PACKAGE_INIT} +# Use original install prefix when loaded through a \"/usr move\" +# cross-prefix symbolic link such as /lib -> /usr/lib. +get_filename_component(_realCurr \"\${CMAKE_CURRENT_LIST_DIR}\" REALPATH) +get_filename_component(_realOrig \"${absInstallDir}\" REALPATH) +if(_realCurr STREQUAL _realOrig) + set(PACKAGE_PREFIX_DIR \"${CMAKE_INSTALL_PREFIX}\") +endif() +unset(_realOrig) +unset(_realCurr) +") + endif() + + if(NOT CCF_NO_SET_AND_CHECK_MACRO) + set(PACKAGE_INIT "${PACKAGE_INIT} +macro(set_and_check _var _file) + set(\${_var} \"\${_file}\") + if(NOT EXISTS \"\${_file}\") + message(FATAL_ERROR \"File or directory \${_file} referenced by variable \${_var} does not exist !\") + endif() +endmacro() +") + endif() + + + if(NOT CCF_NO_CHECK_REQUIRED_COMPONENTS_MACRO) + set(PACKAGE_INIT "${PACKAGE_INIT} +macro(check_required_components _NAME) + foreach(comp \${\${_NAME}_FIND_COMPONENTS}) + if(NOT \${_NAME}_\${comp}_FOUND) + if(\${_NAME}_FIND_REQUIRED_\${comp}) + set(\${_NAME}_FOUND FALSE) + endif() + endif() + endforeach() +endmacro() +") + endif() + + set(PACKAGE_INIT "${PACKAGE_INIT} +####################################################################################") + + configure_file("${_inputFile}" "${_outputFile}" @ONLY) + +endfunction() diff --git a/CMake/CMakeParseArguments.cmake b/CMake/CMakeParseArguments.cmake new file mode 100644 index 0000000000..5e58023943 --- /dev/null +++ b/CMake/CMakeParseArguments.cmake @@ -0,0 +1,186 @@ +# CMAKE_PARSE_ARGUMENTS( args...) +# +# CMAKE_PARSE_ARGUMENTS() is intended to be used in macros or functions for +# parsing the arguments given to that macro or function. +# It processes the arguments and defines a set of variables which hold the +# values of the respective options. +# +# The argument contains all options for the respective macro, +# i.e. keywords which can be used when calling the macro without any value +# following, like e.g. the OPTIONAL keyword of the install() command. +# +# The argument contains all keywords for this macro +# which are followed by one value, like e.g. DESTINATION keyword of the +# install() command. +# +# The argument contains all keywords for this macro +# which can be followed by more than one value, like e.g. the TARGETS or +# FILES keywords of the install() command. +# +# When done, CMAKE_PARSE_ARGUMENTS() will have defined for each of the +# keywords listed in , and +# a variable composed of the given +# followed by "_" and the name of the respective keyword. +# These variables will then hold the respective value from the argument list. +# For the keywords this will be TRUE or FALSE. +# +# All remaining arguments are collected in a variable +# _UNPARSED_ARGUMENTS, this can be checked afterwards to see whether +# your macro was called with unrecognized parameters. +# +# As an example here a my_install() macro, which takes similar arguments as the +# real install() command: +# +# function(MY_INSTALL) +# set(options OPTIONAL FAST) +# set(oneValueArgs DESTINATION RENAME) +# set(multiValueArgs TARGETS CONFIGURATIONS) +# cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) +# ... +# +# Assume my_install() has been called like this: +# my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub) +# +# After the cmake_parse_arguments() call the macro will have set the following +# variables: +# MY_INSTALL_OPTIONAL = TRUE +# MY_INSTALL_FAST = FALSE (this option was not used when calling my_install() +# MY_INSTALL_DESTINATION = "bin" +# MY_INSTALL_RENAME = "" (was not used) +# MY_INSTALL_TARGETS = "foo;bar" +# MY_INSTALL_CONFIGURATIONS = "" (was not used) +# MY_INSTALL_UNPARSED_ARGUMENTS = "blub" (no value expected after "OPTIONAL" +# +# You can then continue and process these variables. +# +# Keywords terminate lists of values, e.g. if directly after a one_value_keyword +# another recognized keyword follows, this is interpreted as the beginning of +# the new option. +# E.g. my_install(TARGETS foo DESTINATION OPTIONAL) would result in +# MY_INSTALL_DESTINATION set to "OPTIONAL", but MY_INSTALL_DESTINATION would +# be empty and MY_INSTALL_OPTIONAL would be set to TRUE therefor. + +#============================================================================= +# Copyright 2010 Alexander Neundorf +# +# CMake - Cross Platform Makefile Generator +# Copyright 2000-2011 Kitware, Inc., Insight Software Consortium +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the names of Kitware, Inc., the Insight Software Consortium, +# nor the names of their contributors may be used to endorse or promote +# products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# ------------------------------------------------------------------------------ +# +# The above copyright and license notice applies to distributions of +# CMake in source and binary form. Some source files contain additional +# notices of original copyright by their contributors; see each source +# for details. Third-party software packages supplied with CMake under +# compatible licenses provide their own copyright notices documented in +# corresponding subdirectories. +# +#------------------------------------------------------------------------------ +# +# CMake was initially developed by Kitware with the following sponsorship: +# +# * National Library of Medicine at the National Institutes of Health +# as part of the Insight Segmentation and Registration Toolkit (ITK). +# +# * US National Labs (Los Alamos, Livermore, Sandia) ASC Parallel +# Visualization Initiative. +# +# * National Alliance for Medical Image Computing (NAMIC) is funded by the +# National Institutes of Health through the NIH Roadmap for Medical Research, +# Grant U54 EB005149. +# +# * Kitware, Inc. +#============================================================================= + + +if(__CMAKE_PARSE_ARGUMENTS_INCLUDED) + return() +endif() +set(__CMAKE_PARSE_ARGUMENTS_INCLUDED TRUE) + + +function(CMAKE_PARSE_ARGUMENTS prefix _optionNames _singleArgNames _multiArgNames) + # first set all result variables to empty/FALSE + foreach(arg_name ${_singleArgNames} ${_multiArgNames}) + set(${prefix}_${arg_name}) + endforeach() + + foreach(option ${_optionNames}) + set(${prefix}_${option} FALSE) + endforeach() + + set(${prefix}_UNPARSED_ARGUMENTS) + + set(insideValues FALSE) + set(currentArgName) + + # now iterate over all arguments and fill the result variables + foreach(currentArg ${ARGN}) + list(FIND _optionNames "${currentArg}" optionIndex) # ... then this marks the end of the arguments belonging to this keyword + list(FIND _singleArgNames "${currentArg}" singleArgIndex) # ... then this marks the end of the arguments belonging to this keyword + list(FIND _multiArgNames "${currentArg}" multiArgIndex) # ... then this marks the end of the arguments belonging to this keyword + + if(${optionIndex} EQUAL -1 AND ${singleArgIndex} EQUAL -1 AND ${multiArgIndex} EQUAL -1) + if(insideValues) + if("${insideValues}" STREQUAL "SINGLE") + set(${prefix}_${currentArgName} ${currentArg}) + set(insideValues FALSE) + elseif("${insideValues}" STREQUAL "MULTI") + list(APPEND ${prefix}_${currentArgName} ${currentArg}) + endif() + else() + list(APPEND ${prefix}_UNPARSED_ARGUMENTS ${currentArg}) + endif() + else() + if(NOT ${optionIndex} EQUAL -1) + set(${prefix}_${currentArg} TRUE) + set(insideValues FALSE) + elseif(NOT ${singleArgIndex} EQUAL -1) + set(currentArgName ${currentArg}) + set(${prefix}_${currentArgName}) + set(insideValues "SINGLE") + elseif(NOT ${multiArgIndex} EQUAL -1) + set(currentArgName ${currentArg}) + set(${prefix}_${currentArgName}) + set(insideValues "MULTI") + endif() + endif() + + endforeach() + + # propagate the result variables to the caller: + foreach(arg_name ${_singleArgNames} ${_multiArgNames} ${_optionNames}) + set(${prefix}_${arg_name} ${${prefix}_${arg_name}} PARENT_SCOPE) + endforeach() + set(${prefix}_UNPARSED_ARGUMENTS ${${prefix}_UNPARSED_ARGUMENTS} PARENT_SCOPE) + +endfunction() diff --git a/CMake/usCTestScript.cmake b/CMake/usCTestScript.cmake new file mode 100644 index 0000000000..0a7f96535b --- /dev/null +++ b/CMake/usCTestScript.cmake @@ -0,0 +1,134 @@ + +macro(build_and_test) + + set(CTEST_SOURCE_DIRECTORY ${US_SOURCE_DIR}) + set(CTEST_BINARY_DIRECTORY "${CTEST_DASHBOARD_ROOT}/${CTEST_PROJECT_NAME}_${CTEST_DASHBOARD_NAME}") + + #if(NOT CTEST_BUILD_NAME) + # set(CTEST_BUILD_NAME "${CMAKE_SYSTEM}_${CTEST_COMPILER}_${CTEST_DASHBOARD_NAME}") + #endif() + + ctest_empty_binary_directory(${CTEST_BINARY_DIRECTORY}) + + ctest_start("Experimental") + + if(NOT EXISTS "${CTEST_BINARY_DIRECTORY}/CMakeCache.txt") + file(WRITE "${CTEST_BINARY_DIRECTORY}/CMakeCache.txt" "${CTEST_INITIAL_CACHE}") + endif() + + ctest_configure(RETURN_VALUE res) + if (res) + message(FATAL_ERROR "CMake configure error") + endif() + ctest_build(RETURN_VALUE res) + if (res) + message(FATAL_ERROR "CMake build error") + endif() + + ctest_test(RETURN_VALUE res PARALLEL_LEVEL ${CTEST_PARALLEL_LEVEL}) + if (res) + message(FATAL_ERROR "CMake test error") + endif() + + + if(WITH_MEMCHECK AND CTEST_MEMORYCHECK_COMMAND) + ctest_memcheck() + endif() + + if(WITH_COVERAGE AND CTEST_COVERAGE_COMMAND) + ctest_coverage() + endif() + + #ctest_submit() + +endmacro() + +function(create_initial_cache var _shared _threading _sf _cxx11 _autoload) + + set(_initial_cache " + US_BUILD_TESTING:BOOL=ON + US_BUILD_SHARED_LIBS:BOOL=${_shared} + US_ENABLE_THREADING_SUPPORT:BOOL=${_threading} + US_ENABLE_SERVICE_FACTORY_SUPPORT:BOOL=${_sf} + US_USE_C++11:BOOL=${_cxx11} + US_ENABLE_AUTOLOADING_SUPPORT:BOOL=${_autoload} + ") + if(_shared) + set(_initial_cache "${_initial_cache} US_BUILD_EXAMPLES:BOOL=ON + ") + endif() + + set(${var} ${_initial_cache} PARENT_SCOPE) + + if(_shared) + set(CTEST_DASHBOARD_NAME "shared") + else() + set(CTEST_DASHBOARD_NAME "static") + endif() + + if(_threading) + set(CTEST_DASHBOARD_NAME "${CTEST_DASHBOARD_NAME}-threading") + endif() + if(_sf) + set(CTEST_DASHBOARD_NAME "${CTEST_DASHBOARD_NAME}-servicefactory") + endif() + if(_cxx11) + set(CTEST_DASHBOARD_NAME "${CTEST_DASHBOARD_NAME}-cxx11") + endif() + if(_autoload) + set(CTEST_DASHBOARD_NAME "${CTEST_DASHBOARD_NAME}-autoloading") + endif() + + set(CTEST_DASHBOARD_NAME ${CTEST_DASHBOARD_NAME} PARENT_SCOPE) + +endfunction() + +#========================================================= + +set(CTEST_PROJECT_NAME CppMicroServices) + +if(NOT CTEST_PARALLEL_LEVEL) + set(CTEST_PARALLEL_LEVEL 1) +endif() + + +# SHARED THREADING SERVICE_FACTORY C++11 AUTOLOAD + +set(config0 0 0 0 0 0 ) +set(config1 0 0 0 0 1 ) +set(config2 0 0 0 1 0 ) +set(config3 0 0 0 1 1 ) +set(config4 0 0 1 0 0 ) +set(config5 0 0 1 0 1 ) +set(config6 0 0 1 1 0 ) +set(config7 0 0 1 1 1 ) +set(config8 0 1 0 0 0 ) +set(config9 0 1 0 0 1 ) +set(config10 0 1 0 1 0 ) +set(config11 0 1 0 1 1 ) +set(config12 0 1 1 0 0 ) +set(config13 0 1 1 0 1 ) +set(config14 0 1 1 1 0 ) +set(config15 0 1 1 1 1 ) +set(config16 1 0 0 0 0 ) +set(config17 1 0 0 0 1 ) +set(config18 1 0 0 1 0 ) +set(config19 1 0 0 1 1 ) +set(config20 1 0 1 0 0 ) +set(config21 1 0 1 0 1 ) +set(config22 1 0 1 1 0 ) +set(config23 1 0 1 1 1 ) +set(config24 1 1 0 0 0 ) +set(config25 1 1 0 0 1 ) +set(config26 1 1 0 1 0 ) +set(config27 1 1 0 1 1 ) +set(config28 1 1 1 0 0 ) +set(config29 1 1 1 0 1 ) +set(config30 1 1 1 1 0 ) +set(config31 1 1 1 1 1 ) + +foreach(i ${US_BUILD_CONFIGURATION}) + create_initial_cache(CTEST_INITIAL_CACHE ${config${i}}) + message("Testing build configuration: ${CTEST_DASHBOARD_NAME}") + build_and_test() +endforeach() diff --git a/CMake/usCTestScript_custom.cmake b/CMake/usCTestScript_custom.cmake new file mode 100644 index 0000000000..cbdcba4727 --- /dev/null +++ b/CMake/usCTestScript_custom.cmake @@ -0,0 +1,24 @@ + +find_program(CTEST_COVERAGE_COMMAND NAMES gcov) +find_program(CTEST_MEMORYCHECK_COMMAND NAMES valgrind) +find_program(CTEST_GIT_COMMAND NAMES git) + +set(CTEST_SITE "bigeye") +set(CTEST_DASHBOARD_ROOT "/tmp") +#set(CTEST_COMPILER "gcc-4.5") +set(CTEST_CMAKE_GENERATOR "Unix Makefiles") +set(CTEST_BUILD_FLAGS "-j") +set(CTEST_BUILD_CONFIGURATION Debug) +set(CTEST_PARALLEL_LEVEL 4) + +set(US_TEST_SHARED 1) +set(US_TEST_STATIC 1) + +set(US_SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/../") + +set(US_BUILD_CONFIGURATION ) +foreach(i RANGE 31) + list(APPEND US_BUILD_CONFIGURATION ${i}) +endforeach() + +include(${US_SOURCE_DIR}/CMake/usCTestScript.cmake) diff --git a/CMake/usCTestScript_travis.cmake b/CMake/usCTestScript_travis.cmake new file mode 100644 index 0000000000..aea8b9e2ac --- /dev/null +++ b/CMake/usCTestScript_travis.cmake @@ -0,0 +1,17 @@ + +find_program(CTEST_COVERAGE_COMMAND NAMES gcov) +find_program(CTEST_MEMORYCHECK_COMMAND NAMES valgrind) +find_program(CTEST_GIT_COMMAND NAMES git) + +set(CTEST_SITE "travis-ci") +set(CTEST_DASHBOARD_ROOT "/tmp") +#set(CTEST_COMPILER "gcc-4.5") +set(CTEST_CMAKE_GENERATOR "Unix Makefiles") +set(CTEST_BUILD_FLAGS "-j") +set(CTEST_BUILD_CONFIGURATION Release) + + +set(US_SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/../") + +set(US_BUILD_CONFIGURATION $ENV{BUILD_CONFIGURATION}) +include(${US_SOURCE_DIR}/CMake/usCTestScript.cmake) diff --git a/CMake/usExecutableInit.cpp b/CMake/usExecutableInit.cpp new file mode 100644 index 0000000000..6e43c3d884 --- /dev/null +++ b/CMake/usExecutableInit.cpp @@ -0,0 +1,24 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +US_INITIALIZE_EXECUTABLE("@US_EXECUTABLE_IDENTIFIER@") diff --git a/CMake/usFunctionCheckCompilerFlags.cmake b/CMake/usFunctionCheckCompilerFlags.cmake new file mode 100644 index 0000000000..4907ce5786 --- /dev/null +++ b/CMake/usFunctionCheckCompilerFlags.cmake @@ -0,0 +1,52 @@ +# +# Helper macro allowing to check if the given flags are supported +# by the underlying build tool +# +# If the flag(s) is/are supported, they will be appended to the string identified by RESULT_VAR +# +# Usage: +# usFunctionCheckCompilerFlags(FLAGS_TO_CHECK VALID_FLAGS_VAR) +# +# Example: +# +# set(myflags) +# usFunctionCheckCompilerFlags("-fprofile-arcs" myflags) +# message(1-myflags:${myflags}) +# usFunctionCheckCompilerFlags("-fauto-bugfix" myflags) +# message(2-myflags:${myflags}) +# usFunctionCheckCompilerFlags("-Wall" myflags) +# message(1-myflags:${myflags}) +# +# The output will be: +# 1-myflags: -fprofile-arcs +# 2-myflags: -fprofile-arcs +# 3-myflags: -fprofile-arcs -Wall + +include(TestCXXAcceptsFlag) + +function(usFunctionCheckCompilerFlags CXX_FLAG_TO_TEST RESULT_VAR) + + if(CXX_FLAG_TO_TEST STREQUAL "") + message(FATAL_ERROR "CXX_FLAG_TO_TEST shouldn't be empty") + endif() + + set(_test_flag ${CXX_FLAG_TO_TEST}) + CHECK_CXX_ACCEPTS_FLAG("-Werror=unknown-warning-option" HAS_FLAG_unknown-warning-option) + if(HAS_FLAG_unknown-warning-option) + set(_test_flag "-Werror=unknown-warning-option ${CXX_FLAG_TO_TEST}") + endif() + + # Internally, the macro CMAKE_CXX_ACCEPTS_FLAG calls TRY_COMPILE. To avoid + # the cost of compiling the test each time the project is configured, the variable set by + # the macro is added to the cache so that following invocation of the macro with + # the same variable name skip the compilation step. + # For that same reason, usFunctionCheckCompilerFlags function appends a unique suffix to + # the HAS_FLAG variable. This suffix is created using a 'clean version' of the flag to test. + string(REGEX REPLACE "-\\s\\$\\+\\*\\{\\}\\(\\)\\#" "" suffix ${CXX_FLAG_TO_TEST}) + CHECK_CXX_ACCEPTS_FLAG(${_test_flag} HAS_FLAG_${suffix}) + + if(HAS_FLAG_${suffix}) + set(${RESULT_VAR} "${${RESULT_VAR}} ${CXX_FLAG_TO_TEST}" PARENT_SCOPE) + endif() + +endfunction() diff --git a/CMake/usFunctionCompileSnippets.cmake b/CMake/usFunctionCompileSnippets.cmake new file mode 100644 index 0000000000..47f67f503f --- /dev/null +++ b/CMake/usFunctionCompileSnippets.cmake @@ -0,0 +1,48 @@ +function(usFunctionCompileSnippets snippet_path) + + # get all files called "main.cpp" + file(GLOB_RECURSE main_cpp_list "${snippet_path}/main.cpp") + + foreach(main_cpp_file ${main_cpp_list}) + # get the directory containing the main.cpp file + get_filename_component(main_cpp_dir "${main_cpp_file}" PATH) + + set(snippet_src_files ) + + # If there exists a "files.cmake" file in the snippet directory, + # include it and assume it sets the variable "snippet_src_files" + # to a list of source files for the snippet. + if(EXISTS "${main_cpp_dir}/files.cmake") + include("${main_cpp_dir}/files.cmake") + set(_tmp_src_files ${snippet_src_files}) + set(snippet_src_files ) + foreach(_src_file ${_tmp_src_files}) + if(IS_ABSOLUTE ${_src_file}) + list(APPEND snippet_src_files ${_src_file}) + else() + list(APPEND snippet_src_files ${main_cpp_dir}/${_src_file}) + endif() + endforeach() + else() + # glob all files in the directory and add them to the snippet src list + file(GLOB_RECURSE snippet_src_files "${main_cpp_dir}/*") + endif() + + # Uset the top-level directory name as the executable name + string(REPLACE "/" ";" main_cpp_dir_tokens "${main_cpp_dir}") + list(GET main_cpp_dir_tokens -1 snippet_exec_name) + set(snippet_target_name "Snippet-${snippet_exec_name}") + + add_executable(${snippet_target_name} ${snippet_src_files}) + target_link_libraries(${snippet_target_name} ${US_LIBRARY_TARGET} ${snippet_link_libraries}) + set_target_properties(${snippet_target_name} PROPERTIES + LABELS Documentation + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/snippets" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/snippets" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/snippets" + OUTPUT_NAME ${snippet_exec_name} + ) + + endforeach() + +endfunction() diff --git a/CMake/usFunctionCreateTestModule.cmake b/CMake/usFunctionCreateTestModule.cmake new file mode 100644 index 0000000000..2ff602e560 --- /dev/null +++ b/CMake/usFunctionCreateTestModule.cmake @@ -0,0 +1,42 @@ + +macro(_us_create_test_module_helper) + + if(_res_files) + usFunctionEmbedResources(_srcs LIBRARY_NAME ${name} ROOT_DIR ${_res_root} FILES ${_res_files}) + endif() + + add_library(${name} ${_srcs}) + if(NOT US_BUILD_SHARED_LIBS) + set_property(TARGET ${name} APPEND PROPERTY COMPILE_DEFINITIONS US_STATIC_MODULE) + endif() + + if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64") + get_property(_compile_flags TARGET ${name} PROPERTY COMPILE_FLAGS) + set_property(TARGET ${name} PROPERTY COMPILE_FLAGS "${_compile_flags} -fPIC") + endif() + + target_link_libraries(${name} ${US_LIBRARY_TARGET} ${US_LINK_LIBRARIES}) + + set(_us_test_module_libs "${_us_test_module_libs};${name}" CACHE INTERNAL "" FORCE) + +endmacro() + +function(usFunctionCreateTestModule name) + set(_srcs ${ARGN}) + set(_res_files ) + usFunctionGenerateModuleInit(_srcs NAME "${name} Module" LIBRARY_NAME ${name}) + _us_create_test_module_helper() +endfunction() + +function(usFunctionCreateTestModuleWithResources name) + cmake_parse_arguments(US_TEST "" "RESOURCES_ROOT" "SOURCES;RESOURCES" "" ${ARGN}) + set(_srcs ${US_TEST_SOURCES}) + set(_res_files ${US_TEST_RESOURCES}) + if(US_TEST_RESOURCES_ROOT) + set(_res_root ${US_TEST_RESOURCES_ROOT}) + else() + set(_res_root resources) + endif() + usFunctionGenerateModuleInit(_srcs NAME "${name} Module" LIBRARY_NAME ${name}) + _us_create_test_module_helper() +endfunction() diff --git a/CMake/usFunctionEmbedResources.cmake b/CMake/usFunctionEmbedResources.cmake new file mode 100644 index 0000000000..7452c168d1 --- /dev/null +++ b/CMake/usFunctionEmbedResources.cmake @@ -0,0 +1,148 @@ +#! \ingroup MicroServicesCMake +#! \brief Embed resources into a shared library or executable. +#! +#! This CMake function uses an external command line program to generate a source +#! file containing data from external resources such as text files or images. The path +#! to the generated source file is appended to the \c src_var variable. +#! +#! Each module can call this function (at most once) to embed resources and make them +#! available at runtime through the Module class. Resources can also be embedded into +#! executables, using the EXECUTABLE_NAME argument instead of LIBRARY_NAME. +#! +#! Example usage: +#! \code{.cmake} +#! set(module_srcs ) +#! usFunctionEmbedResources(module_srcs +#! LIBRARY_NAME "mylib" +#! ROOT_DIR resources +#! FILES config.properties logo.png +#! ) +#! \endcode +#! +#! \param LIBRARY_NAME (required if EXECUTABLE_NAME is empty) The library name of the module +#! which will include the generated source file, without extension. +#! \param EXECUTABLE_NAME (required if LIBRARY_NAME is empty) The name of the executable +#! which will include the generated source file. +#! \param COMPRESSION_LEVEL (optional) The zip compression level. Defaults to the default zip +#! level. Level 0 disables compression. +#! \param COMPRESSION_THRESHOLD (optional) The compression threshold ranging from 0 to 100 for +#! actually compressing the resource data. The default threshold is 30, meaning a size +#! reduction of 30 percent or better results in the resource data being compressed. +#! \param ROOT_DIR (optional) The root path for all resources listed after the FILES argument. +#! If no or a relative path is given, it is considered relativ to the current CMake source directory. +#! \param FILES (optional) A list of resources (paths to external files in the file system) relative +#! to the ROOT_DIR argument or the current CMake source directory if ROOT_DIR is empty. +#! +#! The ROOT_DIR and FILES arguments may be repeated any number of times to merge files from +#! different root directories into the embedded resource tree (hence the relative file paths +#! after the FILES argument must be unique). +#! +function(usFunctionEmbedResources src_var) + + set(prefix US_RESOURCE) + set(arg_names LIBRARY_NAME EXECUTABLE_NAME COMPRESSION_LEVEL COMPRESSION_THRESHOLD ROOT_DIR FILES) + foreach(arg_name ${arg_names}) + set(${prefix}_${arg_name}) + endforeach(arg_name) + + set(cmd_line_args ) + set(absolute_res_files ) + set(current_arg_name DEFAULT_ARGS) + set(current_arg_list) + set(current_root_dir ${CMAKE_CURRENT_SOURCE_DIR}) + foreach(arg ${ARGN}) + + list(FIND arg_names "${arg}" is_arg_name) + + if(is_arg_name GREATER -1) + set(${prefix}_${current_arg_name} ${current_arg_list}) + set(current_arg_name "${arg}") + set(current_arg_list) + else() + set(current_arg_list ${current_arg_list} "${arg}") + if(current_arg_name STREQUAL "ROOT_DIR") + set(current_root_dir "${arg}") + if(NOT IS_ABSOLUTE ${current_root_dir}) + set(current_root_dir "${CMAKE_CURRENT_SOURCE_DIR}/${current_root_dir}") + endif() + if(NOT IS_DIRECTORY ${current_root_dir}) + message(SEND_ERROR "The ROOT_DIR argument is not a directory: ${current_root_dir}") + endif() + get_filename_component(current_root_dir "${current_root_dir}" REALPATH) + file(TO_NATIVE_PATH "${current_root_dir}" current_root_dir_native) + list(APPEND cmd_line_args -d "${current_root_dir_native}") + elseif(current_arg_name STREQUAL "FILES") + set(res_file "${current_root_dir}/${arg}") + file(TO_NATIVE_PATH "${res_file}" res_file_native) + if(IS_DIRECTORY ${res_file}) + message(SEND_ERROR "A resource cannot be a directory: ${res_file_native}") + endif() + if(NOT EXISTS ${res_file}) + message(SEND_ERROR "Resource does not exists: ${res_file_native}") + endif() + list(APPEND absolute_res_files ${res_file}) + file(TO_NATIVE_PATH "${arg}" res_filename_native) + list(APPEND cmd_line_args "${res_filename_native}") + endif() + endif(is_arg_name GREATER -1) + + endforeach(arg ${ARGN}) + + set(${prefix}_${current_arg_name} ${current_arg_list}) + + if(NOT src_var) + message(SEND_ERROR "Output variable name not specified.") + endif() + + if(US_RESOURCE_EXECUTABLE_NAME AND US_RESOURCE_LIBRARY_NAME) + message(SEND_ERROR "Only one of LIBRARY_NAME or EXECUTABLE_NAME can be specified.") + endif() + + if(NOT US_RESOURCE_LIBRARY_NAME AND NOT US_RESOURCE_EXECUTABLE_NAME) + message(SEND_ERROR "LIBRARY_NAME or EXECUTABLE_NAME argument not specified.") + endif() + + if(NOT US_RESOURCE_FILES) + message(WARNING "No FILES argument given. Skipping resource processing.") + return() + endif() + + list(GET cmd_line_args 0 first_arg) + if(NOT first_arg STREQUAL "-d") + set(cmd_line_args -d "${CMAKE_CURRENT_SOURCE_DIR}" ${cmd_line_args}) + endif() + + if(US_RESOURCE_COMPRESSION_LEVEL) + set(cmd_line_args -c ${US_RESOURCE_COMPRESSION_LEVEL} ${cmd_line_args}) + endif() + + if(US_RESOURCE_COMPRESSION_THRESHOLD) + set(cmd_line_args -t ${US_RESOURCE_COMPRESSION_THRESHOLD} ${cmd_line_args}) + endif() + + if(US_RESOURCE_LIBRARY_NAME) + set(us_cpp_resource_file "${CMAKE_CURRENT_BINARY_DIR}/${US_RESOURCE_LIBRARY_NAME}_resources.cpp") + set(us_lib_name ${US_RESOURCE_LIBRARY_NAME}) + else() + set(us_cpp_resource_file "${CMAKE_CURRENT_BINARY_DIR}/${US_RESOURCE_EXECUTABLE_NAME}_resources.cpp") + set(us_lib_name "\"\"") + endif() + + set(resource_compiler ${CppMicroServices_RCC_EXECUTABLE}) + if(TARGET ${CppMicroServices_RCC_EXECUTABLE_NAME}) + set(resource_compiler ${CppMicroServices_RCC_EXECUTABLE_NAME}) + elseif(NOT resource_compiler) + message(FATAL_ERROR "The CppMicroServices resource compiler was not found. Check the CppMicroServices_RCC_EXECUTABLE CMake variable.") + endif() + + add_custom_command( + OUTPUT ${us_cpp_resource_file} + COMMAND ${resource_compiler} "${us_lib_name}" ${us_cpp_resource_file} ${cmd_line_args} + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + DEPENDS ${absolute_res_files} ${resource_compiler} + COMMENT "Generating embedded resource file ${us_cpp_resource_name}" + ) + + set(${src_var} "${${src_var}};${us_cpp_resource_file}" PARENT_SCOPE) + +endfunction() diff --git a/CMake/usFunctionGenerateExecutableInit.cmake b/CMake/usFunctionGenerateExecutableInit.cmake new file mode 100644 index 0000000000..fc4030cf80 --- /dev/null +++ b/CMake/usFunctionGenerateExecutableInit.cmake @@ -0,0 +1,43 @@ +#! \ingroup MicroServicesCMake +#! \brief Generate a source file which handles proper initialization of an executable. +#! +#! This CMake function will store the path to a generated source file in the +#! src_var variable, which should be compiled into an executable. Example usage: +#! +#! \code{.cmake} +#! set(executable_srcs ) +#! usFunctionGenerateExecutableInit(executable_srcs +#! IDENTIFIER "MyExecutable" +#! ) +#! add_executable(MyExecutable ${executable_srcs}) +#! \endcode +#! +#! \param src_var (required) The name of a list variable to which the path of the generated +#! source file will be appended. +#! \param IDENTIFIER (required) A valid C identifier for the executable. +#! +#! \see #usFunctionGenerateModuleInit +#! \see \ref MicroServices_AutoLoading +#! +function(usFunctionGenerateExecutableInit src_var) + + cmake_parse_arguments(US_EXECUTABLE "" "IDENTIFIER" "" ${ARGN}) + + # sanity checks + if(NOT US_EXECUTABLE_IDENTIFIER) + message(SEND_ERROR "IDENTIFIER argument is mandatory") + endif() + + set(_regex_validation "[a-zA-Z_-][a-zA-Z_0-9-]*") + string(REGEX MATCH ${_regex_validation} _valid_chars ${US_EXECUTABLE_IDENTIFIER}) + if(NOT _valid_chars STREQUAL US_EXECUTABLE_IDENTIFIER) + message(FATAL_ERROR "IDENTIFIER contains illegal characters.") + endif() + + set(exec_init_src_file "${CMAKE_CURRENT_BINARY_DIR}/${US_EXECUTABLE_IDENTIFIER}_init.cpp") + configure_file(${CppMicroServices_EXECUTABLE_INIT_TEMPLATE} ${exec_init_src_file} @ONLY) + + set(_src ${${src_var}} ${exec_init_src_file}) + set(${src_var} ${_src} PARENT_SCOPE) + +endfunction() diff --git a/CMake/usFunctionGenerateModuleInit.cmake b/CMake/usFunctionGenerateModuleInit.cmake new file mode 100644 index 0000000000..e02cb839cb --- /dev/null +++ b/CMake/usFunctionGenerateModuleInit.cmake @@ -0,0 +1,54 @@ +#! \ingroup MicroServicesCMake +#! \brief Generate a source file which handles proper initialization of a module. +#! +#! This CMake function will store the path to a generated source file in the +#! src_var variable, which should be compiled into a module. Example usage: +#! +#! \code{.cmake} +#! set(module_srcs ) +#! usFunctionGenerateModuleInit(module_srcs +#! NAME "My Module" +#! LIBRARY_NAME "mylib" +#! ) +#! add_library(mylib ${module_srcs}) +#! \endcode +#! +#! \param src_var (required) The name of a list variable to which the path of the generated +#! source file will be appended. +#! \param NAME (required) A human-readable name for the module. +#! \param LIBRARY_NAME (optional) The name of the module, without extension. If empty, the +#! NAME argument will be used. +#! +#! \see #usFunctionGenerateExecutableInit +#! \see \ref MicroServices_AutoLoading +#! +function(usFunctionGenerateModuleInit src_var) + + cmake_parse_arguments(US_MODULE "EXECUTABLE" "NAME;LIBRARY_NAME" "" ${ARGN}) + + if(US_MODULE_EXECUTABLE) + message(SEND_ERROR "EXECUTABLE option no longer supported. Use usFunctionGenerateExecutableInit instead.") + endif() + + # sanity checks + if(NOT US_MODULE_NAME) + message(SEND_ERROR "NAME argument is mandatory") + endif() + + if(NOT US_MODULE_LIBRARY_NAME) + set(US_MODULE_LIBRARY_NAME ${US_MODULE_NAME}) + endif() + + set(_regex_validation "[a-zA-Z_-][a-zA-Z_0-9-]*") + string(REGEX MATCH ${_regex_validation} _valid_chars ${US_MODULE_LIBRARY_NAME}) + if(NOT _valid_chars STREQUAL US_MODULE_LIBRARY_NAME) + message(FATAL_ERROR "[Module: ${US_MODULE_NAME}] LIBRARY_NAME \"${US_MODULE_LIBRARY_NAME}\" contains illegal characters.") + endif() + + set(module_init_src_file "${CMAKE_CURRENT_BINARY_DIR}/${US_MODULE_LIBRARY_NAME}_init.cpp") + configure_file(${CppMicroServices_MODULE_INIT_TEMPLATE} ${module_init_src_file} @ONLY) + + set(_src ${${src_var}} ${module_init_src_file}) + set(${src_var} ${_src} PARENT_SCOPE) + +endfunction() diff --git a/CMake/usFunctionGetGccVersion.cmake b/CMake/usFunctionGetGccVersion.cmake new file mode 100644 index 0000000000..022fa606cf --- /dev/null +++ b/CMake/usFunctionGetGccVersion.cmake @@ -0,0 +1,18 @@ + +#! \brief Get the gcc version +function(usFunctionGetGccVersion path_to_gcc output_var) + if(CMAKE_COMPILER_IS_GNUCXX) + execute_process( + COMMAND ${path_to_gcc} -dumpversion + RESULT_VARIABLE result + OUTPUT_VARIABLE output + ERROR_VARIABLE error + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_STRIP_TRAILING_WHITESPACE + ) + if(result) + message(FATAL_ERROR "Failed to obtain compiler version running [${path_to_gcc} -dumpversion]: ${error}") + endif() + set(${output_var} ${output} PARENT_SCOPE) + endif() +endfunction() diff --git a/CMake/usModuleInit.cpp b/CMake/usModuleInit.cpp new file mode 100644 index 0000000000..05678e8649 --- /dev/null +++ b/CMake/usModuleInit.cpp @@ -0,0 +1,24 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +US_INITIALIZE_MODULE("@US_MODULE_NAME@", "@US_MODULE_LIBRARY_NAME@") diff --git a/CMake/usPublicHeaderWrapper.h.in b/CMake/usPublicHeaderWrapper.h.in new file mode 100644 index 0000000000..556302f562 --- /dev/null +++ b/CMake/usPublicHeaderWrapper.h.in @@ -0,0 +1 @@ +#include "@_us_public_header@" diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000000..f15f788bbe --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,375 @@ +project(CppMicroServices) + +set(${PROJECT_NAME}_MAJOR_VERSION 1) +set(${PROJECT_NAME}_MINOR_VERSION 99) +set(${PROJECT_NAME}_PATCH_VERSION 0) +set(${PROJECT_NAME}_VERSION ${${PROJECT_NAME}_MAJOR_VERSION}.${${PROJECT_NAME}_MINOR_VERSION}.${${PROJECT_NAME}_PATCH_VERSION}) + +cmake_minimum_required(VERSION 2.8) +cmake_policy(VERSION 2.8) +cmake_policy(SET CMP0017 NEW) + +#----------------------------------------------------------------------------- +# Update CMake module path +#------------------------------------------------------------------------------ + +set(CMAKE_MODULE_PATH + ${PROJECT_SOURCE_DIR}/CMake + ${CMAKE_MODULE_PATH} + ) + +#----------------------------------------------------------------------------- +# CMake function(s) and macro(s) +#----------------------------------------------------------------------------- + +include(CMakeParseArguments) +include(CMakePackageConfigHelpers) +include(CheckCXXSourceCompiles) +include(usFunctionCheckCompilerFlags) +include(usFunctionEmbedResources) +include(usFunctionGetGccVersion) +include(usFunctionGenerateModuleInit) +include(usFunctionGenerateExecutableInit) + +#----------------------------------------------------------------------------- +# Init output directories +#----------------------------------------------------------------------------- + +set(US_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") +set(US_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") +set(US_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") + +foreach(_type ARCHIVE LIBRARY RUNTIME) + if(NOT CMAKE_${_type}_OUTPUT_DIRECTORY) + set(CMAKE_${_type}_OUTPUT_DIRECTORY ${US_${_type}_OUTPUT_DIRECTORY}) + endif() +endforeach() + +#----------------------------------------------------------------------------- +# Set a default build type if none was specified +#----------------------------------------------------------------------------- + +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + message(STATUS "Setting build type to 'Debug' as none was specified.") + set(CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build." FORCE) + + # Set the possible values of build type for cmake-gui + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY + STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") +endif() + +#----------------------------------------------------------------------------- +# CMake options +#----------------------------------------------------------------------------- + +function(us_cache_var _var_name _var_default _var_type _var_help) + set(_advanced 0) + set(_force) + foreach(_argn ${ARGN}) + if(_argn STREQUAL ADVANCED) + set(_advanced 1) + elseif(_argn STREQUAL FORCE) + set(_force FORCE) + endif() + endforeach() + + if(US_IS_EMBEDDED) + if(NOT DEFINED ${_var_name} OR _force) + set(${_var_name} ${_var_default} PARENT_SCOPE) + endif() + else() + set(${_var_name} ${_var_default} CACHE ${_var_type} "${_var_help}" ${_force}) + if(_advanced) + mark_as_advanced(${_var_name}) + endif() + endif() +endfunction() + +# Determine if we are being build inside a larger project +if(NOT DEFINED US_IS_EMBEDDED) + if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) + set(US_IS_EMBEDDED 0) + else() + set(US_IS_EMBEDDED 1) + set(CppMicroServices_EXPORTS 1) + endif() +endif() + +us_cache_var(US_ENABLE_AUTOLOADING_SUPPORT OFF BOOL "Enable module auto-loading support") +us_cache_var(US_ENABLE_THREADING_SUPPORT OFF BOOL "Enable threading support") +us_cache_var(US_ENABLE_DEBUG_OUTPUT OFF BOOL "Enable debug messages" ADVANCED) +us_cache_var(US_ENABLE_RESOURCE_COMPRESSION ON BOOL "Enable resource compression" ADVANCED) +us_cache_var(US_BUILD_SHARED_LIBS ON BOOL "Build shared libraries") +us_cache_var(US_BUILD_TESTING OFF BOOL "Build tests") + +if(WIN32 AND NOT CYGWIN) + set(default_runtime_install_dir bin/) + set(default_library_install_dir bin/) + set(default_archive_install_dir lib/) + set(default_header_install_dir include/) + set(default_auxiliary_install_dir share/) +else() + set(default_runtime_install_dir bin/) + set(default_library_install_dir lib/${PROJECT_NAME}) + set(default_archive_install_dir lib/${PROJECT_NAME}) + set(default_header_install_dir include/${PROJECT_NAME}) + set(default_auxiliary_install_dir share/${PROJECT_NAME}) +endif() + +us_cache_var(RUNTIME_INSTALL_DIR ${default_runtime_install_dir} STRING "Relative install location for binaries" ADVANCED) +us_cache_var(LIBRARY_INSTALL_DIR ${default_library_install_dir} STRING "Relative install location for libraries" ADVANCED) +us_cache_var(ARCHIVE_INSTALL_DIR ${default_archive_install_dir} STRING "Relative install location for archives" ADVANCED) +us_cache_var(HEADER_INSTALL_DIR ${default_header_install_dir} STRING "Relative install location for headers" ADVANCED) +us_cache_var(AUXILIARY_INSTALL_DIR ${default_auxiliary_install_dir} STRING "Relative install location for auxiliary files" ADVANCED) + +if(MSVC10 OR MSVC11 OR MSVC12) + # Visual Studio 2010 and newer have support for C++11 enabled by default + set(US_USE_C++11 1) +else() + us_cache_var(US_USE_C++11 OFF BOOL "Enable the use of C++11 features" ADVANCED) +endif() + +us_cache_var(US_NAMESPACE "us" STRING "The namespace for the C++ micro services entities") +us_cache_var(US_HEADER_PREFIX "" STRING "The file name prefix for the public C++ micro services header files") + +set(BUILD_SHARED_LIBS ${US_BUILD_SHARED_LIBS}) + +set(${PROJECT_NAME}_MODULE_INIT_TEMPLATE "${CMAKE_CURRENT_SOURCE_DIR}/CMake/usModuleInit.cpp") +set(${PROJECT_NAME}_EXECUTABLE_INIT_TEMPLATE "${CMAKE_CURRENT_SOURCE_DIR}/CMake/usExecutableInit.cpp") + +#----------------------------------------------------------------------------- +# US C/CXX Flags +#----------------------------------------------------------------------------- + +set(US_C_FLAGS) +set(US_C_FLAGS_RELEASE) +set(US_CXX_FLAGS) +set(US_CXX_FLAGS_RELEASE) + +# This is used as a preprocessor define +set(US_USE_CXX11 ${US_USE_C++11}) + +# Set C++ compiler flags +if(NOT MSVC) + foreach(_cxxflag -Werror -Wall -Wextra -Wpointer-arith -Winvalid-pch -Wcast-align + -Wwrite-strings -Woverloaded-virtual -Wnon-virtual-dtor -Wold-style-cast + -Wstrict-null-sentinel -Wsign-promo -fdiagnostics-show-option) + usFunctionCheckCompilerFlags(${_cxxflag} US_CXX_FLAGS) + endforeach() + + if(US_USE_C++11) + usFunctionCheckCompilerFlags("-std=c++0x" US_CXX_FLAGS) + endif() +endif() + +if(CMAKE_COMPILER_IS_GNUCXX) + + usFunctionGetGccVersion(${CMAKE_CXX_COMPILER} GCC_VERSION) + if(${GCC_VERSION} VERSION_LESS "4.0.0") + message(FATAL_ERROR "gcc version ${GCC_VERSION} not supported. Please use gcc >= 4.") + endif() + + # With older versions of gcc the flag -fstack-protector-all requires an extra dependency to libssp.so. + # If the gcc version is lower than 4.4.0 and the build type is Release let's not include the flag. + if(${GCC_VERSION} VERSION_GREATER "4.4.0" OR (CMAKE_BUILD_TYPE STREQUAL "Debug" AND ${GCC_VERSION} VERSION_LESS "4.4.0")) + usFunctionCheckCompilerFlags("-fstack-protector-all" US_CXX_FLAGS) + endif() + + if(MINGW) + # suppress warnings about auto imported symbols + set(US_CXX_FLAGS "-Wl,--enable-auto-import ${US_CXX_FLAGS}") + # we need to define a Windows version + set(US_CXX_FLAGS "-D_WIN32_WINNT=0x0500 ${US_CXX_FLAGS}") + else() + # Enable visibility support + if(NOT ${GCC_VERSION} VERSION_LESS "4.5") + usFunctionCheckCompilerFlags("-fvisibility=hidden -fvisibility-inlines-hidden" US_CXX_FLAGS) + else() + set(US_GCC_RTTI_WORKAROUND_NEEDED 1) + endif() + endif() + + usFunctionCheckCompilerFlags("-O1 -D_FORTIFY_SOURCE=2" _fortify_source_flag) + if(_fortify_source_flag) + set(US_CXX_FLAGS_RELEASE "${US_CXX_FLAGS_RELEASE} -D_FORTIFY_SOURCE=2") + endif() + + +elseif(MSVC) + set(US_CXX_FLAGS "/MP /wd4996 ${US_CXX_FLAGS}") +endif() + +if(NOT US_IS_EMBEDDED) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${US_CXX_FLAGS}") + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${US_CXX_FLAGS_RELEASE}") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${US_C_FLAGS}") + set(CMAKE_C_FLAGS_REALEASE "${CMAKE_C_FLAGS_RELEASE} ${US_C_FLAGS_RELEASE}") +endif() + +#----------------------------------------------------------------------------- +# US Link Flags +#----------------------------------------------------------------------------- + +set(US_LINK_FLAGS ) +if(NOT MSVC) + foreach(_linkflag -Wl,--no-undefined) + set(_add_flag) + usFunctionCheckCompilerFlags("${_linkflag}" _add_flag) + if(_add_flag) + set(US_LINK_FLAGS "${US_LINK_FLAGS} ${_linkflag}") + endif() + endforeach() +endif() + +#----------------------------------------------------------------------------- +# US Header Checks +#----------------------------------------------------------------------------- + +include(CheckIncludeFile) + +CHECK_INCLUDE_FILE(stdint.h HAVE_STDINT) + +#----------------------------------------------------------------------------- +# US include dirs and libraries +#----------------------------------------------------------------------------- + +set(US_INCLUDE_DIRS + ${PROJECT_BINARY_DIR}/include +) + +set(US_INTERNAL_INCLUDE_DIRS + ${PROJECT_BINARY_DIR}/include + ${CMAKE_CURRENT_SOURCE_DIR}/src/util + ${CMAKE_CURRENT_SOURCE_DIR}/src/service + ${CMAKE_CURRENT_SOURCE_DIR}/src/module +) + +# link library for third party libs +if(US_IS_EMBEDDED) + set(US_LIBRARY_TARGET ${US_EMBEDDING_LIBRARY}) +else() + set(US_LIBRARY_TARGET ${PROJECT_NAME}) +endif() + +# link libraries for the CppMicroServices lib +set(US_LINK_LIBRARIES ) +if(UNIX) + list(APPEND US_LINK_LIBRARIES dl) +endif() + +#----------------------------------------------------------------------------- +# Source directory +#----------------------------------------------------------------------------- + +set(us_config_h_file "${PROJECT_BINARY_DIR}/include/usConfig.h") +configure_file(usConfig.h.in ${us_config_h_file}) + +set(US_RCC_EXECUTABLE_NAME usResourceCompiler) +set(CppMicroServices_RCC_EXECUTABLE_NAME ${US_RCC_EXECUTABLE_NAME}) + +add_subdirectory(tools) + +add_subdirectory(src) + + +#----------------------------------------------------------------------------- +# US testing +#----------------------------------------------------------------------------- + +if(US_BUILD_TESTING) + enable_testing() + add_subdirectory(test) +endif() + +#----------------------------------------------------------------------------- +# Documentation +#----------------------------------------------------------------------------- + +add_subdirectory(documentation) + +#----------------------------------------------------------------------------- +# Last configuration and install steps +#----------------------------------------------------------------------------- + +if(NOT US_IS_EMBEDDED) + export(TARGETS ${PROJECT_NAME} ${US_RCC_EXECUTABLE_NAME} + FILE ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Targets.cmake) + install(EXPORT ${PROJECT_NAME}Targets + FILE ${PROJECT_NAME}Targets.cmake + DESTINATION ${AUXILIARY_INSTALL_DIR}/CMake/) +endif() + +set(_install_cmake_scripts + ${${PROJECT_NAME}_MODULE_INIT_TEMPLATE} + ${${PROJECT_NAME}_EXECUTABLE_INIT_TEMPLATE} + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/CMakeParseArguments.cmake + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/usFunctionGenerateModuleInit.cmake + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/usFunctionGenerateExecutableInit.cmake + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/usFunctionEmbedResources.cmake + ) + +install(FILES ${_install_cmake_scripts} + DESTINATION ${AUXILIARY_INSTALL_DIR}/CMake/ + ) + +# Configure CppMicroServicesConfig.cmake for the build tree + +set(PACKAGE_CONFIG_INCLUDE_DIR ${US_INCLUDE_DIRS}) +set(PACKAGE_CONFIG_RUNTIME_DIR ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +set(PACKAGE_CONFIG_CMAKE_DIR ${PROJECT_SOURCE_DIR}/CMake) +if(US_IS_EMBEDDED) + set(PACKAGE_EMBEDDED "if(@PROJECT_NAME@_IS_EMBEDDED) + set(@PROJECT_NAME@_INTERNAL_INCLUDE_DIRS @US_INTERNAL_INCLUDE_DIRS@) + set(@PROJECT_NAME@_SOURCES @US_SOURCES@) + set(@PROJECT_NAME@_PUBLIC_HEADERS @US_PUBLIC_HEADERS@) + set(@PROJECT_NAME@_PRIVATE_HEADERS @US_PRIVATE_HEADERS@) +endif()") +else() + set(PACKAGE_EMBEDDED ) +endif() + +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}Config.cmake.in + ${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake + @ONLY + ) + +# Configure CppMicroServicesConfig.cmake for the install tree +set(CONFIG_INCLUDE_DIR ${HEADER_INSTALL_DIR}) +set(CONFIG_RUNTIME_DIR ${RUNTIME_INSTALL_DIR}) +set(CONFIG_CMAKE_DIR ${AUXILIARY_INSTALL_DIR}/CMake) +configure_package_config_file( + ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}Config.cmake.in + ${PROJECT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${PROJECT_NAME}Config.cmake + INSTALL_DESTINATION ${AUXILIARY_INSTALL_DIR}/CMake/ + PATH_VARS CONFIG_INCLUDE_DIR CONFIG_RUNTIME_DIR CONFIG_CMAKE_DIR + NO_SET_AND_CHECK_MACRO + NO_CHECK_REQUIRED_COMPONENTS_MACRO + ) + +# Version information +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}ConfigVersion.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake + @ONLY + ) + +install(FILES ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${PROJECT_NAME}Config.cmake + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake + DESTINATION ${AUXILIARY_INSTALL_DIR}/CMake/ + COMPONENT sdk + ) + +#----------------------------------------------------------------------------- +# Build the examples +#----------------------------------------------------------------------------- + +option(US_BUILD_EXAMPLES "Build example projects" OFF) +if(US_BUILD_EXAMPLES) + if(NOT US_BUILD_SHARED_LIBS) + message(WARNING "Examples are not available if US_BUILD_SHARED_LIBS is OFF") + else() + set(CppMicroServices_DIR ${PROJECT_BINARY_DIR}) + add_subdirectory(examples) + endif() +endif() diff --git a/CTestConfig.cmake b/CTestConfig.cmake new file mode 100644 index 0000000000..65ff58f092 --- /dev/null +++ b/CTestConfig.cmake @@ -0,0 +1,7 @@ +set(CTEST_PROJECT_NAME "CppMicroServices") +#set(CTEST_NIGHTLY_START_TIME "23:00:00 EDT") + +#set(CTEST_DROP_METHOD "http") +#set(CTEST_DROP_SITE "my.cdash.org") +#set(CTEST_DROP_LOCATION "/submit.php?project=${CTEST_PROJECT_NAME}") +#set(CTEST_DROP_SITE_CDASH TRUE) diff --git a/CppMicroServicesConfig.cmake.in b/CppMicroServicesConfig.cmake.in new file mode 100644 index 0000000000..0a8e57d74d --- /dev/null +++ b/CppMicroServicesConfig.cmake.in @@ -0,0 +1,36 @@ +@PACKAGE_INIT@ + +set(@PROJECT_NAME@_USE_CXX11 @US_USE_CXX11@) + +set(@PROJECT_NAME@_CXX_FLAGS "@US_CXX_FLAGS@") +set(@PROJECT_NAME@_CXX_FLAGS_RELEASE "@US_CXX_FLAGS_RELEASE@") +set(@PROJECT_NAME@_CXX_FLAGS_DEBUG "@US_CXX_FLAGS_DEBUG@") +set(@PROJECT_NAME@_C_FLAGS "@US_C_FLAGS@") +set(@PROJECT_NAME@_C_FLAGS_RELEASE "@US_C_FLAGS_RELEASE@") +set(@PROJECT_NAME@_C_FLAGS_DEBUG "@US_C_FLAGS_DEBUG@") + +set(@PROJECT_NAME@_INCLUDE_DIR @PACKAGE_CONFIG_INCLUDE_DIR@) + +set(@PROJECT_NAME@_RCC_EXECUTABLE_NAME @CppMicroServices_RCC_EXECUTABLE_NAME@) +set(@PROJECT_NAME@_MODULE_INIT_TEMPLATE @PACKAGE_CONFIG_CMAKE_DIR@/usModuleInit.cpp) +set(@PROJECT_NAME@_EXECUTABLE_INIT_TEMPLATE @PACKAGE_CONFIG_CMAKE_DIR@/usExecutableInit.cpp) + +set(@PROJECT_NAME@_INCLUDE_DIRS ${@PROJECT_NAME@_INCLUDE_DIR}) +set(@PROJECT_NAME@_LIBRARIES @US_LIBRARY_TARGET@) + +find_program(@PROJECT_NAME@_RCC_EXECUTABLE ${@PROJECT_NAME@_RCC_EXECUTABLE_NAME} + PATHS "@PACKAGE_CONFIG_RUNTIME_DIR@" + PATH_SUFFIXES Release Debug RelWithDebInfo MinSizeRel) +mark_as_advanced(@PROJECT_NAME@_RCC_EXECUTABLE) + +set(@PROJECT_NAME@_IS_EMBEDDED @US_IS_EMBEDDED@) +@PACKAGE_EMBEDDED@ + +if(NOT TARGET @PROJECT_NAME@ AND NOT @PROJECT_NAME@_IS_EMBEDDED) + include(${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake) +endif() + +include(@PACKAGE_CONFIG_CMAKE_DIR@/CMakeParseArguments.cmake) +include(@PACKAGE_CONFIG_CMAKE_DIR@/usFunctionGenerateModuleInit.cmake) +include(@PACKAGE_CONFIG_CMAKE_DIR@/usFunctionGenerateExecutableInit.cmake) +include(@PACKAGE_CONFIG_CMAKE_DIR@/usFunctionEmbedResources.cmake) diff --git a/CppMicroServicesConfigVersion.cmake.in b/CppMicroServicesConfigVersion.cmake.in new file mode 100644 index 0000000000..b5be35dea9 --- /dev/null +++ b/CppMicroServicesConfigVersion.cmake.in @@ -0,0 +1,34 @@ +# The created file sets PACKAGE_VERSION_EXACT if the current version string and +# the requested version string are exactly the same and it sets +# PACKAGE_VERSION_COMPATIBLE if the current version major number == requested version major number +# and the current version minor number >= requested version minor number + +set(PACKAGE_VERSION_MAJOR @CppMicroServices_MAJOR_VERSION@) +set(PACKAGE_VERSION_MINOR @CppMicroServices_MINOR_VERSION@) +set(PACKAGE_VERSION_PATCH @CppMicroServices_PATCH_VERSION@) +set(PACKAGE_VERSION "@CppMicroServices_VERSION@") + +if(PACKAGE_VERSION VERSION_EQUAL PACKAGE_FIND_VERSION) + set(PACKAGE_VERSION_EXACT TRUE) +else() + set(PACKAGE_VERSION_EXACT FALSE) + if(NOT PACKAGE_VERSION_MAJOR EQUAL PACKAGE_FIND_VERSION_MAJOR) + set(PACKAGE_VERSION_COMPATIBLE FALSE) + elseif(PACKAGE_VERSION_MINOR LESS PACKAGE_FIND_VERSION_MINOR) + set(PACKAGE_VERSION_COMPATIBLE FALSE) + else() + set(PACKAGE_VERSION_COMPATIBLE TRUE) + endif() +endif() + +# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it: +if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "@CMAKE_SIZEOF_VOID_P@" STREQUAL "") + return() +endif() + +# check that the installed version has the same 32/64bit-ness as the one which is currently searching: +if(NOT "${CMAKE_SIZEOF_VOID_P}" STREQUAL "@CMAKE_SIZEOF_VOID_P@") + math(EXPR installedBits "@CMAKE_SIZEOF_VOID_P@ * 8") + set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)") + set(PACKAGE_VERSION_UNSUITABLE TRUE) +endif() diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000000..2470e5f9a3 --- /dev/null +++ b/README.md @@ -0,0 +1,89 @@ +[![Build Status](https://secure.travis-ci.org/saschazelzer/CppMicroServices.png)](http://travis-ci.org/saschazelzer/CppMicroServices) + +C++ Micro Services +================== + +Introduction +------------ + +The C++ Micro Services library provides a dynamic service registry based on the +service layer as specified in the OSGi R4.2 specifications. It enables users to +realize a service oriented approach within their software stack. + +The advantages include higher reuse of components, looser coupling, better organization of +responsibilities, cleaner API contracts, etc. + +Requirements +------------ + +This is a pure C++ implementation of the OSGi service model and does not have any third-party +library dependencies. + +Supported Platforms +------------------- + +The library should compile on many different platforms. Below is a list of tested compiler/OS combinations: + + - GCC 4.5 (Ubuntu 11.04 and MacOS X 10.6) + - Visual Studio 2008 and 2010 + - Clang 3.0 (Ubuntu 11.04 and MacOS X 10.6) + +Legal +----- + +Copyright (c) German Cancer Research Center. Licensed under the [Apache License v2.0][apache_license]. + +Quick Start +----------- + +Essentially, the C++ Micro Services library provides you with a powerful dynamic service registry. +Each shared or static library has an associated `ModuleContext` object, through which the service +registry is accessed. + +To query the registry for a service object implementing one or more specific interfaces, the code +would look like this: + +```cpp +#include +#include + +using namespace us; + +void UseService(ModuleContext* context) +{ + ServiceReference serviceRef = context->GetServiceReference(); + if (serviceRef) + { + SomeInterface* service = context->GetService(serviceRef); + if (service) { /* do something */ } + } +} +``` + +Registering a service object against a certain interface looks like this: + +```cpp +#include +#include + +using namespace us; + +void RegisterSomeService(ModuleContext* context, SomeInterface* service) +{ + context->RegisterService(service); +} +``` + +The OSGi service model additionally allows to annotate services with properties and using these +properties during service look-ups. It also allows to track the life-cycle of service objects. +Please see the [Documentation](http://cppmicroservices.org/doc_latest/index.html) for more +examples and tutorials and the API reference. There is also a blog post about +[OSGi Lite for C++](http://blog.cppmicroservices.org/2012/04/15/osgi-lite-for-c++). + +Build Instructions +------------------ + +Please visit the [Build Instructions][bi_master] page online. + +[bi_master]: http://cppmicroservices.org/doc_latest/BuildInstructions.html +[apache_license]: http://www.apache.org/licenses/LICENSE-2.0 diff --git a/documentation/CMakeDoxygenFilter.cpp b/documentation/CMakeDoxygenFilter.cpp new file mode 100644 index 0000000000..7aba552149 --- /dev/null +++ b/documentation/CMakeDoxygenFilter.cpp @@ -0,0 +1,494 @@ +/*============================================================================= + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include + +#include + +//-------------------------------------- +// Utilitiy classes and functions +//-------------------------------------- + +struct ci_char_traits : public std::char_traits + // just inherit all the other functions + // that we don't need to override +{ + static bool eq(char c1, char c2) + { return toupper(c1) == toupper(c2); } + + static bool ne(char c1, char c2) + { return toupper(c1) != toupper(c2); } + + static bool lt(char c1, char c2) + { return toupper(c1) < toupper(c2); } + + static bool gt(char c1, char c2) + { return toupper(c1) > toupper(c2); } + + static int compare(const char* s1, const char* s2, std::size_t n) + { + while (n-- > 0) + { + if (lt(*s1, *s2)) return -1; + if (gt(*s1, *s2)) return 1; + ++s1; ++s2; + } + return 0; + } + + static const char* find(const char* s, int n, char a) + { + while (n-- > 0 && toupper(*s) != toupper(a)) + { + ++s; + } + return s; + } +}; + +typedef std::basic_string ci_string; + +//-------------------------------------- +// Lexer +//-------------------------------------- + +class CMakeLexer +{ +public: + + enum Token { + TOK_EOF = -1, + TOK_EOL = -2, + + // commands + TOK_MACRO = -3, TOK_ENDMACRO = -4, + TOK_FUNCTION = -5, TOK_ENDFUNCTION = -6, + TOK_DOXYGEN_COMMENT = -7, + TOK_SET = -8, + TOK_STRING_LITERAL = -100, + TOK_NUMBER_LITERAL = -102, + + // primary + TOK_IDENTIFIER = -200 + }; + + CMakeLexer(std::istream& is) + : _lastChar(' '), _is(is), _line(1), _col(1) + {} + + int getToken() + { + // skip whitespace + while (isspace(_lastChar) && _lastChar != '\r' && _lastChar != '\n') + { + _lastChar = getChar(); + } + + if (isalpha(_lastChar) || _lastChar == '_') + { + _identifier = _lastChar; + while (isalnum(_lastChar = getChar()) || _lastChar == '-' || _lastChar == '_') + { + _identifier += _lastChar; + } + + if (_identifier == "set") + return TOK_SET; + if (_identifier == "function") + return TOK_FUNCTION; + if (_identifier == "macro") + return TOK_MACRO; + if (_identifier == "endfunction") + return TOK_ENDFUNCTION; + if (_identifier == "endmacro") + return TOK_ENDMACRO; + return TOK_IDENTIFIER; + } + + if (isdigit(_lastChar)) + { + // very lax!! number detection + _identifier = _lastChar; + while (isalnum(_lastChar = getChar()) || _lastChar == '.' || _lastChar == ',') + { + _identifier += _lastChar; + } + return TOK_NUMBER_LITERAL; + } + + if (_lastChar == '#') + { + _lastChar = getChar(); + if (_lastChar == '!') + { + // found a doxygen comment marker + _identifier.clear(); + + _lastChar = getChar(); + while (_lastChar != EOF && _lastChar != '\n' && _lastChar != '\r') + { + _identifier += _lastChar; + _lastChar = getChar(); + } + return TOK_DOXYGEN_COMMENT; + } + + // skip the comment + while (_lastChar != EOF && _lastChar != '\n' && _lastChar != '\r') + { + _lastChar = getChar(); + } + } + + if (_lastChar == '"') + { + _lastChar = getChar(); + _identifier.clear(); + while (_lastChar != EOF && _lastChar != '"') + { + _identifier += _lastChar; + _lastChar = getChar(); + } + + // eat the closing " + _lastChar = getChar(); + return TOK_STRING_LITERAL; + } + + // don't eat the EOF + if (_lastChar == EOF) return TOK_EOF; + + // don't eat the EOL + if (_lastChar == '\r' || _lastChar == '\n') + { + if (_lastChar == '\r') _lastChar = getChar(); + if (_lastChar == '\n') _lastChar = getChar(); + return TOK_EOL; + } + + // return the character as its ascii value + int thisChar = _lastChar; + _lastChar = getChar(); + return thisChar; + } + + std::string getIdentifier() const + { + return std::string(_identifier.c_str()); + } + + int curLine() const + { return _line; } + + int curCol() const + { return _col; } + + int getChar() + { + int c = _is.get(); + updateLoc(c); + return c; + } + +private: + + void updateLoc(int c) + { + if (c == '\n' || c == '\r') + { + ++_line; + _col = 1; + } + else + { + ++_col; + } + } + + ci_string _identifier; + int _lastChar; + std::istream& _is; + + int _line; + int _col; +}; + +//-------------------------------------- +// Parser +//-------------------------------------- + +class CMakeParser +{ + +public: + + CMakeParser(std::istream& is, std::ostream& os) + : _is(is), _os(os), _lexer(is), _curToken(CMakeLexer::TOK_EOF), _lastToken(CMakeLexer::TOK_EOF) + { } + + int curToken() + { + return _curToken; + } + + int nextToken() + { + _lastToken = _curToken; + _curToken = _lexer.getToken(); + while (_curToken == CMakeLexer::TOK_EOL) + { + // Try to preserve lines in output to allow correct line number referencing by doxygen. + _os << std::endl; + _curToken = _lexer.getToken(); + } + return _curToken; + } + + void handleMacro() + { + if(!parseMacro()) + { + // skip token for error recovery + nextToken(); + } + } + + void handleFunction() + { + if(!parseFunction()) + { + // skip token for error recovery + nextToken(); + } + } + + void handleSet() + { + // SET(var ...) following a documentation block is assumed to be a variable declaration. + if (_lastToken != CMakeLexer::TOK_DOXYGEN_COMMENT) + { + // No comment block before + nextToken(); + } else if(!parseSet()) + { + // skip token for error recovery + nextToken(); + } + } + + void handleDoxygenComment() + { + _os << "///" << _lexer.getIdentifier(); + nextToken(); + } + + void handleTopLevelExpression() + { + // skip token + nextToken(); + } + +private: + + void printError(const char* str) + { + std::cerr << "Error: " << str << " (at line " << _lexer.curLine() << ", col " << _lexer.curCol() << ")"; + } + + bool parseMacro() + { + if (nextToken() != '(') + { + printError("Expected '(' after MACRO"); + return false; + } + + nextToken(); + std::string macroName = _lexer.getIdentifier(); + if (curToken() != CMakeLexer::TOK_IDENTIFIER || macroName.empty()) + { + printError("Expected macro name"); + return false; + } + + _os << macroName << '('; + if (nextToken() == CMakeLexer::TOK_IDENTIFIER) + { + _os << _lexer.getIdentifier(); + while (nextToken() == CMakeLexer::TOK_IDENTIFIER) + { + _os << ", " << _lexer.getIdentifier(); + } + } + + if (curToken() != ')') + { + printError("Missing expected ')'"); + } + else + { + _os << ");"; + } + + // eat the ')' + nextToken(); + return true; + } + + bool parseSet() + { + if (nextToken() != '(') + { + printError("Expected '(' after SET"); + return false; + } + + nextToken(); + std::string variableName = _lexer.getIdentifier(); + if (curToken() != CMakeLexer::TOK_IDENTIFIER || variableName.empty()) + { + printError("Expected variable name"); + return false; + } + + _os << "CMAKE_VARIABLE " << variableName; + + nextToken(); + while ((curToken() == CMakeLexer::TOK_IDENTIFIER) + || (curToken() == CMakeLexer::TOK_STRING_LITERAL) + || (curToken() == CMakeLexer::TOK_NUMBER_LITERAL)) + { + nextToken(); + } + + if (curToken() != ')') + { + printError("Missing expected ')'"); + } + else + { + _os << ";"; + } + + // eat the ')' + nextToken(); + return true; + } + + bool parseFunction() + { + if (nextToken() != '(') + { + printError("Expected '(' after FUNCTION"); + return false; + } + + nextToken(); + std::string funcName = _lexer.getIdentifier(); + if (curToken() != CMakeLexer::TOK_IDENTIFIER || funcName.empty()) + { + printError("Expected function name"); + return false; + } + + _os << funcName << '('; + if (nextToken() == CMakeLexer::TOK_IDENTIFIER) + { + _os << _lexer.getIdentifier(); + while (nextToken() == CMakeLexer::TOK_IDENTIFIER) + { + _os << ", " << _lexer.getIdentifier(); + } + } + + if (curToken() != ')') + { + printError("Missing expected ')'"); + } + else + { + _os << ");"; + } + + // eat the ')' + nextToken(); + + return true; + } + + std::istream& _is; + std::ostream& _os; + CMakeLexer _lexer; + int _curToken; + int _lastToken; +}; + + +#define STRINGIFY(a) #a +#define DOUBLESTRINGIFY(a) STRINGIFY(a) + +int main(int argc, char** argv) +{ + assert(argc > 1); + + for (int i = 1; i < argc; ++i) + { + std::ifstream ifs(argv[i]); + std::ostream& os = std::cout; + + #ifdef USE_NAMESPACE + os << "namespace " << DOUBLESTRINGIFY(USE_NAMESPACE) << " {\n"; + #endif + + CMakeParser parser(ifs, os); + parser.nextToken(); + while (ifs.good()) + { + switch (parser.curToken()) + { + case CMakeLexer::TOK_EOF: + return ifs.get(); // eat EOF + case CMakeLexer::TOK_MACRO: + parser.handleMacro(); + break; + case CMakeLexer::TOK_FUNCTION: + parser.handleFunction(); + break; + case CMakeLexer::TOK_SET: + parser.handleSet(); + break; + case CMakeLexer::TOK_DOXYGEN_COMMENT: + parser.handleDoxygenComment(); + break; + default: + parser.handleTopLevelExpression(); + break; + } + } + + #ifdef USE_NAMESPACE + os << "}\n"; + #endif + } + + return EXIT_SUCCESS; +} diff --git a/documentation/CMakeLists.txt b/documentation/CMakeLists.txt new file mode 100644 index 0000000000..7aec333a00 --- /dev/null +++ b/documentation/CMakeLists.txt @@ -0,0 +1,84 @@ + +if(US_BUILD_TESTING) + include(usFunctionCompileSnippets) + # Compile source code snippets + add_subdirectory(snippets) +endif() + +if(NOT US_IS_EMBEDDED AND NOT US_NO_DOCUMENTATION) + find_package(Doxygen) + + if(DOXYGEN_FOUND) + + option(US_DOCUMENTATION_FOR_WEBPAGE "Build Doxygen documentation for the webpage" OFF) + set(US_DOXYGEN_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR} CACHE PATH "Doxygen output directory") + mark_as_advanced(US_DOCUMENTATION_FOR_WEBPAGE US_DOXYGEN_OUTPUT_DIR) + + set(US_HAVE_DOT "NO") + if(DOXYGEN_DOT_EXECUTABLE) + set(US_HAVE_DOT "YES") + endif() + + if(NOT DEFINED US_DOXYGEN_DOT_NUM_THREADS) + set(US_DOXYGEN_DOT_NUM_THREADS 4) + endif() + + # We are in standalone mode, so we generate a "mainpage" + set(US_DOXYGEN_MAIN_PAGE_CMD "\\mainpage") + set(US_DOXYGEN_ENABLED_SECTIONS "us_standalone") + + if(US_DOCUMENTATION_FOR_WEBPAGE) + configure_file(doxygen/header.html + ${CMAKE_CURRENT_BINARY_DIR}/header.html COPY_ONLY) + set(US_DOXYGEN_HEADER header.html) + + configure_file(doxygen/footer.html + ${CMAKE_CURRENT_BINARY_DIR}/footer.html COPY_ONLY) + set(US_DOXYGEN_FOOTER footer.html) + + configure_file(doxygen/doxygen_extra.css + ${CMAKE_CURRENT_BINARY_DIR}/doxygen_extra.css COPY_ONLY) + set(US_DOXYGEN_EXTRA_CSS doxygen_extra.css) + + set(US_DOXYGEN_OUTPUT_DIR ${PROJECT_SOURCE_DIR}/gh-pages) + if(${PROJECT_NAME}_MINOR_VERSION EQUAL 99) + set(US_DOXYGEN_HTML_OUTPUT "doc_latest") + else() + set(US_DOXYGEN_HTML_OUTPUT "doc_${${PROJECT_NAME}_MAJOR_VERSION}_${${PROJECT_NAME}_MINOR_VERSION}") + endif() + else() + set(US_DOXYGEN_HEADER ) + set(US_DOXYGEN_FOOTER ) + set(US_DOXYGEN_CSS ) + set(US_DOXYGEN_HTML_OUTPUT "html") + endif() + + # Compile a command line tool which transforms comments in CMake scripts into + # Doxygen parseable C code. + set(CMakeDoxygenFilter_EXECUTABLE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CMakeDoxygenFilter${CMAKE_EXECUTABLE_SUFFIX}") + try_compile(_result_var + "${CMAKE_CURRENT_BINARY_DIR}" + "${CMAKE_CURRENT_SOURCE_DIR}/CMakeDoxygenFilter.cpp" + OUTPUT_VARIABLE _compile_output + COPY_FILE ${CMakeDoxygenFilter_EXECUTABLE} + ) + + if(NOT _result_var) + message(FATAL_ERROR "error: Faild to compile ${CMAKE_CURRENT_SOURCE_DIR}/CMakeDoxygenFilter.cpp (result: ${result_var})\n${_compile_output}") + endif() + + configure_file(doxygen.conf.in + ${CMAKE_CURRENT_BINARY_DIR}/doxygen.conf) + + add_custom_target(doc + ${DOXYGEN} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.conf + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + ) + + install(CODE "execute_process(COMMAND \"${CMAKE_COMMAND}\" --build \"${PROJECT_BINARY_DIR}\" --target doc)") + + install(DIRECTORY ${US_DOXYGEN_OUTPUT_DIR}/${US_DOXYGEN_HTML_OUTPUT} + DESTINATION ${AUXILIARY_INSTALL_DIR}/doc/ + COMPONENT doc) + endif() +endif() diff --git a/documentation/doxygen.conf.in b/documentation/doxygen.conf.in new file mode 100644 index 0000000000..275eb52db2 --- /dev/null +++ b/documentation/doxygen.conf.in @@ -0,0 +1,1894 @@ +# Doxyfile 1.8.3.1 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project. +# +# All text after a hash (#) is considered a comment and will be ignored. +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" "). + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# http://www.gnu.org/software/libiconv for the list of possible encodings. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or sequence of words) that should +# identify the project. Note that if you do not use Doxywizard you need +# to put quotes around the project name if it contains spaces. + +PROJECT_NAME = "C++ Micro Services" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = @CppMicroServices_VERSION@ + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer +# a quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = "A dynamic OSGi-like C++ service registry" + +# With the PROJECT_LOGO tag one can specify an logo or icon that is +# included in the documentation. The maximum height of the logo should not +# exceed 55 pixels and the maximum width should not exceed 200 pixels. +# Doxygen will copy the logo to the output directory. + +PROJECT_LOGO = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = @US_DOXYGEN_OUTPUT_DIR@ + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, +# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English +# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, +# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, +# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = NO + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. Note that you specify absolute paths here, but also +# relative paths, which will be relative from the directory where doxygen is +# started. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful if your file system +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like regular Qt-style comments +# (thus requiring an explicit @brief command for a brief description.) + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then Doxygen will +# interpret the first line (until the first dot) of a Qt-style +# comment as the brief description. If set to NO, the comments +# will behave just like regular Qt-style comments (thus requiring +# an explicit \brief command for a brief description.) + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 2 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = "FIXME=\par Fix Me's:\n" \ + "embmainpage{1}=@US_DOXYGEN_MAIN_PAGE_CMD@" + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding +# "class=itcl::class" will allow you to use the command class in the +# itcl::class meaning. + +TCL_SUBST = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for +# Java. For instance, namespaces will be presented as packages, qualified +# scopes will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources only. Doxygen will then generate output that is more tailored for +# Fortran. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for +# VHDL. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, +# and language is one of the parsers supported by doxygen: IDL, Java, +# Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, +# C++. For instance to make doxygen treat .inc files as Fortran files (default +# is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note +# that for custom extensions you also need to set FILE_PATTERNS otherwise the +# files are not read by doxygen. + +EXTENSION_MAPPING = + +# If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all +# comments according to the Markdown format, which allows for more readable +# documentation. See http://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you +# can mix doxygen, HTML, and XML commands with Markdown formatting. +# Disable only in case of backward compatibilities issues. + +MARKDOWN_SUPPORT = YES + +# When enabled doxygen tries to link words that correspond to documented classes, +# or namespaces to their corresponding documentation. Such a link can be +# prevented in individual cases by by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also makes the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = YES + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. +# Doxygen will parse them like normal C++ but will assume all classes use public +# instead of private inheritance when no explicit protection keyword is present. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES (the +# default) will make doxygen replace the get and set methods by a property in +# the documentation. This will only work if the methods are indeed getting or +# setting a simple type. If this is not the case, or you want to show the +# methods anyway, you should set this option to NO. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = YES + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and +# unions are shown inside the group in which they are included (e.g. using +# @ingroup) instead of on a separate page (for HTML and Man pages) or +# section (for LaTeX and RTF). + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and +# unions with only public data fields will be shown inline in the documentation +# of the scope in which they are defined (i.e. file, namespace, or group +# documentation), provided this scope is documented. If set to NO (the default), +# structs, classes, and unions are shown on a separate page (for HTML and Man +# pages) or section (for LaTeX and RTF). + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum +# is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically +# be useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. + +TYPEDEF_HIDES_STRUCT = NO + +# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to +# determine which symbols to keep in memory and which to flush to disk. +# When the cache is full, less often used symbols will be written to disk. +# For small to medium size projects (<1000 input files) the default value is +# probably good enough. For larger projects a too small cache size can cause +# doxygen to be busy swapping symbols to and from disk most of the time +# causing a significant performance penalty. +# If the system has enough physical memory increasing the cache will improve the +# performance by keeping more symbols in memory. Note that the value works on +# a logarithmic scale so increasing the size by one will roughly double the +# memory usage. The cache size is given by this formula: +# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols. + +SYMBOL_CACHE_SIZE = 0 + +# Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be +# set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given +# their name and scope. Since this can be an expensive process and often the +# same symbol appear multiple times in the code, doxygen keeps a cache of +# pre-resolved symbols. If the cache is too small doxygen will become slower. +# If the cache is too large, memory is wasted. The cache size is given by this +# formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols. + +LOOKUP_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = YES + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal +# scope will be included in the documentation. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = YES + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = NO + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base +# name of the file that contains the anonymous namespace. By default +# anonymous namespaces are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = YES + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen +# will list include files with double quotes in the documentation +# rather than with sharp brackets. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen +# will sort the (brief and detailed) documentation of class members so that +# constructors and destructors are listed first. If set to NO (the default) +# the constructors will appear in the respective orders defined by +# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. +# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO +# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the +# hierarchy of group names into alphabetical order. If set to NO (the default) +# the group names will appear in their defined order. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = YES + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to +# do proper type resolution of all parameters of a function it will reject a +# match between the prototype and the implementation of a member function even +# if there is only one candidate or it is obvious which candidate to choose +# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen +# will still accept a match between prototype and implementation in such cases. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if section-label ... \endif +# and \cond section-label ... \endcond blocks. + +ENABLED_SECTIONS = @US_DOXYGEN_ENABLED_SECTIONS@ + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or macro consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and macros in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 0 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = NO + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. +# This will remove the Files entry from the Quick Index and from the +# Folder Tree View (if specified). The default is YES. + +SHOW_FILES = NO + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the +# Namespaces page. +# This will remove the Namespaces entry from the Quick Index +# and from the Folder Tree View (if specified). The default is YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. +# You can optionally specify a file name after the option, if omitted +# DoxygenLayout.xml will be used as the name of the layout file. + +LAYOUT_FILE = + +# The CITE_BIB_FILES tag can be used to specify one or more bib files +# containing the references data. This must be a list of .bib files. The +# .bib extension is automatically appended if omitted. Using this command +# requires the bibtex tool to be installed. See also +# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style +# of the bibliography can be controlled using LATEX_BIB_STYLE. To use this +# feature you need bibtex and perl available in the search path. Do not use +# file names with spaces, bibtex cannot handle them. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# The WARN_NO_PARAMDOC option can be enabled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = YES + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = @PROJECT_SOURCE_DIR@ \ + @PROJECT_SOURCE_DIR@/CMake/usFunctionEmbedResources.cmake \ + @PROJECT_SOURCE_DIR@/CMake/usFunctionGenerateModuleInit.cmake \ + @PROJECT_SOURCE_DIR@/CMake/usFunctionGenerateExecutableInit.cmake \ + @PROJECT_BINARY_DIR@/include/usConfig.h + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is +# also the default input encoding. Doxygen uses libiconv (or the iconv built +# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for +# the list of possible encodings. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh +# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py +# *.f90 *.f *.for *.vhd *.vhdl + +FILE_PATTERNS = *.h \ + *.dox \ + *.md + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = YES + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = @PROJECT_SOURCE_DIR@/README.md \ + @PROJECT_SOURCE_DIR@/documentation/snippets/ \ + @PROJECT_SOURCE_DIR@/examples/ \ + @PROJECT_SOURCE_DIR@/test/ \ + @PROJECT_SOURCE_DIR@/gh-pages/ \ + @PROJECT_SOURCE_DIR@/.git/ + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = */.git/* \ + *_p.h \ + *Private.* + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test + +EXCLUDE_SYMBOLS = us \ + US_NAMESPACE \ + *Private* \ + ModuleInfo \ + ServiceObjectsBase* \ + TrackedService* + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = @PROJECT_SOURCE_DIR@/documentation/snippets/ \ + @PROJECT_SOURCE_DIR@/examples/ + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = YES + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. +# If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. +# Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. +# The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty or if +# non of the patterns match the file name, INPUT_FILTER is applied. + +FILTER_PATTERNS = *.cmake=@CMakeDoxygenFilter_EXECUTABLE@ + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) +# and it is also possible to disable source filtering for a specific pattern +# using *.ext= (so without naming a filter). This option only has effect when +# FILTER_SOURCE_FILES is enabled. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MD_FILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page (index.html). +# This can be useful if you have a project on for instance GitHub and want reuse +# the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C, C++ and Fortran comments will always remain visible. + +STRIP_CODE_COMMENTS = NO + +# If the REFERENCED_BY_RELATION tag is set to YES +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = YES + +# If the REFERENCES_RELATION tag is set to YES +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = YES + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. +# Otherwise they will link to the documentation. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = YES + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 3 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = @US_DOXYGEN_HTML_OUTPUT@ + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. Note that when using a custom header you are responsible +# for the proper inclusion of any scripts and style sheets that doxygen +# needs, which is dependent on the configuration options used. +# It is advised to generate a default header using "doxygen -w html +# header.html footer.html stylesheet.css YourConfigFile" and then modify +# that header. Note that the header is subject to change so you typically +# have to redo this when upgrading to a newer version of doxygen or when +# changing the value of configuration settings such as GENERATE_TREEVIEW! + +HTML_HEADER = @US_DOXYGEN_HEADER@ + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = @US_DOXYGEN_FOOTER@ + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If left blank doxygen will +# generate a default style sheet. Note that it is recommended to use +# HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this +# tag will in the future become obsolete. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional +# user-defined cascading style sheet that is included after the standard +# style sheets created by doxygen. Using this option one can overrule +# certain style aspects. This is preferred over using HTML_STYLESHEET +# since it does not replace the standard style sheet and is therefor more +# robust against future updates. Doxygen will copy the style sheet file to +# the output directory. + +HTML_EXTRA_STYLESHEET = @US_DOXYGEN_EXTRA_CSS@ + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that +# the files will be copied as-is; there are no commands or markers available. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. +# Doxygen will adjust the colors in the style sheet and background images +# according to this color. Hue is specified as an angle on a colorwheel, +# see http://en.wikipedia.org/wiki/Hue for more information. +# For instance the value 0 represents red, 60 is yellow, 120 is green, +# 180 is cyan, 240 is blue, 300 purple, and 360 is red again. +# The allowed range is 0 to 359. + +HTML_COLORSTYLE_HUE = 220 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of +# the colors in the HTML output. For a value of 0 the output will use +# grayscales only. A value of 255 will produce the most vivid colors. + +HTML_COLORSTYLE_SAT = 100 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to +# the luminance component of the colors in the HTML output. Values below +# 100 gradually make the output lighter, whereas values above 100 make +# the output darker. The value divided by 100 is the actual gamma applied, +# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, +# and 100 does not change the gamma. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting +# this to NO can help when comparing the output of multiple runs. + +HTML_TIMESTAMP = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. + +HTML_DYNAMIC_SECTIONS = NO + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of +# entries shown in the various tree structured indices initially; the user +# can expand and collapse entries dynamically later on. Doxygen will expand +# the tree to such a level that at most the specified number of entries are +# visible (unless a fully collapsed tree already exceeds this amount). +# So setting the number of entries 1 will produce a full collapsed tree by +# default. 0 is a special value representing an infinite number of entries +# and will result in a full expanded tree by default. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files +# will be generated that can be used as input for Apple's Xcode 3 +# integrated development environment, introduced with OSX 10.5 (Leopard). +# To create a documentation set, doxygen will generate a Makefile in the +# HTML output directory. Running make will produce the docset in that +# directory and running "make install" will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find +# it at startup. +# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html +# for more information. + +GENERATE_DOCSET = NO + +# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the +# feed. A documentation feed provides an umbrella under which multiple +# documentation sets from a single provider (such as a company or product suite) +# can be grouped. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that +# should uniquely identify the documentation set bundle. This should be a +# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen +# will append .docset to the name. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely +# identify the documentation publisher. This should be a reverse domain-name +# style string, e.g. com.mycompany.MyDocSet.documentation. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING +# is used to encode HtmlHelp index (hhk), content (hhc) and project file +# content. + +CHM_INDEX_ENCODING = + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated +# that can be used as input for Qt's qhelpgenerator to generate a +# Qt Compressed Help (.qch) of the generated HTML documentation. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can +# be used to specify the file name of the resulting .qch file. +# The path specified is relative to the HTML output folder. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#namespace + +QHP_NAMESPACE = + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#virtual-folders + +QHP_VIRTUAL_FOLDER = + +# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to +# add. For more information please see +# http://doc.trolltech.com/qthelpproject.html#custom-filters + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see +# +# Qt Help Project / Custom Filters. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's +# filter section matches. +# +# Qt Help Project / Filter Attributes. + +QHP_SECT_FILTER_ATTRS = + +# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can +# be used to specify the location of Qt's qhelpgenerator. +# If non-empty doxygen will try to run qhelpgenerator on the generated +# .qhp file. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files +# will be generated, which together with the HTML files, form an Eclipse help +# plugin. To install this plugin and make it available under the help contents +# menu in Eclipse, the contents of the directory containing the HTML and XML +# files needs to be copied into the plugins directory of eclipse. The name of +# the directory within the plugins directory should be the same as +# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before +# the help appears. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have +# this name. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) +# at top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. Since the tabs have the same information as the +# navigation tree you can set this option to NO if you already set +# GENERATE_TREEVIEW to YES. + +DISABLE_INDEX = NO + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. +# If the tag value is set to YES, a side panel will be generated +# containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). +# Windows users are probably better off using the HTML help feature. +# Since the tree basically has the same information as the tab index you +# could consider to set DISABLE_INDEX to NO when enabling this option. + +GENERATE_TREEVIEW = NO + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values +# (range [0,1..20]) that doxygen will group on one line in the generated HTML +# documentation. Note that a value of 0 will completely suppress the enum +# values from appearing in the overview section. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 300 + +# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open +# links to external symbols imported via tag files in a separate window. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of Latex formulas included +# as images in the HTML documentation. The default is 10. Note that +# when you change the font size after a successful doxygen run you need +# to manually remove any form_*.png images from the HTML output directory +# to force them to be regenerated. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are +# not supported properly for IE 6.0, but are supported on all modern browsers. +# Note that when changing this option you need to delete any form_*.png files +# in the HTML output before the changes have effect. + +FORMULA_TRANSPARENT = YES + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax +# (see http://www.mathjax.org) which uses client side Javascript for the +# rendering instead of using prerendered bitmaps. Use this if you do not +# have LaTeX installed or if you want to formulas look prettier in the HTML +# output. When enabled you may also need to install MathJax separately and +# configure the path to it using the MATHJAX_RELPATH option. + +USE_MATHJAX = NO + +# When MathJax is enabled you can set the default output format to be used for +# thA MathJax output. Supported types are HTML-CSS, NativeMML (i.e. MathML) and +# SVG. The default value is HTML-CSS, which is slower, but has the best +# compatibility. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the +# HTML output directory using the MATHJAX_RELPATH option. The destination +# directory should contain the MathJax.js script. For instance, if the mathjax +# directory is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to +# the MathJax Content Delivery Network so you can quickly see the result without +# installing MathJax. +# However, it is strongly recommended to install a local +# copy of MathJax from http://www.mathjax.org before deployment. + +MATHJAX_RELPATH = http://www.mathjax.org/mathjax + +# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension +# names that should be enabled during MathJax rendering. + +MATHJAX_EXTENSIONS = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box +# for the HTML output. The underlying search engine uses javascript +# and DHTML and should work on any modern browser. Note that when using +# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets +# (GENERATE_DOCSET) there is already a search function so this one should +# typically be disabled. For large projects the javascript based search engine +# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. + +SEARCHENGINE = YES + +# When the SERVER_BASED_SEARCH tag is enabled the search engine will be +# implemented using a web server instead of a web client using Javascript. +# There are two flavours of web server based search depending on the +# EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for +# searching and an index file used by the script. When EXTERNAL_SEARCH is +# enabled the indexing and searching needs to be provided by external tools. +# See the manual for details. + +SERVER_BASED_SEARCH = NO + +# When EXTERNAL_SEARCH is enabled doxygen will no longer generate the PHP +# script for searching. Instead the search results are written to an XML file +# which needs to be processed by an external indexer. Doxygen will invoke an +# external search engine pointed to by the SEARCHENGINE_URL option to obtain +# the search results. Doxygen ships with an example indexer (doxyindexer) and +# search engine (doxysearch.cgi) which are based on the open source search engine +# library Xapian. See the manual for configuration details. + +EXTERNAL_SEARCH = NO + +# The SEARCHENGINE_URL should point to a search engine hosted by a web server +# which will returned the search results when EXTERNAL_SEARCH is enabled. +# Doxygen ships with an example search engine (doxysearch) which is based on +# the open source search engine library Xapian. See the manual for configuration +# details. + +SEARCHENGINE_URL = + +# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed +# search data is written to a file for indexing by an external tool. With the +# SEARCHDATA_FILE tag the name of this file can be specified. + +SEARCHDATA_FILE = searchdata.xml + +# When SERVER_BASED_SEARCH AND EXTERNAL_SEARCH are both enabled the +# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is +# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple +# projects and redirect the results back to the right project. + +EXTERNAL_SEARCH_ID = + +# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen +# projects other than the one defined by this configuration file, but that are +# all added to the same external search index. Each project needs to have a +# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id +# of to a relative location where the documentation can be found. +# The format is: EXTRA_SEARCH_MAPPINGS = id1=loc1 id2=loc2 ... + +EXTRA_SEARCH_MAPPINGS = + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = NO + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. +# Note that when enabling USE_PDFLATEX this option is only used for +# generating bitmaps for formulas in the HTML output, but not in the +# Makefile that is written to the output directory. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = amssymb + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for +# the generated latex document. The footer should contain everything after +# the last chapter. If it is left blank doxygen will generate a +# standard footer. Notice: only use this tag if you know what you are doing! + +LATEX_FOOTER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = NO + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = NO + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +# If LATEX_SOURCE_CODE is set to YES then doxygen will include +# source code with syntax highlighting in the LaTeX output. +# Note that which sources are shown also depends on other settings +# such as SOURCE_BROWSER. + +LATEX_SOURCE_CODE = NO + +# The LATEX_BIB_STYLE tag can be used to specify the style to use for the +# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See +# http://en.wikipedia.org/wiki/BibTeX for more info. + +LATEX_BIB_STYLE = plain + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load style sheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. +# This is useful +# if you want to understand what is going on. +# On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = YES + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = YES + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# pointed to by INCLUDE_PATH will be searched when a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = @PROJECT_BINARY_DIR@/include/ + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = *.h + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = US_PREPEND_NAMESPACE(x)=x \ + US_BEGIN_NAMESPACE= \ + US_END_NAMESPACE= \ + US_EXPORT= \ + US_ABI_LOCAL= \ + US_MSVC_POP_WARNING= + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition that +# overrules the definition found in the source code. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all references to function-like macros +# that are alone on a line, have an all uppercase name, and do not end with a +# semicolon, because these will confuse the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. For each +# tag file the location of the external documentation should be added. The +# format of a tag file without this location is as follows: +# +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths +# or URLs. Note that each tag file must have a unique name (where the name does +# NOT include the path). If a tag file is not located in the directory in which +# doxygen is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = NO + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option also works with HAVE_DOT disabled, but it is recommended to +# install and use dot, since it yields more powerful graphs. + +CLASS_DIAGRAMS = YES + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see +# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = @US_HAVE_DOT@ + +# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is +# allowed to run in parallel. When set to 0 (the default) doxygen will +# base this on the number of processors available in the system. You can set it +# explicitly to a value larger than 0 to get control over the balance +# between CPU load and processing speed. + +DOT_NUM_THREADS = @US_DOXYGEN_DOT_NUM_THREADS@ + +# By default doxygen will use the Helvetica font for all dot files that +# doxygen generates. When you want a differently looking font you can specify +# the font name using DOT_FONTNAME. You need to make sure dot is able to find +# the font, which can be done by putting it in a standard location or by setting +# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the +# directory containing the font. + +DOT_FONTNAME = FreeSans.ttf + +# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. +# The default size is 10pt. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the Helvetica font. +# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to +# set the path where dot can find it. + +DOT_FONTPATH = + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If the UML_LOOK tag is enabled, the fields and methods are shown inside +# the class node. If there are many fields or methods and many nodes the +# graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS +# threshold limits the number of items for each type to make the size more +# managable. Set this to 0 for no limit. Note that the threshold may be +# exceeded by 50% before the limit is enforced. + +UML_LIMIT_NUM_FIELDS = 10 + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = NO + +# If the CALL_GRAPH and HAVE_DOT options are set to YES then +# doxygen will generate a call dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable call graphs +# for selected functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then +# doxygen will generate a caller dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable caller +# graphs for selected functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will generate a graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = NO + +# If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = NO + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are svg, png, jpg, or gif. +# If left blank png will be used. If you choose svg you need to set +# HTML_FILE_EXTENSION to xhtml in order to make the SVG files +# visible in IE 9+ (other browsers do not have this requirement). + +DOT_IMAGE_FORMAT = png + +# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to +# enable generation of interactive SVG images that allow zooming and panning. +# Note that this requires a modern browser other than Internet Explorer. +# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you +# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files +# visible. Older versions of IE do not have SVG support. + +INTERACTIVE_SVG = NO + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = @US_DOXYGEN_DOT_PATH@ + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The MSCFILE_DIRS tag can be used to specify one or more directories that +# contain msc files that are included in the documentation (see the +# \mscfile command). + +MSCFILE_DIRS = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of +# nodes that will be shown in the graph. If the number of nodes in a graph +# becomes larger than this value, doxygen will truncate the graph, which is +# visualized by representing a node as a red box. Note that doxygen if the +# number of direct children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note +# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not +# seem to support this out of the box. Warning: Depending on the platform used, +# enabling this option may lead to badly anti-aliased labels on the edges of +# a graph (i.e. they become hard to read). + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES diff --git a/documentation/doxygen/MicroServices.dox b/documentation/doxygen/MicroServices.dox new file mode 100644 index 0000000000..86032cd9d6 --- /dev/null +++ b/documentation/doxygen/MicroServices.dox @@ -0,0 +1,126 @@ + +/** + +\defgroup MicroServices Micro Services Classes + +\brief This category includes classes related to the C++ Micro Services component. + +The C++ Micro Services component provides a dynamic service registry based on the service layer +as specified in the OSGi R4.2 specifications. + +*/ + +/** + +\defgroup MicroServicesUtils Utility Classes + +\brief This category includes utility classes which can be used by others. + +*/ + +/** + +\defgroup MicroServicesCMake CMake Functions + +\brief This category includes CMake utility functions for external projects. + +External projects can include the CMake scripts provided by the CppMicroServices +library to automatically generate module initialization code and to embed external resources +into a modules shared library. + +*/ + +/** + +\page MicroServices_Tutorials Tutorial + +This tutorial creates successively more complex modules to illustrate +most of the features and functionality offered by the C++ Micro Services library. +It is heavily base on the Apache Felix OSGi Tutorial. + +- \subpage MicroServices_Example1 +- \subpage MicroServices_Example2 +- \subpage MicroServices_Example2b +- \subpage MicroServices_Example3 +- \subpage MicroServices_Example4 +- \subpage MicroServices_Example5 +- \subpage MicroServices_Example6 +- \subpage MicroServices_Example7 + +*/ + +/** + +\page MicroServices_UserDocs User Documentation + +This is a list of available documentation for different aspects of the C++ +Micro Services library: + +\if us_standalone +- \subpage BuildInstructions +- \subpage MicroServices_GettingStarted +\endif +- \subpage MicroServices_TheModuleContext +- \subpage MicroServices_Resources +- \subpage MicroServices_ModuleProperties +- \subpage MicroServices_AutoLoading +- \subpage MicroServices_StaticModules +- \subpage MicroServices_EmulateSingleton + +*/ + +/** + +\embmainpage{MicroServices_Overview} The C++ Micro Services + +The C++ Micro Services library provides a dynamic service registry based on the service layer +as specified in the OSGi R4.2 specifications. It enables users to realize a service oriented +approach within their software stack. The advantages include higher reuse of components, looser +coupling, better organization of responsibilities, cleaner API contracts, etc. + +\if us_standalone +\section MicroServices_Overview_BI Build Instructions + +How to build the C++ Micro Services library is explained in detail on the \ref BuildInstructions page. +\endif + +

Tutorial

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

User Documentation

+ +The links in the following list point to important +\if us_standalone +\ref MicroServices_UserDocs "user documentation": +\else +\subpage MicroServices_UserDocs "user documentation": +\endif + +\if us_standalone +- \ref BuildInstructions +- \ref MicroServices_GettingStarted +\endif +- \ref MicroServices_TheModuleContext +- \ref MicroServices_Resources +- \ref MicroServices_ModuleProperties +- \ref MicroServices_AutoLoading +- \ref MicroServices_StaticModules +- \ref MicroServices_EmulateSingleton + +*/ diff --git a/documentation/doxygen/MicroServices_AutoLoading.md b/documentation/doxygen/MicroServices_AutoLoading.md new file mode 100644 index 0000000000..66a39cbb95 --- /dev/null +++ b/documentation/doxygen/MicroServices_AutoLoading.md @@ -0,0 +1,86 @@ +Auto Loading Modules {#MicroServices_AutoLoading} +==================== + +Auto-loading of modules is a feature of the CppMicroServices library to manage the loading +of modules which would normally not be loaded at runtime because of missing link-time +dependencies. + +The Problem +----------- + +Imagine that you have a module *A* which provides an interface for loading files and another +module *B* which registers a service implementing that interface for files of type *png*. +Your executable *E* uses the interface from *A* to query the service registry for available +services. Due to the link-time dependencies, this results in the following dependency graph: + +\dot +digraph linker_deps { + node [shape=record, fontname=Helvetica, fontsize=10]; + a [ label="Module A\n(Interfaces)" ]; + b [ label="Module B\n(service provider)" ]; + e [ label="Executable E\n(service consumer)" ]; + a -> e; + a -> b; +} +\enddot + +When the executable *E* is launched, the dynamic linker of your operating system loads +module *A* to satisfy the dependencies of *E*, but module *B* will not be loaded. Therefore, +the executable will not be able to consume any services from module *B*. + +The Solution +------------ + +The problem above is solved in the CppMicroServices library by automatically loading modules +from a list of configurable file-system locations. + +For each module being loaded, the following steps are taken: + + - If the module provides an activator, it's ModuleActivator::Load() method is called. + - If auto-loading is enabled, and the module declared a non-empty auto-load directory, the + auto-load paths returned from ModuleSettings::GetAutoLoadPaths() are processed. + - For each auto-load path, all modules in that path with the currently loaded module's + auto-load directory appended are explicitly loaded. + +See the ModuleSettings class for details about auto-load paths. The auto-load directory of +a module defaults to the module's library name, but can be customized using a `manifest.json` +file (see \ref MicroServices_ModuleProperties). For executables, the auto-load directory +defaults to the special value `main`. This allows third-party modules to be auto-loaded +during application start-up, without having to reference a special auto-load directory. + +If module *A* in the example above contains initialization code like + +\code +US_INITIALIZE_MODULE("Module A", "A") +\endcode + +and the module's library is located at + + /myproject/libA.so + +all libraries located at + + /myproject/A/ + +will be automatically loaded (unless the auto-load paths have been modified). By ensuring that +module *B* from the example above is located at + + /myproject/A/libB.so + +it will be loaded when the executable *E* is started and is then able to register its services +before the executable queries the service registry. + +\note If you need to add additional auto-load search paths during application start-up, provide +a ModuleActivator instance in your executable and call ModuleSettings::AddAutoLoadPath() in +your executable's ModuleActivator::Load() method. If there are modules inside a `main` sub-directory +of any of the provided auto-load search paths, these modules will then be auto-loaded before +your executable's main() function is executed. + +Environment Variables +--------------------- + +The following environment variables influence the runtime behavior of the CppMicroServices library: + + - *US_DISABLE_AUTOLOADING* If set, auto-loading of modules is disabled. + - *US_AUTOLOAD_PATHS* A `:` (Unix) or `;` (Windows) separated list of paths from which modules + should be auto-loaded. diff --git a/documentation/doxygen/MicroServices_Debugging.dox b/documentation/doxygen/MicroServices_Debugging.dox new file mode 100644 index 0000000000..4e3c735c8f --- /dev/null +++ b/documentation/doxygen/MicroServices_Debugging.dox @@ -0,0 +1,70 @@ + +/** + * \ingroup MicroServicesUtils + * + * \enum MsgType + * This enum describes the messages that can be sent to a message handler (MsgHandler). + * You can use the enum to identify and associate the various message types with the + * appropriate actions. + */ + +/** + * \ingroup MicroServicesUtils + * + * \var MsgType DebugMsg + * A debug message. + */ + +/** + * \ingroup MicroServicesUtils + * + * \var MsgType InfoMsg + * An informational message. + */ + +/** + * \ingroup MicroServicesUtils + * + * \var MsgType WarningMsg + * A warning message. + */ + +/** + * \ingroup MicroServicesUtils + * + * \var MsgType ErrorMsg + * An error message. + */ + +/** + * \ingroup MicroServicesUtils + * + * \typedef MsgHandler + * A message handler callback function. + */ + +/** + * \ingroup MicroServicesUtils + * + * \fn MsgHandler installMsgHandler(MsgHandler) + * \brief Installs a message handler which has been defined previously. + * + * Returns a pointer to the previous message handler (which may be 0). + * + * The message handler is a function that prints out debug messages, warnings, + * and fatal error messages. The C++ Micro Services library (debug mode) contains + * warning messages that are printed when internal errors (usually invalid function + * arguments) occur. The library built in release mode also contains such warnings + * unless US_NO_WARNING_OUTPUT has been set during compilation. In both debug and release mode + * debugging message are suppressed by default, unless US_ENABLE_DEBUGGING_OUTPUT + * has been set during compilation. If you implement your own message handler, + * you get total control of these messages. + * + * The default message handler prints the message to the standard output. If it is + * an error message, the application aborts immediately. + * + * Only one message handler can be defined, since this is usually done on an + * application-wide basis to control debug output. + * + * To restore the message handler, call installMsgHandler(0). + */ diff --git a/documentation/doxygen/MicroServices_EmulateSingleton.dox b/documentation/doxygen/MicroServices_EmulateSingleton.dox new file mode 100644 index 0000000000..55e51753e9 --- /dev/null +++ b/documentation/doxygen/MicroServices_EmulateSingleton.dox @@ -0,0 +1,89 @@ +/** + +\page MicroServices_EmulateSingleton Emulating singletons with micro services + +\section MicroServices_EmulateSingleton_1 Meyers Singleton + +Singletons are a well known pattern to ensure that only one instance of a class exists +during the whole life-time of the application. A self-deleting variant is the "Meyers Singleton": + +\snippet uServices-singleton/SingletonOne.h s1 + +where the GetInstance() method is implemented as + +\snippet uServices-singleton/SingletonOne.cpp s1 + +If such a singleton is accessed during static deinitialization (which happens during unloading +of shared libraries or application termination), your program might crash or even worse, exhibit undefined +behavior, depending on your compiler and/or weekday. Such an access might happen in destructors of +other objects with static life-time. + +For example, suppose that SingletonOne needs to call a second Meyers singleton during destruction: + +\snippet uServices-singleton/SingletonOne.cpp s1d + +If SingletonTwo was destroyed before SingletonOne, this leads to the mentioned problems. Note that +this problem only occurs for static objects defined in the same shared library. + +Since you cannot reliably control the destruction order of global static objects, you must not +introduce dependencies between them during static deinitialization. This is one reason why one +should consider an alternative approach to singletons (unless you can absolutely make sure that nothing in +your shared library will introduce such dependencies. Never.) + +Of course you could use something like a "Phoenix singleton" but that will have other drawbacks in certain +scenarios. Returning pointers instead of references in GetInstance() would open up the possibility to +return NULL, but than again this would not help if you require a non-NULL instance in your destructor. + +Another reason for an alternative approach is that singletons are usually not meant to be singletons for eternity. +If your design evolves, you might hit a point where you suddenly need multiple instances of your singleton. + +\section MicroServices_EmulateSingleton_2 Singletons as a service + +The C++ Micro Services can be used to emulate the singleton pattern using a non-singleton class. This +leaves room for future extensions without the need for heavy refactoring. Additionally, it gives you +full control about the construction and destruction order of your "singletons" inside your shared library +or executable, making it possible to have dependencies between them during destruction. + +\subsection MicroServices_EmulateSingleton_2_1 Converting a classic singleton + +We modify the previous SingletonOne class such that it internally uses the micro services API. The changes +are discussed in detail below. + +\snippet uServices-singleton/SingletonOne.h ss1 + + - In the implementation above, the class SingletonOneService provides the implementation as well as the interface. + - Friend activator: We move the responsibility of constructing instances of SingletonOneService from the GetInstance() + method to the module activator. + - Service interface declaration: Because the SingletonOneService class introduces a new service interface, it must + be registered under a unique name using the helper macro US_DECLARE_SERVICE_INTERFACE. + +Let's have a look at the modified GetInstance() and ~SingletonOneService() methods. + +\snippet uServices-singleton/SingletonOne.cpp ss1gi + +The inline comments should explain the details. Note that we now had to change the return type to a pointer, instead +of a reference as in the classic singleton. This is necessary since we can no longer guarantee that an instance +always exists. Clients of the GetInstance() method must check for null pointers and react appropriately. + +\warning Newly created "singletons" should not expose a GetInstance() method. They should be handled as proper +services and hence should be retrieved by clients using the ModuleContext or ServiceTracker API. The +GetInstance() method is for migration purposes only. + +\snippet uServices-singleton/SingletonOne.cpp ss1d + +The SingletonTwoService::GetInstance() method is implemented exactly as in SingletonOneService. Because we know +that the module activator guarantees that a SingletonTwoService instance will always be available during the +life-time of a SingletonOneService instance (see below), we can assert a non-null pointer. Otherwise, we would +have to handle the null-pointer case. + +The order of construction/registration and destruction/unregistration of our singletons (or any other services) is +defined in the Load() and Unload() methods of the module activator. + +\snippet uServices-singleton/main.cpp 0 + +The Unload() method is defined as: + +\snippet uServices-singleton/main.cpp 1 + + +*/ diff --git a/documentation/doxygen/MicroServices_ModuleProperties.md b/documentation/doxygen/MicroServices_ModuleProperties.md new file mode 100644 index 0000000000..29464ae39b --- /dev/null +++ b/documentation/doxygen/MicroServices_ModuleProperties.md @@ -0,0 +1,51 @@ +Module Properties {#MicroServices_ModuleProperties} +================= + +A C++ Micro Services Module provides meta-data in the form of so-called *properties* about itself. +Properties are key - value pairs where the key is of type `std::string` and the value of type `Any`. +The following properties are always set by the C++ Micro Services library and cannot be altered by +the module author: + + * `module.id` - The unique id of the module (type `long`) + * `module.name` - The human readable name of the module (type `std::string`) + * `module.location` - The full path to the module's shared library on the file system (type `std::string`) + +Module authors can add custom properties by providing a `manifest.json` file, embedded as a top-level +resource into the module (see \ref MicroServices_Resources). The root value of the Json file must be +a Json object. An example `manifest.json` file would be: + +~~~{.json} +{ + "module.version" : "1.0.2", + "module.description" : "This module provides an awesome service", + "authors" : [ "John Doe", "Douglas Reynolds", "Daniel Cannady" ], + "rating" : 5 +} +~~~ + +All Json member names of the root object will be available as property keys in the module containing +the `manifest.json` file. The C++ Micro Services library specifies the following standard keys for +re-use in `manifest.json` files: + + * `module.version` - The version of the module (type `std::string`). The version string must be a + valid version identifier, as specified in the ModuleVersion class. + * `module.vendor` - The vendor name of the module (type `std::string`) + * `module.description` - A description for the module (type `std::string`) + * `module.autoload_dir` - A custom auto-load directory for the module (type `std::string`). If not + set, this property defaults to the module's library name. + +\note Some of the properties mentioned above may also be accessed via dedicated methods in the Module class, +e.g. Module::GetName() or Module::GetVersion(). + +When parsing the `manifest.json` file, the Json types are mapped to C++ types and stored in instances of +the Any class. The mapping is as follows: + +| Json | C++ (%Any) | +|-------|-----------| +|object | std::map | +|array | std::vector | +|string | std::string | +|number | int or double | +|true | bool | +|false | bool | +|null | %Any() | diff --git a/documentation/doxygen/MicroServices_Resources.md b/documentation/doxygen/MicroServices_Resources.md new file mode 100644 index 0000000000..101044d143 --- /dev/null +++ b/documentation/doxygen/MicroServices_Resources.md @@ -0,0 +1,56 @@ +The Resources System {#MicroServices_Resources} +==================== + +The C++ Micro Services library provides a generic resources system to embed arbitrary files into a +module's shared library (the current size limitation is based on the largest source code file size +your compiler can handle). + +The following features are supported: + + * Embed arbitrary data into shared or static modules or executables. + * Data is embedded in a compressed format if the size reduction exceeds a + configurable threshold. + * Resources are accessed via a Module instance, providing individual resource lookup and access + for each module. + * Resources are managed in a tree hierarchy, modeling the original child - parent relationship + on the file-system. + * The ModuleResource class provides a high-level API for accessing resource information and + traversing the resource tree. + * The ModuleResourceStream class provides an STL input stream derived class for the seamless usage + of embedded resource data in third-party libraries. + + +Embedding Resources in a %Module +-------------------------------- + +Resources are embedded by compiling a source file generated by the `usResourceCompiler` executable +into a module's shared or static library (or into an executable). + +If you are using CMake, consider using the provided `#usFunctionEmbedResources` CMake macro which +handles the invocation of the `usResourceCompiler` executable and sets up the correct file +dependencies. + +Accessing Resources at Runtime +------------------------------ + +Each module provides access to its embedded resources via the Module class which provides methods +returning ModuleResource objects. The ModuleResourceStream class provides a std::istream compatible +object to access the resource contents. + +The following example shows how to retrieve a resource from each currently loaded module whose path +is specified by a module property: + +\snippet uServices-resources/main.cpp 2 + +This example could be enhanced to dynamically react to modules being loaded and unloaded, making use +of the popular "extender pattern" from OSGi. + +Limitations +----------- + +Currently, the system has the following limitations: + + * At most one file generated by the `usResourceCompiler` executable can be compiled into a module's + shared library (you can work around this limitation by creating static modules and importing them). + * The size of embedded resources is limited by the file size your compiler can handle. However, the file + size is the sum of the size of all resources embedded into a module plus a small overhead. diff --git a/documentation/doxygen/MicroServices_StaticModules.md b/documentation/doxygen/MicroServices_StaticModules.md new file mode 100644 index 0000000000..344cfb5146 --- /dev/null +++ b/documentation/doxygen/MicroServices_StaticModules.md @@ -0,0 +1,90 @@ +Static Modules {#MicroServices_StaticModules} +============== + +The normal and most flexible way to include a CppMicroServices module in an application is to compile +it into a shared library that is either linked by another library (or executable) or +\ref MicroServices_AutoLoading "auto-loaded" during runtime. + +However, modules can be linked statically to your application or shared library. This makes the deployment +of your application less error-prone and in the case of a complete static build also minimizes its binary +size and start-up time. The disadvantage is that no functionality can be added without a rebuild and +redistribution of the application. + +# Creating Static Modules + +Static modules are written just like shared modules - there are no differences in the usage of the +CppMicroServices API or the provided preprocessor macros. The only thing you need to make sure is that +the `US_STATIC_MODULE` preprocessor macro is defined when building a module statically. + +# Using Static Modules + +Static modules can be used (imported) in shared or other static libraries or in the executable itself. +Assuming that a static module makes use of the CppMicroServices API (e.g. by registering some services +using a ModuleContext), the importing library or executable needs to put a call to the `#US_INITIALIZE_MODULE` +or the `#US_INITIALIZE_EXECUTABLE` macro somewhere in its source code. This ensures the availability of +a module context which is shared with all imported static libraries (see also \ref MicroServices_StaticModules_Context). + +\note Note that if your static module does not export a module activator by using the macro +`#US_EXPORT_MODULE_ACTIVATOR` or does not contain embedded resources (see \ref MicroServices_Resources) you +do not need to put the special import macros explained below into +your code. You can use and link the static module just like any other static library. + +For every static module you would like to import, you need to put a call to `#US_IMPORT_MODULE` into the +source code of the importing library. To make the static module's resources available to the importing module, +you must also call `#US_IMPORT_MODULE_RESOURCES`. Addidtionally, you need a call to `#US_LOAD_IMPORTED_MODULES` +which contains a space-deliminated list of module names in the importing libaries source code. This ensures +that the module activators of the imported static modules (if they exist) are called appropriately and that +the embedded resources are registered with the importing module. + +\note When importing a static module into another static module, the call to `#US_LOAD_IMPORTED_MODULES` in +the importing static module will have no effect. This macro can only be used in shared modules or executables. + +There are two main usage scenarios which are explained below together with some example code. + +## Using a Shared CppMicroServices Library + +Building the CppMicroServices library as a shared library allows you to import static modules into other +shared or static modules or into the executable. As noted above, the importing shared module or executable +needs to provide a module context by calling the `#US_INITIALIZE_MODULE` or `#US_INITIALIZE_EXECUTABLE` macro. +Additionally, you must ensure to use the `#US_LOAD_IMPORTED_MODULES_INTO_MAIN` macro instead of +`#US_LOAD_IMPORTED_MODULES` when importing static modules into an executable. + +Example code for importing the two static modules `MyStaticModule1` and `MyStaticModule2` into an executable: + +\snippet uServices-staticmodules/main.cpp ImportStaticModuleIntoMain + +Importing the static module `MyStaticModule` into a shared or static module looks like this: + +\snippet uServices-staticmodules/main.cpp ImportStaticModuleIntoLib + +Having a shared CppMicroServices library, the executable also needs some initialization code: + +\snippet uServices-staticmodules/main.cpp InitializeExecutable + +Note that shared (but not static) modules also need the `#US_INITIALIZE_MODULE` call when importing static modules. + +## Using a Static CppMicroServices Library + +The CppMicroServices library can be build as a static library. In that case, creating shared modules is not supported. +If you create shared modules which link a static version of the CppMicroServices library, the runtime behavior is +undefined. + +In this usage scenario, every module will be statically build and linked to an executable. The executable needs to +import all the static modules, just like above: + +\snippet uServices-staticmodules/main.cpp ImportStaticModuleIntoMain + +However, it can omit the `#US_INITIALIZE_MODULE` macro call (the module context from the CppMicroServices library +will be shared across all modules and the executable). + +# A Note About The Module Context {#MicroServices_StaticModules_Context} + +Modules using the CppMicroServices API frequently need a `ModuleContext` object to query, retrieve, and register services. +Static modules will never get their own module context but will share the context with their importing module or +executable. Therefore, the importing module or executable needs to ensure the availability of such a context (by using +the `#US_INITIALIZE_MODULE` or `#US_INITIALIZE_EXECUTABLE` macro). + +\note The CppMicroServices library will *always* provide a module context, independent of its library build mode. + +So in a completely statically build application, the CppMicroServices library provides a global module context for all +imported modules and the executable. diff --git a/documentation/doxygen/MicroServices_TheModuleContext.md b/documentation/doxygen/MicroServices_TheModuleContext.md new file mode 100644 index 0000000000..f35054b556 --- /dev/null +++ b/documentation/doxygen/MicroServices_TheModuleContext.md @@ -0,0 +1,37 @@ +The Module Context {#MicroServices_TheModuleContext} +=================== + +In the context of the C++ Micro Services library, we will call all supported "shared library" types +(DLL, DSO, DyLib, etc.) uniformly a *module*. A module accesses the C++ Micro Services API via a +ModuleContext object. While multiple modules could use the same ModuleContext, it is highly recommended +that each module gets its own (this will enable module specific service usage tracking and also allows +the C++ Micro Services framework to properly cleanup resources after a module has been unloaded). + +### Creating a ModuleContext + +To create a ModuleContext object for a specific library, you have two options. If your project uses +CMake as the build system, use the supplied `#usFunctionGenerateModuleInit` CMake function to automatically +create a source file and add it to your module's sources: + +~~~{.cpp} +set(module_srcs ) +usFunctionGenerateModuleInit(module_srcs + NAME "My Module" + LIBRARY_NAME "mylibname" + ) +add_library(mylib ${module_srcs}) +~~~ + +If you do not use CMake, you have to add a call to the macro `#US_INITIALIZE_MODULE` in one of the source +files of your module: + +\snippet uServices-modulecontext/main.cpp InitializeModule + +### Getting a ModuleContext + +To retrieve the module specific ModuleContext object from anywhere in your module, use the +`#GetModuleContext` function: + +\snippet uServices-modulecontext/main.cpp GetModuleContext + +Please note that the call to `#GetModuleContext` will fail if you did not create a module specific context. diff --git a/documentation/doxygen/doxygen_extra.css b/documentation/doxygen/doxygen_extra.css new file mode 100644 index 0000000000..4328573360 --- /dev/null +++ b/documentation/doxygen/doxygen_extra.css @@ -0,0 +1,283 @@ + +#MSearchField { + height: 14px; +} + +#MSearchClose { + top: 1px; +} + +#MSearchResultsWindow { + z-index: 200; +} + +body { + background-color: inherit; +} + +body, table, div, p, dl { + font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; + font-size: 13px; + line-height: 18px; + color: #333333; +} + +h1 { + font-size: 150%; +} + +h2 { + font-size: 120%; +} + +h3 { + font-size: 100%; +} + +a { + color: #0088CC; +} + +div#top { + background-color: #F5F5F5; + margin: -20px -20px 20px; +} + +.tabs, .tabs2, .tabs3 { + font-size: 16px; + position: relative; + background-image: none; +} + +.tabs2 { + font-size: 14px; +} +.tabs3 { + font-size: 12px; +} + +.tablist li { + background-image: none; + line-height: inherit; +} + +.tablist a { + background-image: none; + padding: 10px 20px; + color: #999999; +} + +.tablist a:hover { + text-decoration: underline; + background-image: none; + text-shadow: none; + color: #999999; +} + +.tablist li.current a { + background-image: none; + background-color: #BBBBBB; + text-shadow: none; +} + +div.qindex, div.navtab { + background-color: inherit; + border: 1px solid #e6e6e6; +} + +h2.groupheader { + border: none; + font-size: 120%; + font-weight: bold; + color: #333333; +} + +pre.fragment { + border: none; + border-top-style: solid; + border-bottom-style: solid; + border-width: 1px 0 1px 0; + border-color: #e6e6e6; + border-radius: 0; +} + +div.fragment { + padding: 4px 6px; + margin: 4px 8px 4px 2px; + border: none; + border-top-style: solid; + border-bottom-style: solid; + border-width: 1px 0 1px 0; + border-color: #e6e6e6; + background-color: #F5F5F5; +} + +div.line { + -webkit-transition-property: none; + -moz-transition-property: none; + -ms-transition-property: none; + -o-transition-property: none; + transition-property: none; +} + +div.ah { + background-color: #f6f6f6; + border: solid thin #e6e6e6; + box-shadow: none; + -webkit-box-shadow: none; + -moz-box-shadow: none; + background-image: none; + color: #333333; +} + +td.indexkey, td.indexvalue { + background-color: inherit; + border: none; +} + +tr.separator\3A, td.memSeparator { + display: none; +} + +hr { + border-top: 1px solid #e6e6e6; +} + +.mdescLeft, .mdescRight, +.memItemLeft, .memItemRight, +.memTemplItemLeft, .memTemplItemRight, .memTemplParams { + background-color: inherit; +} + +.memItemLeft, .memItemRight, .memTemplParams { + border: none; +} + +.memproto, dl.reflist dt { + border-top: 1px solid #e6e6e6; + border-left: 1px solid #e6e6e6; + border-right: 1px solid #e6e6e6; + text-shadow: none; + background-image: none; + background-color: #f6f6f6; + /* opera specific markup */ + box-shadow: none; + border-top-right-radius: 8px; + border-top-left-radius: 8px; + /* firefox specific markup */ + -moz-box-shadow: none; + -moz-border-radius-topright: 8px; + -moz-border-radius-topleft: 8px; + /* webkit specific markup */ + -webkit-box-shadow: none; + -webkit-border-top-right-radius: 8px; + -webkit-border-top-left-radius: 8px; +} + +.memdoc, dl.reflist dd { + border-bottom: 1px solid #e6e6e6; + border-left: 1px solid #e6e6e6; + border-right: 1px solid #e6e6e6; + padding: 2px 5px; + background-color: inherit; + background-image: none; + border-top-width: 0; + /* opera specific markup */ + border-bottom-left-radius: 8px; + border-bottom-right-radius: 8px; + box-shadow:none; + /* firefox specific markup */ + -moz-border-radius-bottomleft: 8px; + -moz-border-radius-bottomright: 8px; + -moz-box-shadow: none; + /* webkit specific markup */ + -webkit-border-bottom-left-radius: 8px; + -webkit-border-bottom-right-radius: 8px; + -webkit-box-shadow: none; +} + +.paramname code { + line-height: inherit; +} + +.params .paramname, .tparams .paramname, .retval .paramname { + padding-right: 10px; +} + +span.mlabel { + border-top:1px solid #405C93; + border-left:1px solid #405C93; +} + +div.directory { + border: none; +} + +.directory td { + vertical-align: baseline; +} + +.directory tr.even { + background-color: inherit; +} + +address { + color: inherit; + margin: 0; +} + +.navpath ul +{ + background-image: none; + height: auto; + line-height: inherit; + color: inherit; + border: none; +} + +.navpath li +{ + background-image: none; + color: inherit; +} + +.navpath li.navelem a +{ + height:22px; + color: #999; +} + +.navpath li.navelem a:hover +{ + text-decoration: underline; +} + +div.ingroups +{ + margin-left: 5px; + padding-left: 5px; +} + +div.header +{ + background-image: none; + background-color: inherit; + border-bottom: 1px solid #333333; +} + +div.headertitle +{ + padding: 0px 5px 0px 7px; +} + +dl.note, dl.warning, dl.attention, dl.pre, dl.post, dl.invariant, dl.deprecated, dl.todo, dl.test, dl.bug +{ + margin-left: 12px; +} + +code { + background-color: none; + border: none; + color: #333333; + padding: 1; +} diff --git a/documentation/doxygen/examples/MicroServices_Example1.md b/documentation/doxygen/examples/MicroServices_Example1.md new file mode 100644 index 0000000000..e5c92e2981 --- /dev/null +++ b/documentation/doxygen/examples/MicroServices_Example1.md @@ -0,0 +1,97 @@ +Example 1 - Service Event Listener {#MicroServices_Example1} +================================== + +This example creates a simple module that listens for service events. +This example does not do much at first, because it only prints out the details +of registering and unregistering services. In the next example we will create +a module that implements a service, which will cause this module to actually +do something. For now, we will just use this example to help us understand the +basics of creating a module and its activator. + +A module gains access to the C++ Micro Services API using a unique instance +of ModuleContext. This unique module context can be used during static +initialization of the module or at any later point during the life-time of the +module. To execute code during static initialization (and de-initialization) +time, the module must provide an implementation of the ModuleActivator interface; +this interface has two methods, Load() and Unload(), that both receive the +module's context and are called when the module is loaded (statically initialized) +and unloaded, respectively. + +\note You do not need to remember the ModuleContext instance within the +ModuleActivator::Load() method and provide custom access methods for later +retrieval. Use the GetModuleContext() function to easily retrieve the current +module's context. + +In the following source code, our module implements +the ModuleActivator interface and uses the context to add itself as a listener +for service events (in the `eventlistener/Activator.cpp` file): + +\snippet eventlistener/Activator.cpp Activator + +After implementing the C++ source code for the module activator, we must *export* +the activator such that the C++ Micro Services library can create an instance +of it and call the `Load()` and `Unload()` methods: + +\dontinclude eventlistener/Activator.cpp +\skipline US_EXPORT + +Now we need to compile the source code. This example uses CMake as the build +system and the top-level CMakeLists.txt file could look like this: + +\dontinclude examples/CMakeLists.txt +\skip project +\until eventlistener + +and the CMakeLists.txt file in the eventlistener subdirectory is: + +\include eventlistener/CMakeLists.txt + +The call to `#usFunctionGenerateModuleInit` is necessary to integrate the shared +library as a module within the C++ Micro Service library. If you are not using +CMake, you have to place a macro call to `#US_INITIALIZE_MODULE` yourself into the +module's source code, e.g. in `Activator.cpp`. Have a look at the +\ref MicroServices_GettingStarted documentation for more details about using CMake +or other build systems (e.g. Makefiles) when writing modules. + +To run the examples contained in the C++ Micro Services library, we use a small +driver program called `CppMicroServicesExampleDriver`: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> h +h This help text +l Load the module with id or name +u Unload the module with id +s Print status information +q Quit +> +\endverbatim + +Typing `s` at the command prompt lists the available, loaded, and unloaded modules. +To load the eventlistener module, type `l eventlistener` at the command prompt: + +\verbatim +> s +Id | Name | Status +----------------------------------- + - | dictionaryclient | - + - | dictionaryclient2 | - + - | dictionaryclient3 | - + - | dictionaryservice | - + - | eventlistener | - + - | frenchdictionary | - + - | spellcheckclient | - + - | spellcheckservice | - + 1 | CppMicroServices | LOADED +> l eventlistener +Starting to listen for service events. +> +\endverbatim + +The above command loaded the eventlistener module (by loading its shared library). +Keep in mind, that this module will not do much at this point since it only +listens for service events and we are not registering any services. In the next +example we will register a service that will generate an event for this module to +receive. To exit the `CppMicroServicesExampleDriver`, use the `q` command. + +Next: \ref MicroServices_Example2 diff --git a/documentation/doxygen/examples/MicroServices_Example2.md b/documentation/doxygen/examples/MicroServices_Example2.md new file mode 100644 index 0000000000..b7fe0bbca3 --- /dev/null +++ b/documentation/doxygen/examples/MicroServices_Example2.md @@ -0,0 +1,87 @@ +Example 2 - Dictionary Service Module {#MicroServices_Example2} +===================================== + +This example creates a module that implements a service. Implementing a +service is a two-step process, first we must define the interface of the service +and then we must define an implementation of the service interface. In this +particular example, we will create a dictionary service that we can use to check +if a word exists, which indicates if the word is spelled correctly or not. First, +we will start by defining a simple dictionary service interface in a file called +`dictionaryservice/IDictionaryService.h`: + +\snippet dictionaryservice/IDictionaryService.h service + +The service interface is quite simple, with only one method that needs to be +implemented. Because we provide an empty out-of-line destructor (defined in the +file `IDictionaryService.cpp`) we must export the service interface by using the +module specific `DICTIONARYSERVICE_EXPORT` macro. + +In the following source code, the module uses its module context +to register the dictionary service. We implement the dictionary service as an +inner class of the module activator class, but we could have also put it in a +separate file. The source code for our module is as follows in a file called +`dictionaryservice/Activator.cpp`: + +\snippet dictionaryservice/Activator.cpp Activator + +Note that we do not need to unregister the service in the Unload() method, +because the C++ Micro Services library will automatically do so for us. The +dictionary service that we have implemented is very simple; its dictionary +is a set of only five words, so this solution is not optimal and is only +intended for educational purposes. + +\note In this example, the service interface and implementation are both +contained in one module which exports the interface class. However, service +implementations almost never need to be exported and in many use cases +it is beneficial to provide the service interface and its implementation(s) +in separate modules. In such a scenario, clients of a service will only +have a link-time dependency on the shared library providing the service interface +(because of the out-of-line destructor) but not on any modules containing +service implementations. This often leads to modules which do not export +any symbols at all and hence need to be loaded into the running process +manually or by using the \ref MicroServices_AutoLoading "auto-loading mechanism". + +For an introduction how to compile our source code, see \ref MicroServices_Example1. + +After running the `CppMicroServicesExampleDriver` program we should make sure that the +module from Example 1 is active. We can use the `s` shell command to get +a list of all modules, their state, and their module identifier number. +If the Example 1 module is not active, we should load the module using the +load command and the module's identifier number or name that is displayed +by the `s` command. Now we can load our dictionary service module by typing +the `l dictionaryservice` command: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> s +Id | Name | Status +----------------------------------- + - | dictionaryservice | - + - | eventlistener | - + 1 | CppMicroServices | LOADED +> l eventlistener +Starting to listen for service events. +> l dictionaryservice +Ex1: Service of type IDictionaryService/1.0 registered. +> s +Id | Name | Status +----------------------------------- + 1 | CppMicroServices | LOADED + 2 | Event Listener | LOADED + 3 | Dictionary Service | LOADED +> +\endverbatim + +To unload the module, use the `u ` command. If the module from +\ref MicroServices_Example1 "Example 1" is still active, +then we should see it print out the details of the service event it receives +when our new module registers its dictionary service. Using the `CppMicroServicesExampleDriver` +commands `u` and `l` we can unload and load it at will, respectively. Each +time we load and unload our dictionary service module, we should see the details +of the associated service event printed from the module from Example 1. In +\ref MicroServices_Example3 "Example 3", we will create a client for our +dictionary service. To exit `CppMicroServicesExampleDriver`, we use the `q` command. + +Next: \ref MicroServices_Example2b + +Previous: \ref MicroServices_Example1 diff --git a/documentation/doxygen/examples/MicroServices_Example2b.md b/documentation/doxygen/examples/MicroServices_Example2b.md new file mode 100644 index 0000000000..4045a8e483 --- /dev/null +++ b/documentation/doxygen/examples/MicroServices_Example2b.md @@ -0,0 +1,76 @@ +Example 2b - Alternative Dictionary Service Module {#MicroServices_Example2b} +================================================== + +This example creates an alternative implementation of the dictionary service +defined in \ref MicroServices_Example2 "Example 2". The source code for the +module is identical except that instead of using English words, French words +are used. The only other difference is that in this module we do not need to +define the dictionary service interface again, since we can just link the +definition from the module in Example 2. The main point of this example is +to illustrate that multiple implementations of the same service may exist; +this example will also be of use to us in \ref MicroServices_Example5 "Example 5". + +In the following source code, the module uses its module context +to register the dictionary service. We implement the dictionary service as an +inner class of the module activator class, but we could have also put it in a +separate file. The source code for our module is as follows in a file called +`dictionaryclient/Activator.cpp`: + +\snippet frenchdictionary/Activator.cpp Activator + +For an introduction how to compile our source code, see \ref MicroServices_Example1. +Because we use the `IDictionaryService` definition from Example 2, we also +need to make sure that the proper include paths and linker dependencies are set: + +\include frenchdictionary/CMakeLists.txt + +After running the `CppMicroServicesExampleDriver` program we should make sure that the +module from Example 1 is active. We can use the `s` shell command to get +a list of all modules, their state, and their module identifier number. +If the Example 1 module is not active, we should load the module using the +load command and the module's identifier number or name that is displayed +by the `s` command. Now we can load our dictionary service module by typing +the `l frenchdictionary` command: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> s +Id | Name | Status +----------------------------------- + - | dictionaryservice | - + - | eventlistener | - + - | frenchdictionary | - + 1 | CppMicroServices | LOADED +> l eventlistener +Starting to listen for service events. +> l frenchdictionary +Ex1: Service of type IDictionaryService/1.0 registered. +Ex1: Service of type IDictionaryService/1.0 registered. +> s +Id | Name | Status +----------------------------------- + 1 | CppMicroServices | LOADED + 2 | Event Listener | LOADED + 3 | Dictionary Service | LOADED + 4 | French Dictionary | LOADED +> +\endverbatim + +To unload the module, use the `u ` command. If the module from +\ref MicroServices_Example1 "Example 1" is still active, +then we should see it print out the details of the service event it receives +when our new module registers its dictionary service. Using the `CppMicroServicesExampleDriver` +commands `u` and `l` we can unload and load it at will, respectively. Each +time we load and unload our dictionary service module, we should see the details +of the associated service event printed from the module from Example 1. In +\ref MicroServices_Example3 "Example 3", we will create a client for our +dictionary service. To exit `CppMicroServicesExampleDriver`, we use the `q` command. + +\note Because our french dictionary module has a link dependency on the +dictionary service module from Example 2, this module is automatically loaded +by the operating system loader. Unloading it will only succeed if there are +no other dependent modules like our french dictionary module currently loaded. + +Next: \ref MicroServices_Example3 + +Previous: \ref MicroServices_Example2 diff --git a/documentation/doxygen/examples/MicroServices_Example3.md b/documentation/doxygen/examples/MicroServices_Example3.md new file mode 100644 index 0000000000..2c225c7ecf --- /dev/null +++ b/documentation/doxygen/examples/MicroServices_Example3.md @@ -0,0 +1,58 @@ +Example 3 - Dictionary Client Module {#MicroServices_Example3} +==================================== + +This example creates a module that is a client of the dictionary service +implemented in \ref MicroServices_Example2 "Example 2". In the following +source code, our module uses its module context to query for a dictionary +service. Our client module uses the first dictionary service it finds and +if none are found it simply prints a message saying so and stops. Using +a service is the same as using any C++ class. The source code for our +module is as follows in a file called `dictionaryclient2/Activator.cpp`: + +\snippet dictionaryclient/Activator.cpp Activator + +Note that we do not need to unget or release the service in the Unload() +method, because the C++ Micro Services library will automatically do so +for us. + +Since we are using the `IDictionaryService` interface defined in Example 1, +we must link our module to the `dictionaryservice` module: + +\include dictionaryclient/CMakeLists.txt + +After running the `CppMicroServicesExampleDriver` executable, and loading the event +listener module, we can use the `l dictionaryclient` command to load +our dictionary client module: + +\verbatim +CppMicroServices-debug> bin/CppMicroServicesExampleDriver +> l eventlistener +Starting to listen for service events. +> l dictionaryclient +Ex1: Service of type IDictionaryService/1.0 registered. +Enter a blank line to exit. +Enter word: +\endverbatim + +The above command loads the module and its dependencies (the `dictionaryservice` +module) in a single step. When we load the module, it will use the main thread to +prompt us for words. Enter one word at a time to check the words and enter a +blank line to stop checking words. To reload the module, we must use the `s` +command to get the module identifier number for the module and first use the +`u ` command to unload the module, then the `l ` command to re-load it. +To test the dictionary service, enter any of the words in the dictionary +(e.g., "welcome", "to", "the", "micro", "services", "tutorial") or any word not +in the dictionary. + +This example client is simple enough and, in fact, is too simple. What would +happen if the dictionary service were to unregister suddenly? Our client would +abort with a segmentation fault due to a null pointer access when trying to use +the service object. This dynamic service availability issue is a central tenent +of the service model. As a result, we must make our client more robust in dealing +with such situations. In \ref MicroServices_Example4 "Example 4", we explore a +slightly more complicated dictionary client that dynamically monitors service +availability. + +Next: \ref MicroServices_Example4 + +Previous: \ref MicroServices_Example2 diff --git a/documentation/doxygen/examples/MicroServices_Example4.md b/documentation/doxygen/examples/MicroServices_Example4.md new file mode 100644 index 0000000000..a43e7dc970 --- /dev/null +++ b/documentation/doxygen/examples/MicroServices_Example4.md @@ -0,0 +1,66 @@ +Example 4 - Robust Dictionary Client Module {#MicroServices_Example4} +=========================================== + +In \ref MicroServices_Example3 "Example 3", we create a simple client module +for our dictionary service. The problem with that client was that it did not +monitor the dynamic availability of the dictionary service, thus an error +would occur if the dictionary service disappeared while the client was using it. +In this example we create a client for the dictionary service that monitors +the dynamic availability of the dictionary service. The result is a more robust +client. + +The functionality of the new dictionary client is essentially the same as the +old client, it reads words from standard input and checks for their existence +in the dictionary service. Our module uses its module context to register itself +as a service event listener; monitoring service events allows the module to +monitor the dynamic availability of the dictionary service. Our client uses the +first dictionary service it finds. The source code for our module is as follows +in a file called `Activator.cpp`: + +\snippet dictionaryclient2/Activator.cpp Activator + +The client listens for service events indicating the arrival or departure of +dictionary services. If a new dictionary service arrives, the module will start +using that service if and only if it currently does not have a dictionary service. +If an existing dictionary service disappears, the module will check to see if the +disappearing service is the one it is using; if it is it stops using it and tries +to query for another dictionary service, otherwise it ignores the event. + +As in Example 3, we must link our module to the `dictionaryservice` module: + +\include dictionaryclient2/CMakeLists.txt + +After running the `CppMicroServicesExampleDriver` executable, and loading the event +listener module, we can use the `l dictionaryclient2` command to load +our robust dictionary client module: + +\verbatim +CppMicroServices-debug> bin/CppMicroServicesExampleDriver +> l eventlistener +Starting to listen for service events. +> l dictionaryclient2 +Ex1: Service of type IDictionaryService/1.0 registered. +Enter a blank line to exit. +Enter word: +\endverbatim + +The above command loads the module and its dependencies (the `dictionaryservice` +module) in a single step. When we load the module, it will use the main thread to +prompt us for words. Enter one word at a time to check the words and enter a +blank line to stop checking words. To reload the module, we must use the `s` +command to get the module identifier number for the module and first use the +`u ` command to unload the module, then the `l ` command to re-load it. +To test the dictionary service, enter any of the words in the dictionary +(e.g., "welcome", "to", "the", "micro", "services", "tutorial") or any word not +in the dictionary. + +Since this client monitors the dynamic availability of the dictionary service, +it is robust in the face of sudden departures of the the dictionary service. +Further, when a dictionary service arrives, it automatically gets the service if +it needs it and continues to function. These capabilities are a little difficult +to demonstrate since we are using a simple single-threaded approach, but in a +multi-threaded or GUI-oriented application this robustness is very useful. + +Next: \ref MicroServices_Example5 + +Previous: \ref MicroServices_Example3 diff --git a/documentation/doxygen/examples/MicroServices_Example5.md b/documentation/doxygen/examples/MicroServices_Example5.md new file mode 100644 index 0000000000..419fbad5bb --- /dev/null +++ b/documentation/doxygen/examples/MicroServices_Example5.md @@ -0,0 +1,61 @@ +Example 5 - Service Tracker Dictionary Client Module {#MicroServices_Example5} +==================================================== + +In \ref MicroServices_Example4 "Example 4", we created a more robust client bundle +for our dictionary service. Due to the complexity of dealing with dynamic service +availability, even that client may not sufficiently address all situations. To +deal with this complexity the C++ Micro Services library provides the `ServiceTracker` +utility class. In this example we create a client for the dictionary service that +uses the `ServiceTracker` class to monitor the dynamic availability of the dictionary +service, resulting in an even more robust client. + +The functionality of the new dictionary client is essentially the same as the one +from Example 4. Our module uses its module context to create a `ServiceTracker` +instance to track the dynamic availability of the dictionary service on our behalf. +Our client uses the dictionary service returned by the `ServiceTracker`, which is +selected based on a ranking algorithm defined by the C++ Micro Services library. +The source code for our modules is as follows in a file called +`dictionaryclient3/Activator.cpp`: + +\snippet dictionaryclient3/Activator.cpp Activator + +Since this client uses the `ServiceTracker` utility class, it will automatically +monitor the dynamic availability of the dictionary service. Again, we must link +our module to the `dictionaryservice` module: + +\include dictionaryclient3/CMakeLists.txt + +After running the `CppMicroServicesExampleDriver` executable, and loading the event +listener module, we can use the `l dictionaryclient3` command to load +our robust dictionary client module: + +\verbatim +CppMicroServices-debug> bin/CppMicroServicesExampleDriver +> l eventlistener +Starting to listen for service events. +> l dictionaryclient3 +Ex1: Service of type IDictionaryService/1.0 registered. +Enter a blank line to exit. +Enter word: +\endverbatim + +The above command loads the module and its dependencies (the `dictionaryservice` +module) in a single step. When we load the module, it will use the main thread to +prompt us for words. Enter one word at a time to check the words and enter a +blank line to stop checking words. To reload the module, we must use the `s` +command to get the module identifier number for the module and first use the +`u ` command to unload the module, then the `l ` command to re-load it. +To test the dictionary service, enter any of the words in the dictionary +(e.g., "welcome", "to", "the", "micro", "services", "tutorial") or any word not +in the dictionary. + +Since this client monitors the dynamic availability of the dictionary service, +it is robust in the face of sudden departures of the the dictionary service. +Further, when a dictionary service arrives, it automatically gets the service if +it needs it and continues to function. These capabilities are a little difficult +to demonstrate since we are using a simple single-threaded approach, but in a +multi-threaded or GUI-oriented application this robustness is very useful. + +Next: \ref MicroServices_Example6 + +Previous: \ref MicroServices_Example4 diff --git a/documentation/doxygen/examples/MicroServices_Example6.md b/documentation/doxygen/examples/MicroServices_Example6.md new file mode 100644 index 0000000000..66559e8931 --- /dev/null +++ b/documentation/doxygen/examples/MicroServices_Example6.md @@ -0,0 +1,123 @@ +Example 6 - Spell Checker Service Module {#MicroServices_Example6} +======================================== + +In this example, we complicate things further by defining a new service that +uses an arbitrary number of dictionary services to perform its function. More +precisely, we define a spell checker service which will aggregate all dictionary +services and provide another service that allows us to spell check passages +using our underlying dictionary services to verify the spelling of words. Our +module will only provide the spell checker service if there are at least two +dictionary services available. First, we will start by defining the spell checker +service interface in a file called `spellcheckservice/ISpellCheckService.h`: + +\snippet spellcheckservice/ISpellCheckService.h service + +The service interface is quite simple, with only one method that needs to be +implemented. Because we provide an empty out-of-line destructor (defined in the +file `ISpellCheckService.cpp`) we must export the service interface by using the +module specific `SPELLCHECKSERVICE_EXPORT` macro. + +In the following source code, the module needs to create a complete list of all +dictionary services; this is somewhat tricky and must be done carefully if done +manually via service event listners. Our module makes use of the `ServiceTracker` +and `ServiceTrackerCustomizer` classes to robustly react to service events related +to dictionary services. The module activator of our module now additionally implements +the `ServiceTrackerCustomizer` class to be automatically notified of arriving, departing, +or modified dictionary services. In case of a newly added dictionary service, our +`ServiceTrackerCustomizer::AddingService()` implementation checks if a spell checker +service was already registered and if not registers a new `ISpellCheckService` instance +if at lead two dictionary services are available. +If the number of dictionary services drops below two, our `ServiceTrackerCustomizer` +implementation un-registers the previously registered spell checker service instance. +These actions must be performed in a synchronized manner to avoid interference from +service events originating from different threads. The implementation of our module +activator is done in a file called `spellcheckservice/Activator.cpp`: + +\snippet spellcheckservice/Activator.cpp Activator + +Note that we do not need to unregister the service in stop() method, because the +C++ Micro Services library will automatically do so for us. The spell checker service +that we have implemented is very simple; it simply parses a given passage into words +and then loops through all available dictionary services for each word until it +determines that the word is correct. Any incorrect words are added to an error list +that will be returned to the caller. This solution is not optimal and is only intended +for educational purposes. + +\note In this example, the service interface and implementation are both +contained in one module which exports the interface class. However, service +implementations almost never need to be exported and in many use cases +it is beneficial to provide the service interface and its implementation(s) +in separate modules. In such a scenario, clients of a service will only +have a link-time dependency on the shared library providing the service interface +(because of the out-of-line destructor) but not on any modules containing +service implementations. This often leads to modules which do not export +any symbols at all and hence need to be loaded into the running process +manually or by using the \ref MicroServices_AutoLoading "auto-loading mechanism". + +\note Due to the link dependency of our module to the module containing the +dictionary service interface as well as a default implementation for it, there +might be at least one dictionary service registered when our module is +loaded, depending on your linker settings (e.g. on Windows, the linker usually +by default optimizes the link dependency away since our module does not actually +use any symbols from the dictionaryservice module. On Linux however, the link +dependency is kept by default.) To observe the dynamic registration and +un-registration of our spell checker service, we require the availability of +at least two dictionary services. + +For an introduction how to compile our source code, see \ref MicroServices_Example1. + +After running the `CppMicroServicesExampleDriver` program we should make sure that the +module from Example 1 is active. We can use the `s` shell command to get +a list of all modules, their state, and their module identifier number. +If the Example 1 module is not active, we should load the module using the +load command and the module's identifier number or name that is displayed +by the `s` command. Now we can load the spell checker service module by +entering the `l spellcheckservice` command which will also trigger the loading +of the dictionaryservice module containing the english dictionary: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> l eventlistener +Starting to listen for service events. +> l spellcheckservice +Ex1: Service of type IDictionaryService/1.0 registered. +> s +Id | Name | Status +----------------------------------- + - | dictionaryclient | - + - | dictionaryclient2 | - + - | dictionaryclient3 | - + - | frenchdictionary | - + - | spellcheckclient | - + 1 | CppMicroServices | LOADED + 2 | Event Listener | LOADED + 3 | Dictionary Service | LOADED + 4 | Spell Check Service | LOADED +> +\endverbatim + +To trigger the registration of the spell checker service from our module, we +load the frenchdictionary using the `l frenchdictionary` command. If the module from +\ref MicroServices_Example1 "Example 1" is still active, +then we should see it print out the details of the service event it receives +when our new module registers its spell checker service: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> l frenchdictionary +Ex1: Service of type IDictionaryService/1.0 registered. +Ex1: Service of type ISpellCheckService/1.0 registered. +> +\endverbatim + +We can experiment with our spell checker service's dynamic availability by stopping +the french dictionary service; when the service is stopped, +the eventlistener module will print that our module is no longer offering its +spell checker service. Likewise, when the french dictionary service comes back, so will +our spell checker service. We create a client for our spell checker service in +\ref MicroServices_Example7 "Example 7". To exit the `CppMicroServicesExampleDriver` program, we +use the `q` command. + +Next: \ref MicroServices_Example7 + +Previous: \ref MicroServices_Example5 diff --git a/documentation/doxygen/examples/MicroServices_Example7.md b/documentation/doxygen/examples/MicroServices_Example7.md new file mode 100644 index 0000000000..8bcdc5e997 --- /dev/null +++ b/documentation/doxygen/examples/MicroServices_Example7.md @@ -0,0 +1,73 @@ +Example 7 - Spell Checker Client Module {#MicroServices_Example7} +======================================= + +In this example we create a client for the spell checker service we implemented +in \ref MicroServices_Example6 "Example 6". This client monitors the dynamic +availability of the spell checker service using the Service Tracker and is very +similar in structure to the dictionary client we implemented in +\ref MicroServices_Example5 "Example 5". The functionality of the spell checker +client reads passages from standard input and spell checks them using the spell +checker service. Our module uses its module context to create a `ServiceTracker` +object to monitor spell checker services. The source code for our module is as +follows in a file called `spellcheckclient/Activator.cpp`: + +\snippet spellcheckclient/Activator.cpp Activator + +After running the `CppMicroServicesExampleDriver` program use the `s` command to make sure that +only the modules from Example 2, Example 2b, and Example 6 are loaded; use the +load (`l`) and un-load (`u`) commands as appropriate to load and un-load the +various tutorial modules, respectively. Now we can load our spell checker client +module by entering `l spellcheckclient`: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> l +Starting to listen for service events. +> l spellcheckservice +Ex1: Service of type IDictionaryService/1.0 registered. +> s +Id | Name | Status +----------------------------------- + - | dictionaryclient | - + - | dictionaryclient2 | - + - | dictionaryclient3 | - + - | frenchdictionary | - + - | spellcheckclient | - + 1 | CppMicroServices | LOADED + 2 | Event Listener | LOADED + 3 | Dictionary Service | LOADED + 4 | Spell Check Service | LOADED +> +\endverbatim + +To trigger the registration of the spell checker service from our module, we +load the frenchdictionary using the `l frenchdictionary` command. If the module from +\ref MicroServices_Example1 "Example 1" is still active, +then we should see it print out the details of the service event it receives +when our new module registers its spell checker service: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> l spellcheckservice +> l frenchdictionary +> l spellcheckclient +Enter a blank line to exit. +Enter passage: +\endverbatim + +When we start the module, it will use the main thread to prompt us for passages; a +passage is a collection or words separate by spaces, commas, periods, exclamation +points, question marks, colons, or semi-colons. Enter a passage and press the enter +key to spell check the passage or enter a blank line to stop spell checking passages. +To restart the module, we must use the command `s` command to get the module identifier +number for the module and first use the `u` command to un-load the module, then the +`l` command to re-load it. + +Since this client uses the Service Tracker to monitor the dynamic availability of the +spell checker service, it is robust in the scenario where the spell checker service +suddenly departs. Further, when a spell checker service arrives, it automatically gets +the service if it needs it and continues to function. These capabilities are a little +difficult to demonstrate since we are using a simple single-threaded approach, but in +a multi-threaded or GUI-oriented application this robustness is very useful. + +Previous: \ref MicroServices_Example6 diff --git a/documentation/doxygen/footer.html b/documentation/doxygen/footer.html new file mode 100644 index 0000000000..ea6b6dac83 --- /dev/null +++ b/documentation/doxygen/footer.html @@ -0,0 +1,4 @@ + + + diff --git a/documentation/doxygen/header.html b/documentation/doxygen/header.html new file mode 100644 index 0000000000..cc5afab151 --- /dev/null +++ b/documentation/doxygen/header.html @@ -0,0 +1,23 @@ +--- +layout: default +title: $title +--- + + + + $projectname: $title + $title + + + + + $treeview + $search + $mathjax + + + $extrastylesheet + + + +
diff --git a/documentation/doxygen/standalone/BuildInstructions.md b/documentation/doxygen/standalone/BuildInstructions.md new file mode 100644 index 0000000000..8319e6bd7a --- /dev/null +++ b/documentation/doxygen/standalone/BuildInstructions.md @@ -0,0 +1,59 @@ +Build Instructions {#BuildInstructions} +================== + +The C++ Micro Services library provides [CMake][cmake] build scripts which allow the generation of +platform and IDE specific project files. + +The library should compile on many different platforms. Below is a list of tested compiler/OS combinations: + + - GCC 4.5 (Ubuntu 11.04 and MacOS X 10.6) + - GCC 4.7 (Ubuntu 12.10) + - Visual Studio 2008, 2010, and 2012 + - Clang 3.0 (Ubuntu 12.10 and MacOS X 10.6) + + +Prerequisites +------------- + +- [CMake][cmake] 2.8 (Visual Studio 2010 and 2012 users should use the latest CMake version available) + + +Configuring the Build +--------------------- + +When building the C++ Micro Services library, you have a few configuration options at hand. + +### General build options + +- **CMAKE_INSTALL_PREFIX** + The installation path. +- **US_BUILD_SHARED_LIBS** + Specify if the library should be build shared or static. See \ref MicroServices_StaticModules + for detailed information about static CppMicroServices modules. +- **US_BUILD_TESTING** + Build unit tests and code snippets. +- **US_ENABLE_AUTOLOADING_SUPPORT** + Enable auto-loading of modules located in special sup-directories. See \ref MicroServices_AutoLoading + for detailed information about this feature. +- **US_ENABLE_THREADING_SUPPORT** + Enable the use of synchronization primitives (atomics and pthread mutexes or Windows primitives) + to make the API thread-safe. If you are application is not multi-threaded, turn this option OFF + to get maximum performance. +- **US_USE_C++11 (advanced)** + Enable the usage of C++11 constructs. +- **US_ENABLE_RESOURCE_COMPRESSION (advanced)** + Enable compression of embedded resources. See \ref MicroServices_Resources for detailed information + about the resource system. + +### Customizing naming conventions + +- **US_NAMESPACE** + The default namespace is `us` but you may override this at will. +- **US_HEADER_PREFIX** + By default, all public headers have a "us" prefix. You may specify an arbitrary prefix to match your + naming conventions. + +The above options are mainly useful when embedding the C++ Micro Services source code in your own library and +you want to make it look like native source code. + +[cmake]: http://www.cmake.org diff --git a/documentation/doxygen/standalone/MicroServices_GettingStarted.md b/documentation/doxygen/standalone/MicroServices_GettingStarted.md new file mode 100644 index 0000000000..fec5a1105c --- /dev/null +++ b/documentation/doxygen/standalone/MicroServices_GettingStarted.md @@ -0,0 +1,49 @@ +Getting Started {#MicroServices_GettingStarted} +=============== + +Projects which want to make use of the capabilities provided by the C++ Micro Services +library need to set-up the correct include paths and link dependencies. Further, each +executable or shared library which needs a ModuleContext instance must contain specific +initialization code. + +The C++ Micro Services library provides \ref MicroServicesCMake "CMake utility functions" +for CMake based projects but there are no restrictions on the type of build system used +for a project. + +CMake based projects +-------------------- + +To easily set-up include paths and linker dependencies, use the common `find_package` +mechanism provided by CMake: + +\dontinclude examples/CMakeLists.txt +\skip project +\until include_directories + +The CMake code above sets up a basic project (called CppMicroServicesExamples) and tries +to find the CppMicroServices package and subsequently to set the necessary include +directories. Building a shared library might then look like this: + +\dontinclude examples/dictionaryservice/CMakeLists.txt +\until target_link + +The call to `#usFunctionGenerateModuleInit` generates the proper module initialization +code and provides access to the module specific ModuleContext instance. + +Makefile based projects +----------------------- + +The following Makefile is located at examples/makefile/Makefile and demonstrates a minimal +build script: + +\include makefile/Makefile + +The variable `CppMicroServices_ROOT` is an environment variable and must be set to the +CppMicroServices installation directory prior to invoking `make`. The module initialization +code for the `libmodule.so` shared library is generated by using the `#US_INITIALIZE_MODULE` +pre-processor macro at the end of the `module.cpp` source file (any source file compiled +into the module would do): + +\dontinclude makefile/module.cpp +\skip usModuleInitialization +\until US_INITIALIZE_MODULE diff --git a/documentation/snippets/CMakeLists.txt b/documentation/snippets/CMakeLists.txt new file mode 100644 index 0000000000..5540734bb9 --- /dev/null +++ b/documentation/snippets/CMakeLists.txt @@ -0,0 +1,4 @@ + +include_directories(${US_INCLUDE_DIRS}) + +usFunctionCompileSnippets("${CMAKE_CURRENT_SOURCE_DIR}") diff --git a/documentation/snippets/uServices-activator/main.cpp b/documentation/snippets/uServices-activator/main.cpp new file mode 100644 index 0000000000..c4ba6c25e7 --- /dev/null +++ b/documentation/snippets/uServices-activator/main.cpp @@ -0,0 +1,27 @@ +#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/documentation/snippets/uServices-modulecontext/main.cpp b/documentation/snippets/uServices-modulecontext/main.cpp new file mode 100644 index 0000000000..a793f3b343 --- /dev/null +++ b/documentation/snippets/uServices-modulecontext/main.cpp @@ -0,0 +1,28 @@ +#include + +//! [GetModuleContext] +#include +#include +#include + +US_USE_NAMESPACE + +void RetrieveModuleContext() +{ + ModuleContext* context = GetModuleContext(); + Module* module = context->GetModule(); + std::cout << "Module name: " << module->GetName() << " [id: " << module->GetModuleId() << "]\n"; +} +//! [GetModuleContext] + +//! [InitializeModule] +#include + +US_INITIALIZE_MODULE("My Module", "mylibname") +//! [InitializeModule] + +int main(int /*argc*/, char* /*argv*/[]) +{ + RetrieveModuleContext(); + return 0; +} diff --git a/documentation/snippets/uServices-registration/main.cpp b/documentation/snippets/uServices-registration/main.cpp new file mode 100644 index 0000000000..be9666e635 --- /dev/null +++ b/documentation/snippets/uServices-registration/main.cpp @@ -0,0 +1,119 @@ +#include +#include +#include +#include + +US_USE_NAMESPACE + + +struct InterfaceA { virtual ~InterfaceA() {} }; +struct InterfaceB { virtual ~InterfaceB() {} }; +struct InterfaceC { virtual ~InterfaceC() {} }; + +US_DECLARE_SERVICE_INTERFACE(InterfaceA, "org.cppmicroservices.snippet.InterfaceA") +US_DECLARE_SERVICE_INTERFACE(InterfaceB, "org.cppmicroservices.snippet.InterfaceB") +US_DECLARE_SERVICE_INTERFACE(InterfaceC, "org.cppmicroservices.snippet.InterfaceC") + +//! [1-1] +class MyService : public InterfaceA +{}; +//! [1-1] + +//! [2-1] +class MyService2 : public InterfaceA, public InterfaceB +{}; +//! [2-1] + +class MyActivator : public ModuleActivator +{ + +public: + + void Load(ModuleContext* context) + { + Register1(context); + Register2(context); + RegisterFactory1(context); + RegisterFactory2(context); + } + + void Register1(ModuleContext* context) + { +//! [1-2] +MyService* myService = new MyService; +context->RegisterService(myService); +//! [1-2] + } + + void Register2(ModuleContext* context) + { +//! [2-2] +MyService2* myService = new MyService2; +context->RegisterService(myService); +//! [2-2] + } + + void RegisterFactory1(ModuleContext* context) + { +//! [f1] +class MyServiceFactory : public ServiceFactory +{ + virtual InterfaceMap GetService(Module* /*module*/, const ServiceRegistrationBase& /*registration*/) + { + MyService* myService = new MyService; + return MakeInterfaceMap(myService); + } + + virtual void UngetService(Module* /*module*/, const ServiceRegistrationBase& /*registration*/, + const InterfaceMap& service) + { + delete ExtractInterface(service); + } +}; + +MyServiceFactory* myServiceFactory = new MyServiceFactory; +context->RegisterService(myServiceFactory); +//! [f1] + } + + void RegisterFactory2(ModuleContext* context) + { +//! [f2] +class MyServiceFactory : public ServiceFactory +{ + virtual InterfaceMap GetService(Module* /*module*/, const ServiceRegistrationBase& /*registration*/) + { + MyService2* myService = new MyService2; + return MakeInterfaceMap(myService); + } + + virtual void UngetService(Module* /*module*/, const ServiceRegistrationBase& /*registration*/, + const InterfaceMap& service) + { + delete ExtractInterface(service); + } +}; + +MyServiceFactory* myServiceFactory = new MyServiceFactory; +context->RegisterService(static_cast(myServiceFactory)); +//! [f2] +// In the RegisterService call above, we could remove the static_cast because local types +// are not considered in template argument type deduction and hence the compiler choose +// the correct RegisterService(ServiceFactory*) overload. However, local types are +// usually the exception and using a non-local type for the service factory would make the +// compiler choose RegisterService(Impl*) instead, unless we use the static_cast. + } + + + void Unload(ModuleContext* /*context*/) + { /* cleanup */ } + +}; + +US_EXPORT_MODULE_ACTIVATOR(mylibname, MyActivator) + +int main(int /*argc*/, char* /*argv*/[]) +{ + MyActivator ma; + return 0; +} diff --git a/documentation/snippets/uServices-resources/main.cpp b/documentation/snippets/uServices-resources/main.cpp new file mode 100644 index 0000000000..474c344374 --- /dev/null +++ b/documentation/snippets/uServices-resources/main.cpp @@ -0,0 +1,86 @@ +#include +#include +#include +#include +#include +#include + +US_USE_NAMESPACE + +void resourceExample() +{ + //! [1] + // Get this module's Module object + Module* module = GetModuleContext()->GetModule(); + + ModuleResource resource = module->GetResource("config.properties"); + if (resource.IsValid()) + { + // Create a ModuleResourceStream object + ModuleResourceStream resourceStream(resource); + + // Read the contents line by line + std::string line; + while (std::getline(resourceStream, line)) + { + // Process the content + std::cout << line << std::endl; + } + } + else + { + // Error handling + } + //! [1] +} + +void parseComponentDefinition(std::istream&) +{ +} + +void extenderPattern() +{ + //! [2] + // Get all loaded modules + std::vector modules; + ModuleRegistry::GetLoadedModules(modules); + + // Check if a module defines a "service-component" property + // and use its value to retrieve an embedded resource containing + // a component description. + for(std::size_t i = 0; i < modules.size(); ++i) + { + Module* const module = modules[i]; + std::string componentPath = module->GetProperty("service-component").ToString(); + if (!componentPath.empty()) + { + ModuleResource componentResource = module->GetResource(componentPath); + if (!componentResource.IsValid() || componentResource.IsDir()) continue; + + // Create a std::istream compatible object and parse the + // component description. + ModuleResourceStream resStream(componentResource); + parseComponentDefinition(resStream); + } + } + //! [2] +} + +int main(int /*argc*/, char* /*argv*/[]) +{ + //! [0] + ModuleContext* moduleContext = GetModuleContext(); + Module* module = moduleContext->GetModule(); + + // List all XML files in the config directory + std::vector xmlFiles = module->FindResources("config", "*.xml", false); + + // Find the resource named vertex_shader.txt starting at the root directory + std::vector shaders = module->FindResources("", "vertex_shader.txt", true); + //! [0] + + return 0; +} + +#include +US_INITIALIZE_EXECUTABLE("uServices-snippet-resources") diff --git a/documentation/snippets/uServices-servicetracker/main.cpp b/documentation/snippets/uServices-servicetracker/main.cpp new file mode 100644 index 0000000000..0c1bc68bef --- /dev/null +++ b/documentation/snippets/uServices-servicetracker/main.cpp @@ -0,0 +1,110 @@ +#include +#include + +US_USE_NAMESPACE + +struct IFooService {}; + +US_DECLARE_SERVICE_INTERFACE(IFooService, "org.cppmicroservices.snippets.IFooService") + +///! [tt] +struct MyTrackedClass { /* ... */ }; +//! [tt] + +//! [ttt] +struct MyTrackedClassTraits : public TrackedTypeTraitsBase +{ + static bool IsValid(const TrackedType&) + { + // Dummy implementation + return true; + } + + static void Dispose(TrackedType&) + {} + + static TrackedType DefaultValue() + { + return TrackedType(); + } +}; +//! [ttt] + +//! [customizer] +struct MyTrackingCustomizer : public ServiceTrackerCustomizer +{ + virtual MyTrackedClass AddingService(const ServiceReferenceT&) + { + return MyTrackedClass(); + } + + virtual void ModifiedService(const ServiceReferenceT&, MyTrackedClass) + { + } + + virtual void RemovedService(const ServiceReferenceT&, MyTrackedClass) + { + } +}; +//! [customizer] + +struct MyTrackingPointerCustomizer : public ServiceTrackerCustomizer +{ + virtual MyTrackedClass* AddingService(const ServiceReferenceT&) + { + return new MyTrackedClass(); + } + + virtual void ModifiedService(const ServiceReferenceT&, MyTrackedClass*) + { + } + + virtual void RemovedService(const ServiceReferenceT&, MyTrackedClass*) + { + } +}; + +// For compilation test purposes only +struct MyTrackingCustomizerVoid : public ServiceTrackerCustomizer +{ + virtual MyTrackedClass AddingService(const ServiceReferenceT&) + { + return MyTrackedClass(); + } + + virtual void ModifiedService(const ServiceReferenceT&, MyTrackedClass) + { + } + + virtual void RemovedService(const ServiceReferenceT&, MyTrackedClass) + { + } +}; + +int main(int /*argc*/, char* /*argv*/[]) +{ + { +//! [tracker] +MyTrackingCustomizer myCustomizer; +ServiceTracker tracker(GetModuleContext(), &myCustomizer); +//! [tracker] + } + + { +//! [tracker2] +MyTrackingPointerCustomizer myCustomizer; +ServiceTracker > tracker(GetModuleContext(), &myCustomizer); +//! [tracker2] + } + + // For compilation test purposes only + MyTrackingCustomizerVoid myCustomizer2; + ServiceTracker tracker2(GetModuleContext(), &myCustomizer2); + ServiceTracker > tracker3(GetModuleContext()); + + return 0; +} + +#include + +US_INITIALIZE_EXECUTABLE("uServices-modulecontext") diff --git a/documentation/snippets/uServices-singleton/SingletonOne.cpp b/documentation/snippets/uServices-singleton/SingletonOne.cpp new file mode 100644 index 0000000000..9380cb316d --- /dev/null +++ b/documentation/snippets/uServices-singleton/SingletonOne.cpp @@ -0,0 +1,80 @@ +#include "SingletonOne.h" + +#include "SingletonTwo.h" + +#include +#include + +#include +#include + +US_USE_NAMESPACE + +//![s1] +SingletonOne& SingletonOne::GetInstance() +{ + static SingletonOne instance; + return instance; +} +//![s1] + +SingletonOne::SingletonOne() : a(1) +{ +} + +//![s1d] +SingletonOne::~SingletonOne() +{ + std::cout << "SingletonTwo::b = " << SingletonTwo::GetInstance().b << std::endl; +} +//![s1d] + +//![ss1gi] +SingletonOneService* SingletonOneService::GetInstance() +{ + static ServiceReference serviceRef; + static ModuleContext* context = GetModuleContext(); + + if (!serviceRef) + { + // This is either the first time GetInstance() was called, + // or a SingletonOneService instance has not yet been registered. + serviceRef = context->GetServiceReference(); + } + + if (serviceRef) + { + // We have a valid service reference. It always points to the service + // with the lowest id (usually the one which was registered first). + // This still might return a null pointer, if all SingletonOneService + // instances have been unregistered (during unloading of the library, + // for example). + return context->GetService(serviceRef); + } + else + { + // No SingletonOneService instance was registered yet. + return 0; + } +} +//![ss1gi] + +SingletonOneService::SingletonOneService() + : a(1) +{ + SingletonTwoService* singletonTwoService = SingletonTwoService::GetInstance(); + assert(singletonTwoService != 0); + std::cout << "SingletonTwoService::b = " << singletonTwoService->b << std::endl; +} + +//![ss1d] +SingletonOneService::~SingletonOneService() +{ + SingletonTwoService* singletonTwoService = SingletonTwoService::GetInstance(); + + // The module activator must ensure that a SingletonTwoService instance is + // available during destruction of a SingletonOneService instance. + assert(singletonTwoService != 0); + std::cout << "SingletonTwoService::b = " << singletonTwoService->b << std::endl; +} +//![ss1d] diff --git a/documentation/snippets/uServices-singleton/SingletonOne.h b/documentation/snippets/uServices-singleton/SingletonOne.h new file mode 100644 index 0000000000..62dbf89270 --- /dev/null +++ b/documentation/snippets/uServices-singleton/SingletonOne.h @@ -0,0 +1,64 @@ +#ifndef SINGLETONONE_H +#define SINGLETONONE_H + +#include +#include +#include +#include + + +//![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: + + // 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/documentation/snippets/uServices-singleton/SingletonTwo.cpp b/documentation/snippets/uServices-singleton/SingletonTwo.cpp new file mode 100644 index 0000000000..db18f6ae01 --- /dev/null +++ b/documentation/snippets/uServices-singleton/SingletonTwo.cpp @@ -0,0 +1,64 @@ +#include "SingletonTwo.h" + +#include "SingletonOne.h" +#include + +#include +#include + +US_USE_NAMESPACE + +SingletonTwo& SingletonTwo::GetInstance() +{ + static SingletonTwo instance; + return instance; +} + +SingletonTwo::SingletonTwo() : b(2) +{ + std::cout << "Constructing SingletonTwo" << std::endl; +} + +SingletonTwo::~SingletonTwo() +{ + std::cout << "Deleting SingletonTwo" << std::endl; + std::cout << "SingletonOne::a = " << SingletonOne::GetInstance().a << std::endl; +} + +SingletonTwoService* SingletonTwoService::GetInstance() +{ + static ServiceReference serviceRef; + static ModuleContext* context = GetModuleContext(); + + if (!serviceRef) + { + // This is either the first time GetInstance() was called, + // or a SingletonTwoService instance has not yet been registered. + serviceRef = context->GetServiceReference(); + } + + if (serviceRef) + { + // We have a valid service reference. It always points to the service + // with the lowest id (usually the one which was registered first). + // This still might return a null pointer, if all SingletonTwoService + // instances have been unregistered (during unloading of the library, + // for example). + return context->GetService(serviceRef); + } + else + { + // No SingletonTwoService instance was registered yet. + return 0; + } +} + +SingletonTwoService::SingletonTwoService() : b(2) +{ + std::cout << "Constructing SingletonTwoService" << std::endl; +} + +SingletonTwoService::~SingletonTwoService() +{ + std::cout << "Deleting SingletonTwoService" << std::endl; +} diff --git a/documentation/snippets/uServices-singleton/SingletonTwo.h b/documentation/snippets/uServices-singleton/SingletonTwo.h new file mode 100644 index 0000000000..9eb8e2b36b --- /dev/null +++ b/documentation/snippets/uServices-singleton/SingletonTwo.h @@ -0,0 +1,48 @@ +#ifndef SINGLETONTWO_H +#define SINGLETONTWO_H + +#include +#include + + +class SingletonTwo +{ +public: + + static SingletonTwo& GetInstance(); + + int b; + +private: + + SingletonTwo(); + ~SingletonTwo(); + + // Disable copy constructor and assignment operator. + SingletonTwo(const SingletonTwo&); + SingletonTwo& operator=(const SingletonTwo&); +}; + +class SingletonTwoService +{ +public: + + static SingletonTwoService* GetInstance(); + + int b; + +private: + + friend class MyActivator; + + SingletonTwoService(); + ~SingletonTwoService(); + + // Disable copy constructor and assignment operator. + SingletonTwoService(const SingletonTwoService&); + SingletonTwoService& operator=(const SingletonTwoService&); +}; + +US_DECLARE_SERVICE_INTERFACE(SingletonTwoService, "org.cppmicroservices.snippet.SingletonTwoService") + +#endif // SINGLETONTWO_H diff --git a/documentation/snippets/uServices-singleton/files.cmake b/documentation/snippets/uServices-singleton/files.cmake new file mode 100644 index 0000000000..7de7f5c5ad --- /dev/null +++ b/documentation/snippets/uServices-singleton/files.cmake @@ -0,0 +1,10 @@ + +set(snippet_src_files + main.cpp + SingletonOne.cpp + SingletonTwo.cpp +) + +usFunctionGenerateExecutableInit(snippet_src_files + IDENTIFIER "uServices_singleton" + ) diff --git a/documentation/snippets/uServices-singleton/main.cpp b/documentation/snippets/uServices-singleton/main.cpp new file mode 100644 index 0000000000..9980ee1f53 --- /dev/null +++ b/documentation/snippets/uServices-singleton/main.cpp @@ -0,0 +1,69 @@ +#include +#include +#include + +#include "SingletonOne.h" +#include "SingletonTwo.h" + +US_USE_NAMESPACE + +class MyActivator : public ModuleActivator +{ + +public: + + //![0] + void Load(ModuleContext* context) + { + // The Load() method of the module activator is called during static + // initialization time of the shared library. + + // First create and register a SingletonTwoService instance. + m_SingletonTwo = new SingletonTwoService; + m_SingletonTwoReg = context->RegisterService(m_SingletonTwo); + + // Now the SingletonOneService constructor will get a valid + // SingletonTwoService instance. + m_SingletonOne = new SingletonOneService; + m_SingletonOneReg = context->RegisterService(m_SingletonOne); + } + //![0] + + //![1] + void Unload(ModuleContext* /*context*/) + { + // Services are automatically unregistered during unloading of + // the shared library after the call to Unload(ModuleContext*) + // has returned. + + // Since SingletonOneService needs a non-null SingletonTwoService + // instance in its destructor, we explicitly unregister and delete the + // SingletonOneService instance here. This way, the SingletonOneService + // destructor will still get a valid SingletonTwoService instance. + m_SingletonOneReg.Unregister(); + delete m_SingletonOne; + + // For singletonTwoService, we could rely on the automatic unregistering + // by the service registry and on automatic deletion if you used + // smart pointer reference counting. You must not delete service instances + // in this method without unregistering them first. + m_SingletonTwoReg.Unregister(); + delete m_SingletonTwo; + } + //![1] + +private: + + SingletonOneService* m_SingletonOne; + SingletonTwoService* m_SingletonTwo; + + ServiceRegistration m_SingletonOneReg; + ServiceRegistration m_SingletonTwoReg; + +}; + +US_EXPORT_MODULE_ACTIVATOR(uServices_singleton, MyActivator) + +int main() +{ +} diff --git a/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp b/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp new file mode 100644 index 0000000000..2984c93702 --- /dev/null +++ b/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp @@ -0,0 +1,39 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include + +US_USE_NAMESPACE + +struct MyStaticModuleActivator : public ModuleActivator +{ + void Load(ModuleContext* /*context*/) + { + std::cout << "Hello from a static module." << std::endl; + } + + void Unload(ModuleContext* /*context*/) {} +}; + +US_EXPORT_MODULE_ACTIVATOR(MyStaticModule, MyStaticModuleActivator) + +US_INITIALIZE_MODULE("My Static Module", "MyStaticModule") diff --git a/documentation/snippets/uServices-staticmodules/files.cmake b/documentation/snippets/uServices-staticmodules/files.cmake new file mode 100644 index 0000000000..2bf4c05a4b --- /dev/null +++ b/documentation/snippets/uServices-staticmodules/files.cmake @@ -0,0 +1,11 @@ +set(snippet_src_files + main.cpp +) + +set(base_dir uServices-staticmodules) +add_library(MyStaticModule STATIC ${base_dir}/MyStaticModule.cpp) +set_property(TARGET MyStaticModule APPEND PROPERTY COMPILE_DEFINITIONS US_STATIC_MODULE) + +set(snippet_link_libraries + MyStaticModule +) diff --git a/documentation/snippets/uServices-staticmodules/main.cpp b/documentation/snippets/uServices-staticmodules/main.cpp new file mode 100644 index 0000000000..e78d3a64c4 --- /dev/null +++ b/documentation/snippets/uServices-staticmodules/main.cpp @@ -0,0 +1,34 @@ +#include + +US_USE_NAMESPACE + +//! [ImportStaticModuleIntoLib] +#include + +US_IMPORT_MODULE(MyStaticModule) +US_LOAD_IMPORTED_MODULES(HostingModule, MyStaticModule) +//! [ImportStaticModuleIntoLib] + +// This is just for illustration purposes in code snippets +extern "C" ModuleActivator* _us_module_activator_instance_MyStaticModule1() { return NULL; } +extern "C" ModuleActivator* _us_module_activator_instance_MyStaticModule2() { return NULL; } +extern "C" ModuleActivator* _us_init_resources_MyStaticModule2() { return NULL; } + +//! [ImportStaticModuleIntoMain] +#include + +US_IMPORT_MODULE(MyStaticModule1) +US_IMPORT_MODULE(MyStaticModule2) +US_IMPORT_MODULE_RESOURCES(MyStaticModule2) +US_LOAD_IMPORTED_MODULES_INTO_MAIN(MyStaticModule1 MyStaticModule2) +//! [ImportStaticModuleIntoMain] + +int main(int /*argc*/, char* /*argv*/[]) +{ + return 0; +} + +//! [InitializeExecutable] +#include +US_INITIALIZE_EXECUTABLE("MyExecutable") +//! [InitializeExecutable] diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt new file mode 100644 index 0000000000..745bd869c3 --- /dev/null +++ b/examples/CMakeLists.txt @@ -0,0 +1,137 @@ +project(CppMicroServicesExamples) + +cmake_minimum_required(VERSION 2.8) + +find_package(CppMicroServices NO_MODULE REQUIRED) + +include_directories(${CppMicroServices_INCLUDE_DIRS}) + +#----------------------------------------------------------------------------- +# Set C/CXX flags +#----------------------------------------------------------------------------- + +if(${CMAKE_PROJECT_NAME} STREQUAL ${PROJECT_NAME}) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CppMicroServices_CXX_FLAGS}") + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${CppMicroServices_CXX_FLAGS_RELEASE}") + set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${CppMicroServices_CXX_FLAGS_DEBUG}") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CppMicroServices_C_FLAGS}") + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} ${CppMicroServices_C_FLAGS_RELEASE}") + set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${CppMicroServices_C_FLAGS_DEBUG}") +endif() + +#----------------------------------------------------------------------------- +# Init output directories +#----------------------------------------------------------------------------- + +set(CppMicroServicesExamples_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") +set(CppMicroServicesExamples_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") +set(CppMicroServicesExamples_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") + +foreach(_type ARCHIVE LIBRARY RUNTIME) + if(NOT CMAKE_${_type}_OUTPUT_DIRECTORY) + set(CMAKE_${_type}_OUTPUT_DIRECTORY ${CppMicroServicesExamples_${_type}_OUTPUT_DIRECTORY}) + endif() +endforeach() + + +function(CreateExample _name) + add_library(Example-${_name} SHARED ${ARGN}) + if(${_name}_DEPENDS) + foreach(_dep ${${_name}_DEPENDS}) + include_directories(${CppMicroServicesExamples_SOURCE_DIR}/${_dep}) + target_link_libraries(Example-${_name} Example-${_dep}) + endforeach() + endif() + target_link_libraries(Example-${_name} ${CppMicroServices_LIBRARIES}) + set_target_properties(Example-${_name} PROPERTIES + LABELS Examples + OUTPUT_NAME ${_name} + ) +endfunction() + +add_subdirectory(eventlistener) +add_subdirectory(dictionaryservice) +add_subdirectory(frenchdictionary) +add_subdirectory(dictionaryclient) +add_subdirectory(dictionaryclient2) +add_subdirectory(dictionaryclient3) +add_subdirectory(spellcheckservice) +add_subdirectory(spellcheckclient) +add_subdirectory(driver) + +#----------------------------------------------------------------------------- +# Test if examples compile against an install tree and if the +# Makefile example compiles +#----------------------------------------------------------------------------- + +if(US_BUILD_TESTING) + enable_testing() + + set(_example_tests ) + + set(_install_dir "${CppMicroServices_BINARY_DIR}/install_test/${CMAKE_INSTALL_PREFIX}") + + add_test(NAME usInstallCleanTest + COMMAND ${CMAKE_COMMAND} -E remove_directory "${_install_dir}") + + add_test(NAME usInstallTest + WORKING_DIRECTORY ${CppMicroServices_BINARY_DIR} + COMMAND ${CMAKE_COMMAND} --build ${CppMicroServices_BINARY_DIR} --target install) + set_tests_properties(usInstallTest PROPERTIES + ENVIRONMENT "DESTDIR=${CppMicroServices_BINARY_DIR}/install_test" + DEPENDS usInstallCleanTest) + + set(_examples_binary_dir "${CppMicroServices_BINARY_DIR}/examples_build") + + add_test(NAME usExamplesCleanTest + COMMAND ${CMAKE_COMMAND} -E remove_directory "${_examples_binary_dir}") + + add_test(NAME usExamplesCreateDirTest + COMMAND ${CMAKE_COMMAND} -E make_directory "${_examples_binary_dir}") + set_tests_properties(usExamplesCreateDirTest PROPERTIES + DEPENDS usExamplesCleanTest) + + add_test(NAME usExamplesConfigureTest + WORKING_DIRECTORY ${_examples_binary_dir} + COMMAND ${CMAKE_COMMAND} + -G ${CMAKE_GENERATOR} + -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} + "-DCppMicroServices_DIR:PATH=${_install_dir}/${CONFIG_CMAKE_DIR}" + "${CMAKE_CURRENT_LIST_DIR}") + set_tests_properties(usExamplesConfigureTest PROPERTIES + DEPENDS "usInstallTest;usExamplesCreateDirTest") + + add_test(NAME usExamplesBuildTest + WORKING_DIRECTORY ${_examples_binary_dir} + COMMAND ${CMAKE_COMMAND} --build .) + set_tests_properties(usExamplesBuildTest PROPERTIES + DEPENDS usExamplesConfigureTest) + + list(APPEND _example_tests usInstallCleanTest usInstallTest usExamplesCleanTest + usExamplesCreateDirTest usExamplesConfigureTest usExamplesBuildTest) + + # The makefile is Linux specific, so only try to build the Makefile example + # if we are on a proper system + if(UNIX AND NOT APPLE) + find_program(MAKE_COMMAND NAMES make gmake) + find_program(CXX_COMMAND NAMES g++) + mark_as_advanced(MAKE_COMMAND CXX_COMMAND) + if(MAKE_COMMAND AND CXX_COMMAND) + add_test(NAME usMakefileExampleCleanTest + WORKING_DIRECTORY ${CppMicroServices_SOURCE_DIR}/examples/makefile + COMMAND ${MAKE_COMMAND} clean) + add_test(NAME usMakefileExampleTest + WORKING_DIRECTORY ${CppMicroServices_SOURCE_DIR}/examples/makefile + COMMAND ${MAKE_COMMAND}) + set_tests_properties(usMakefileExampleTest PROPERTIES + DEPENDS "usMakefileExampleCleanTest;usInstallTest" + ENVIRONMENT "CppMicroServices_ROOT=${CppMicroServices_BINARY_DIR}/install_test${CMAKE_INSTALL_PREFIX};CppMicroServices_CXX_FLAGS=${CppMicroServices_CXX_FLAGS}") + list(APPEND _example_tests usMakefileExampleCleanTest usMakefileExampleTest) + endif() + endif() + + if(US_TEST_LABELS) + set_tests_properties(${_example_tests} PROPERTIES LABELS "${US_TEST_LABELS}") + endif() + +endif() diff --git a/examples/dictionaryclient/Activator.cpp b/examples/dictionaryclient/Activator.cpp new file mode 100644 index 0000000000..fc3d47f37d --- /dev/null +++ b/examples/dictionaryclient/Activator.cpp @@ -0,0 +1,117 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" + +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module activator that uses a dictionary service to check for + * the proper spelling of a word by check for its existence in the dictionary. + * This modules uses the first service that it finds and does not monitor the + * dynamic availability of the service (i.e., it does not listen for the arrival + * or departure of dictionary services). When loading this module, the thread + * calling the Load() method is used to read words from standard input. You can + * stop checking words by entering an empty line, but to start checking words + * again you must unload and then load the module again. + */ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +public: + + /** + * Implements ModuleActivator::Load(). Queries for all available dictionary + * services. If none are found it simply prints a message and returns, + * otherwise it reads words from standard input and checks for their + * existence from the first dictionary that it finds. + * + * \note It is very bad practice to use the calling thread to perform a lengthy + * process like this; this is only done for the purpose of the tutorial. + * + * @param context the module context for this module. + */ + void Load(ModuleContext *context) + { + // Query for all service references matching any language. + std::vector > refs = + context->GetServiceReferences("(Language=*)"); + + if (!refs.empty()) + { + std::cout << "Enter a blank line to exit." << std::endl; + + // Loop endlessly until the user enters a blank line + while (std::cin) + { + // Ask the user to enter a word. + std::cout << "Enter word: "; + + std::string word; + std::getline(std::cin, word); + + // If the user entered a blank line, then + // exit the loop. + if (word.empty()) + { + break; + } + + // First, get a dictionary service and then check + // if the word is correct. + IDictionaryService* dictionary = context->GetService(refs.front()); + if ( dictionary->CheckWord( word ) ) + { + std::cout << "Correct." << std::endl; + } + else + { + std::cout << "Incorrect." << std::endl; + } + + // Unget the dictionary service. + context->UngetService(refs.front()); + } + } + else + { + std::cout << "Couldn't find any dictionary service..." << std::endl; + } + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unget any used services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + // NOTE: The service is automatically released. + } + +}; + +US_EXPORT_MODULE_ACTIVATOR(dictionaryclient, Activator) +//![Activator] diff --git a/examples/dictionaryclient/CMakeLists.txt b/examples/dictionaryclient/CMakeLists.txt new file mode 100644 index 0000000000..bd610a3686 --- /dev/null +++ b/examples/dictionaryclient/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Dictionary Client" + LIBRARY_NAME "dictionaryclient") + +set(dictionaryclient_DEPENDS dictionaryservice) +CreateExample(dictionaryclient ${_srcs}) diff --git a/examples/dictionaryclient2/Activator.cpp b/examples/dictionaryclient2/Activator.cpp new file mode 100644 index 0000000000..28d2e14276 --- /dev/null +++ b/examples/dictionaryclient2/Activator.cpp @@ -0,0 +1,214 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" + +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module activator that uses a dictionary service to check for + * the proper spelling of a word by checking for its existence in the + * dictionary. This module is more complex than the module in Example 3 because + * it monitors the dynamic availability of the dictionary services. In other + * words, if the service it is using departs, then it stops using it gracefully, + * or if it needs a service and one arrives, then it starts using it + * automatically. As before, the module uses the first service that it finds and + * uses the calling thread of the Load() method to read words from standard + * input. You can stop checking words by entering an empty line, but to start + * checking words again you must unload and then load the module again. + */ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +public: + + Activator() + : m_context(NULL) + , m_dictionary(NULL) + {} + + /** + * Implements ModuleActivator::Load(). Adds itself as a listener for service + * events, then queries for available dictionary services. If any + * dictionaries are found it gets a reference to the first one available and + * then starts its "word checking loop". If no dictionaries are found, then + * it just goes directly into its "word checking loop", but it will not be + * able to check any words until a dictionary service arrives; any arriving + * dictionary service will be automatically used by the client if a + * dictionary is not already in use. Once it has dictionary, it reads words + * from standard input and checks for their existence in the dictionary that + * it is using. + * + * \note It is very bad practice to use the calling thread to perform a + * lengthy process like this; this is only done for the purpose of + * the tutorial. + * + * @param context the module context for this module. + */ + void Load(ModuleContext *context) + { + m_context = context; + + { + // Use your favorite thread library to synchronize member + // variable access within this scope while registering + // the service listener and performing our initial + // dictionary service lookup since we + // don't want to receive service events when looking up the + // dictionary service, if one exists. + // MutexLocker lock(&m_mutex); + + // Listen for events pertaining to dictionary services. + m_context->AddServiceListener(this, &Activator::ServiceChanged, + std::string("(&(") + ServiceConstants::OBJECTCLASS() + "=" + + us_service_interface_iid() + ")" + "(Language=*))"); + + // Query for any service references matching any language. + std::vector > refs = + context->GetServiceReferences("(Language=*)"); + + // If we found any dictionary services, then just get + // a reference to the first one so we can use it. + if (!refs.empty()) + { + m_ref = refs.front(); + m_dictionary = m_context->GetService(m_ref); + } + } + + std::cout << "Enter a blank line to exit." << std::endl; + + // Loop endlessly until the user enters a blank line + while (std::cin) + { + // Ask the user to enter a word. + std::cout << "Enter word: "; + + std::string word; + std::getline(std::cin, word); + + // If the user entered a blank line, then + // exit the loop. + if (word.empty()) + { + break; + } + // If there is no dictionary, then say so. + else if (m_dictionary == NULL) + { + std::cout << "No dictionary available." << std::endl; + } + // Otherwise print whether the word is correct or not. + else if (m_dictionary->CheckWord( word )) + { + std::cout << "Correct." << std::endl; + } + else + { + std::cout << "Incorrect." << std::endl; + } + } + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unget any used services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + // NOTE: The service is automatically released. + } + + /** + * Implements ServiceListener.serviceChanged(). Checks to see if the service + * we are using is leaving or tries to get a service if we need one. + * + * @param event the fired service event. + */ + void ServiceChanged(const ServiceEvent event) + { + // Use your favorite thread library to synchronize this + // method with the Load() method. + // MutexLocker lock(&m_mutex); + + // If a dictionary service was registered, see if we + // need one. If so, get a reference to it. + if (event.GetType() == ServiceEvent::REGISTERED) + { + if (!m_ref) + { + // Get a reference to the service object. + m_ref = event.GetServiceReference(); + m_dictionary = m_context->GetService(m_ref); + } + } + // If a dictionary service was unregistered, see if it + // was the one we were using. If so, unget the service + // and try to query to get another one. + else if (event.GetType() == ServiceEvent::UNREGISTERING) + { + if (event.GetServiceReference() == m_ref) + { + // Unget service object and null references. + m_context->UngetService(m_ref); + m_ref = 0; + m_dictionary = NULL; + + // Query to see if we can get another service. + std::vector > refs; + try + { + refs = m_context->GetServiceReferences("(Language=*)"); + } + catch (const std::invalid_argument& e) + { + std::cout << e.what() << std::endl; + } + + if (!refs.empty()) + { + // Get a reference to the first service object. + m_ref = refs.front(); + m_dictionary = m_context->GetService(m_ref); + } + } + } + } + +private: + + // Module context + ModuleContext* m_context; + + // The service reference being used + ServiceReference m_ref; + + // The service object being used + IDictionaryService* m_dictionary; +}; + +US_EXPORT_MODULE_ACTIVATOR(dictionaryclient2, Activator) +//![Activator] diff --git a/examples/dictionaryclient2/CMakeLists.txt b/examples/dictionaryclient2/CMakeLists.txt new file mode 100644 index 0000000000..7e7524a088 --- /dev/null +++ b/examples/dictionaryclient2/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Dictionary Client 2" + LIBRARY_NAME "dictionaryclient2") + +set(dictionaryclient2_DEPENDS dictionaryservice) +CreateExample(dictionaryclient2 ${_srcs}) diff --git a/examples/dictionaryclient3/Activator.cpp b/examples/dictionaryclient3/Activator.cpp new file mode 100644 index 0000000000..a97524435b --- /dev/null +++ b/examples/dictionaryclient3/Activator.cpp @@ -0,0 +1,142 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" + +#include +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module activator that uses a dictionary + * service to check for the proper spelling of a word by + * checking for its existence in the dictionary. This module + * uses a service tracker to dynamically monitor the availability + * of a dictionary service, instead of providing a custom service + * listener as in Example 4. The module uses the service returned + * by the service tracker, which is selected based on a ranking + * algorithm defined by the C++ Micro Services library. + * Again, the calling thread of the Load() method is used to read + * words from standard input, checking its existence in the dictionary. + * You can stop checking words by entering an empty line, but + * to start checking words again you must unload and then load + * the module again. + */ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +public: + + Activator() + : m_context(NULL) + , m_tracker(NULL) + {} + + /** + * Implements ModuleActivator::Load(). Creates a service + * tracker to monitor dictionary services and starts its "word + * checking loop". It will not be able to check any words until + * the service tracker finds a dictionary service; any discovered + * dictionary service will be automatically used by the client. + * It reads words from standard input and checks for their + * existence in the discovered dictionary. + * + * \note It is very bad practice to use the calling thread to perform a + * lengthy process like this; this is only done for the purpose of + * the tutorial. + * + * @param context the module context for this module. + */ + void Load(ModuleContext *context) + { + m_context = context; + + // Create a service tracker to monitor dictionary services. + m_tracker = new ServiceTracker( + m_context, LDAPFilter(std::string("(&(") + ServiceConstants::OBJECTCLASS() + "=" + + us_service_interface_iid() + ")" + + "(Language=*))") + ); + m_tracker->Open(); + + std::cout << "Enter a blank line to exit." << std::endl; + + // Loop endlessly until the user enters a blank line + while (std::cin) + { + // Ask the user to enter a word. + std::cout << "Enter word: "; + + std::string word; + std::getline(std::cin, word); + + // Get the selected dictionary, if available. + IDictionaryService* dictionary = m_tracker->GetService(); + + // If the user entered a blank line, then + // exit the loop. + if (word.empty()) + { + break; + } + // If there is no dictionary, then say so. + else if (dictionary == NULL) + { + std::cout << "No dictionary available." << std::endl; + } + // Otherwise print whether the word is correct or not. + else if (dictionary->CheckWord(word)) + { + std::cout << "Correct." << std::endl; + } + else + { + std::cout << "Incorrect." << std::endl; + } + } + + // This automatically closes the tracker + delete m_tracker; + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unget any used services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + } + +private: + + // Module context + ModuleContext* m_context; + + // The service tracker + ServiceTracker* m_tracker; +}; + +US_EXPORT_MODULE_ACTIVATOR(dictionaryclient3, Activator) +//![Activator] diff --git a/examples/dictionaryclient3/CMakeLists.txt b/examples/dictionaryclient3/CMakeLists.txt new file mode 100644 index 0000000000..44984fbd6e --- /dev/null +++ b/examples/dictionaryclient3/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Dictionary Client 3" + LIBRARY_NAME "dictionaryclient3") + +set(dictionaryclient3_DEPENDS dictionaryservice) +CreateExample(dictionaryclient3 ${_srcs}) diff --git a/examples/dictionaryservice/Activator.cpp b/examples/dictionaryservice/Activator.cpp new file mode 100644 index 0000000000..a7289f7a42 --- /dev/null +++ b/examples/dictionaryservice/Activator.cpp @@ -0,0 +1,116 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" + +#include +#include +#include + +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module activator that uses the module + * context to register an English language dictionary service + * with the C++ Micro Services registry during static initialization + * of the module. The dictionary service interface is + * defined in a separate file and is implemented by a nested class. + */ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +private: + + /** + * A private inner class that implements a dictionary service; + * see IDictionaryService for details of the service. + */ + class DictionaryImpl : public IDictionaryService + { + // The set of words contained in the dictionary. + std::set m_dictionary; + + public: + + DictionaryImpl() + { + m_dictionary.insert("welcome"); + m_dictionary.insert("to"); + m_dictionary.insert("the"); + m_dictionary.insert("micro"); + m_dictionary.insert("services"); + m_dictionary.insert("tutorial"); + } + + /** + * Implements IDictionaryService::CheckWord(). Determines + * if the passed in word is contained in the dictionary. + * @param word the word to be checked. + * @return true if the word is in the dictionary, + * false otherwise. + **/ + bool CheckWord(const std::string& word) + { + 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(dictionaryservice, Activator) +//![Activator] diff --git a/examples/dictionaryservice/CMakeLists.txt b/examples/dictionaryservice/CMakeLists.txt new file mode 100644 index 0000000000..ae21e3b14c --- /dev/null +++ b/examples/dictionaryservice/CMakeLists.txt @@ -0,0 +1,26 @@ +# The library name for the module +set(_lib_name dictionaryservice) + +# A list of source code files +set(_srcs + Activator.cpp + IDictionaryService.cpp +) + +# Generate module initialization code +usFunctionGenerateModuleInit(_srcs + NAME "Dictionary Service" + LIBRARY_NAME ${_lib_name}) + +# Create the library +add_library(Example-${_lib_name} SHARED ${_srcs}) + +# Link the CppMicroServices library +target_link_libraries(Example-${_lib_name} ${CppMicroServices_LIBRARIES}) + +set_target_properties(Example-${_lib_name} PROPERTIES + LABELS Examples + OUTPUT_NAME ${_lib_name} +) + +#CreateExample(dictionaryservice ${_srcs}) diff --git a/examples/dictionaryservice/IDictionaryService.cpp b/examples/dictionaryservice/IDictionaryService.cpp new file mode 100644 index 0000000000..ef0ba43dcb --- /dev/null +++ b/examples/dictionaryservice/IDictionaryService.cpp @@ -0,0 +1,25 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "IDictionaryService.h" + +IDictionaryService::~IDictionaryService() +{} diff --git a/examples/dictionaryservice/IDictionaryService.h b/examples/dictionaryservice/IDictionaryService.h new file mode 100644 index 0000000000..df806d843f --- /dev/null +++ b/examples/dictionaryservice/IDictionaryService.h @@ -0,0 +1,58 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef IDICTIONARYSERVICE_H +#define IDICTIONARYSERVICE_H + +//! [service] +#include + +#include + +#ifdef Example_dictionaryservice_EXPORTS + #define DICTIONAYSERVICE_EXPORT US_ABI_EXPORT +#else + #define DICTIONAYSERVICE_EXPORT US_ABI_IMPORT +#endif + +/** + * A simple service interface that defines a dictionary service. + * A dictionary service simply verifies the existence of a word. + **/ +struct DICTIONAYSERVICE_EXPORT IDictionaryService +{ + // Out-of-line virtual desctructor for proper dynamic cast + // support with older versions of gcc. + virtual ~IDictionaryService(); + + /** + * Check for the existence of a word. + * @param word the word to be checked. + * @return true if the word is in the dictionary, + * false otherwise. + **/ + virtual bool CheckWord(const std::string& word) = 0; +}; + +US_DECLARE_SERVICE_INTERFACE(IDictionaryService, "IDictionaryService/1.0") +//! [service] + +#endif // DICTIONARYSERVICE_H diff --git a/examples/driver/CMakeLists.txt b/examples/driver/CMakeLists.txt new file mode 100644 index 0000000000..f37d796a46 --- /dev/null +++ b/examples/driver/CMakeLists.txt @@ -0,0 +1,16 @@ + +if(WIN32) + string(REPLACE "/" "\\\\" CMAKE_LIBRARY_OUTPUT_DIRECTORY_NATIVE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) + string(REPLACE "/" "\\\\" CMAKE_RUNTIME_OUTPUT_DIRECTORY_NATIVE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +else() + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_NATIVE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_NATIVE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +endif() + +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/usCppMicroServicesExampleDriverConfig.h.in + ${CMAKE_CURRENT_BINARY_DIR}/usCppMicroServicesExampleDriverConfig.h) + +include_directories(${CMAKE_CURRENT_BINARY_DIR}) + +add_executable(CppMicroServicesExampleDriver main.cpp) +target_link_libraries(CppMicroServicesExampleDriver ${CppMicroServices_LIBRARIES}) diff --git a/examples/driver/main.cpp b/examples/driver/main.cpp new file mode 100644 index 0000000000..f4dcfa7649 --- /dev/null +++ b/examples/driver/main.cpp @@ -0,0 +1,300 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include + +#include "usCppMicroServicesExampleDriverConfig.h" + +#if defined(US_PLATFORM_POSIX) + #include +#elif defined(US_PLATFORM_WINDOWS) + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #include +#else + #error Unsupported platform +#endif + +#include +#include +#include +#include +#include +#include +#include + +US_USE_NAMESPACE + +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + +std::map GetExampleModules() +{ + std::map names; + names.insert(std::make_pair("Event Listener", "eventlistener")); + names.insert(std::make_pair("Dictionary Service", "dictionaryservice")); + names.insert(std::make_pair("French Dictionary", "frenchdictionary")); + names.insert(std::make_pair("Dictionary Client", "dictionaryclient")); + names.insert(std::make_pair("Dictionary Client 2", "dictionaryclient2")); + names.insert(std::make_pair("Dictionary Client 3", "dictionaryclient3")); + names.insert(std::make_pair("Spell Check Service", "spellcheckservice")); + names.insert(std::make_pair("Spell Check Client", "spellcheckclient")); + return names; +} + +int main(int /*argc*/, char** /*argv*/) +{ + char cmd[256]; + + std::map availableModules = GetExampleModules(); + + /* module path -> lib handle */ + std::map libraryHandles; + + SharedLibrary sharedLib(LIB_PATH, ""); + + std::cout << "> "; + while(std::cin.getline(cmd, sizeof(cmd))) + { + std::string strCmd(cmd); + if (strCmd == "q") + { + break; + } + else if (strCmd == "h") + { + std::cout << std::left << std::setw(15) << "h" << " This help text\n" + << std::setw(15) << "l " << " Load the module with id or name \n" + << std::setw(15) << "u " << " Unload the module with id \n" + << std::setw(15) << "s" << " Print status information\n" + << std::setw(15) << "q" << " Quit\n" << std::flush; + } + else if (strCmd.find("l ") != std::string::npos) + { + std::string idOrName; + idOrName.assign(strCmd.begin()+2, strCmd.end()); + std::stringstream ss(idOrName); + + long int id = -1; + ss >> id; + if (id > 0) + { + Module* module = ModuleRegistry::GetModule(id); + if (!module) + { + std::cout << "Error: unknown id" << std::endl; + } + else if (module->IsLoaded()) + { + std::cout << "Info: module already loaded" << std::endl; + } + else + { + try + { + std::map::iterator libIter = + libraryHandles.find(module->GetLocation()); + if (libIter != libraryHandles.end()) + { + libIter->second.Load(); + } + else + { + // The module has been loaded previously due to a + // linker dependency + SharedLibrary libHandle(module->GetLocation()); + libHandle.Load(); + libraryHandles.insert(std::make_pair(libHandle.GetFilePath(), libHandle)); + } + } + catch (const std::exception& e) + { + std::cout << e.what() << std::endl; + } + } + } + else + { + Module* module = ModuleRegistry::GetModule(idOrName); + if (!module) + { + try + { + std::map::iterator libIter = + libraryHandles.find(sharedLib.GetFilePath(idOrName)); + if (libIter != libraryHandles.end()) + { + libIter->second.Load(); + } + else + { + bool libFound = false; + for (std::map::const_iterator availableModuleIter = availableModules.begin(); + availableModuleIter != availableModules.end(); ++availableModuleIter) + { + if (availableModuleIter->second == idOrName) + { + libFound = true; + } + } + if (!libFound) + { + std::cout << "Error: unknown example module" << std::endl; + } + else + { + SharedLibrary libHandle(LIB_PATH, idOrName); + libHandle.Load(); + libraryHandles.insert(std::make_pair(libHandle.GetFilePath(), libHandle)); + } + } + + std::vector modules; + ModuleRegistry::GetModules(modules); + for (std::vector::const_iterator moduleIter = modules.begin(); + moduleIter != modules.end(); ++moduleIter) + { + availableModules.erase((*moduleIter)->GetName()); + } + + } + catch (const std::exception& e) + { + std::cout << e.what() << std::endl; + } + } + else if (!module->IsLoaded()) + { + try + { + const std::string modulePath = module->GetLocation(); + std::map::iterator libIter = + libraryHandles.find(modulePath); + if (libIter != libraryHandles.end()) + { + libIter->second.Load(); + } + else + { + SharedLibrary libHandle(LIB_PATH, idOrName); + libHandle.Load(); + libraryHandles.insert(std::make_pair(libHandle.GetFilePath(), libHandle)); + } + } + catch (const std::exception& e) + { + std::cout << e.what() << std::endl; + } + } + else if (module) + { + std::cout << "Info: module already loaded" << std::endl; + } + } + } + else if (strCmd.find("u ") != std::string::npos) + { + std::stringstream ss(strCmd); + ss.ignore(2); + + long int id = -1; + ss >> id; + + if (id == 1) + { + std::cout << "Info: Unloading not possible" << std::endl; + } + else + { + Module* const module = ModuleRegistry::GetModule(id); + if (module) + { + std::map::iterator libIter = + libraryHandles.find(module->GetLocation()); + if (libIter == libraryHandles.end()) + { + std::cout << "Info: Unloading not possible. The module was loaded by a dependent module." << std::endl; + } + else + { + try + { + libIter->second.Unload(); + + // Check if it has really been unloaded + if (module->IsLoaded()) + { + std::cout << "Info: The module is still referenced by another loaded module. It will be unloaded when all dependent modules are unloaded." << std::endl; + } + } + catch (const std::exception& e) + { + std::cout << e.what() << std::endl; + } + } + } + else + { + std::cout << "Error: unknown id" << std::endl; + } + } + } + else if (strCmd == "s") + { + std::vector modules; + ModuleRegistry::GetModules(modules); + + std::cout << std::left; + + std::cout << "Id | " << std::setw(20) << "Name" << " | " << std::setw(9) << "Status" << std::endl; + std::cout << "-----------------------------------\n"; + + for (std::map::const_iterator nameIter = availableModules.begin(); + nameIter != availableModules.end(); ++nameIter) + { + std::cout << " - | " << std::setw(20) << nameIter->second << " | " << std::setw(9) << "-" << std::endl; + } + + for (std::vector::const_iterator moduleIter = modules.begin(); + moduleIter != modules.end(); ++moduleIter) + { + std::cout << std::right << std::setw(2) << (*moduleIter)->GetModuleId() << std::left << " | "; + std::cout << std::setw(20) << (*moduleIter)->GetName() << " | "; + std::cout << std::setw(9) << ((*moduleIter)->IsLoaded() ? "LOADED" : "UNLOADED"); + std::cout << std::endl; + } + } + else + { + std::cout << "Unknown command: " << strCmd << " (type 'h' for help)" << std::endl; + } + std::cout << "> "; + } + + return 0; +} diff --git a/examples/driver/usCppMicroServicesExampleDriverConfig.h.in b/examples/driver/usCppMicroServicesExampleDriverConfig.h.in new file mode 100644 index 0000000000..880a0cfa25 --- /dev/null +++ b/examples/driver/usCppMicroServicesExampleDriverConfig.h.in @@ -0,0 +1,41 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USEXAMPLEDRIVERCONFIG_H +#define USEXAMPLEDRIVERCONFIG_H + +#include "usConfig.h" + +#ifdef US_PLATFORM_POSIX +#define PATH_SEPARATOR "/" +#else +#define PATH_SEPARATOR "\\" +#endif + +#ifdef CMAKE_INTDIR +#define US_LIBRARY_OUTPUT_DIRECTORY "@CMAKE_LIBRARY_OUTPUT_DIRECTORY_NATIVE@" PATH_SEPARATOR CMAKE_INTDIR +#define US_RUNTIME_OUTPUT_DIRECTORY "@CMAKE_RUNTIME_OUTPUT_DIRECTORY_NATIVE@" PATH_SEPARATOR CMAKE_INTDIR +#else +#define US_LIBRARY_OUTPUT_DIRECTORY "@CMAKE_LIBRARY_OUTPUT_DIRECTORY_NATIVE@" +#define US_RUNTIME_OUTPUT_DIRECTORY "@CMAKE_RUNTIME_OUTPUT_DIRECTORY_NATIVE@" +#endif + +#endif // USEXAMPLEDRIVERCONFIG_H diff --git a/examples/eventlistener/Activator.cpp b/examples/eventlistener/Activator.cpp new file mode 100644 index 0000000000..d7b9ae245f --- /dev/null +++ b/examples/eventlistener/Activator.cpp @@ -0,0 +1,90 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a simple module that utilizes the CppMicroServices's + * event mechanism to listen for service events. Upon receiving a service event, + * it prints out the event's details. + */ +class Activator : public ModuleActivator +{ + +private: + + /** + * Implements ModuleActivator::Load(). Prints a message and adds a member + * function to the module context as a service listener. + * + * @param context the framework context for the module. + */ + void Load(ModuleContext* context) + { + std::cout << "Starting to listen for service events." << std::endl; + context->AddServiceListener(this, &Activator::ServiceChanged); + } + + /** + * Implements ModuleActivator::Unload(). Prints a message and removes the + * member function from the module context as a service listener. + * + * @param context the framework context for the module. + */ + void Unload(ModuleContext* context) + { + context->RemoveServiceListener(this, &Activator::ServiceChanged); + std::cout << "Stopped listening for service events." << std::endl; + + // Note: It is not required that we remove the listener here, + // since the framework will do it automatically anyway. + } + + /** + * Prints the details of any service event from the framework. + * + * @param event the fired service event. + */ + void ServiceChanged(const ServiceEvent event) + { + std::string objectClass = ref_any_cast >(event.GetServiceReference().GetProperty(ServiceConstants::OBJECTCLASS())).front(); + + if (event.GetType() == ServiceEvent::REGISTERED) + { + std::cout << "Ex1: Service of type " << objectClass << " registered." << std::endl; + } + else if (event.GetType() == ServiceEvent::UNREGISTERING) + { + std::cout << "Ex1: Service of type " << objectClass << " unregistered." << std::endl; + } + else if (event.GetType() == ServiceEvent::MODIFIED) + { + std::cout << "Ex1: Service of type " << objectClass << " modified." << std::endl; + } + } +}; + +US_EXPORT_MODULE_ACTIVATOR(eventlistener, Activator) +//! [Activator] diff --git a/examples/eventlistener/CMakeLists.txt b/examples/eventlistener/CMakeLists.txt new file mode 100644 index 0000000000..2c6dce49be --- /dev/null +++ b/examples/eventlistener/CMakeLists.txt @@ -0,0 +1,7 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Event Listener" + LIBRARY_NAME "eventlistener") + +CreateExample(eventlistener ${_srcs}) diff --git a/examples/frenchdictionary/Activator.cpp b/examples/frenchdictionary/Activator.cpp new file mode 100644 index 0000000000..cb70512826 --- /dev/null +++ b/examples/frenchdictionary/Activator.cpp @@ -0,0 +1,119 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" + +#include +#include +#include +#include + +#include +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module activator that uses the module + * context to register a French language dictionary service + * with the C++ Micro Services registry during static initialization + * of the module. The dictionary service interface is + * defined in Example 2 (dictionaryservice) and is implemented by a + * nested class. This class is identical to the class in Example 2, + * except that the dictionary contains French words. + */ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +private: + + /** + * A private inner class that implements a dictionary service; + * see DictionaryService for details of the service. + */ + class DictionaryImpl : public IDictionaryService + { + // The set of words contained in the dictionary. + std::set m_dictionary; + + public: + + DictionaryImpl() + { + m_dictionary.insert("bienvenue"); + m_dictionary.insert("au"); + m_dictionary.insert("tutoriel"); + m_dictionary.insert("micro"); + m_dictionary.insert("services"); + } + + /** + * 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("French"); + context->RegisterService(m_dictionaryService.get(), props); + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unregister any registered services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + // NOTE: The service is automatically unregistered + } + +}; + +US_EXPORT_MODULE_ACTIVATOR(frenchdictionary, Activator) +//![Activator] diff --git a/examples/frenchdictionary/CMakeLists.txt b/examples/frenchdictionary/CMakeLists.txt new file mode 100644 index 0000000000..d5c0a649dd --- /dev/null +++ b/examples/frenchdictionary/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "French Dictionary" + LIBRARY_NAME "frenchdictionary") + +set(frenchdictionary_DEPENDS dictionaryservice) +CreateExample(frenchdictionary ${_srcs}) diff --git a/examples/makefile/IDictionaryService.cpp b/examples/makefile/IDictionaryService.cpp new file mode 100644 index 0000000000..47e5097506 --- /dev/null +++ b/examples/makefile/IDictionaryService.cpp @@ -0,0 +1,5 @@ +#include "IDictionaryService.h" + +IDictionaryService::~IDictionaryService() +{ +} diff --git a/examples/makefile/IDictionaryService.h b/examples/makefile/IDictionaryService.h new file mode 100644 index 0000000000..1f003f955d --- /dev/null +++ b/examples/makefile/IDictionaryService.h @@ -0,0 +1,33 @@ +#ifndef IDICTIONARYSERVICE_H +#define IDICTIONARYSERVICE_H + +#include + +#include + +#ifdef MODULE_EXPORTS + #define MODULE_EXPORT US_ABI_EXPORT +#else + #define MODULE_EXPORT US_ABI_IMPORT +#endif + +/** + * A simple service interface that defines a dictionary service. + * A dictionary service simply verifies the existence of a word. + **/ +struct MODULE_EXPORT IDictionaryService +{ + virtual ~IDictionaryService(); + + /** + * Check for the existence of a word. + * @param word the word to be checked. + * @return true if the word is in the dictionary, + * false otherwise. + **/ + virtual bool CheckWord(const std::string& word) = 0; +}; + +US_DECLARE_SERVICE_INTERFACE(IDictionaryService, "IDictionaryService/1.0") + +#endif // DICTIONARYSERVICE_H diff --git a/examples/makefile/Makefile b/examples/makefile/Makefile new file mode 100644 index 0000000000..0e4d21a6d2 --- /dev/null +++ b/examples/makefile/Makefile @@ -0,0 +1,26 @@ +CXX = g++ +CXXFLAGS = -g -Wall -Wno-unused -pedantic -fPIC $(CppMicroServices_CXX_FLAGS) +LDFLAGS = -Wl,-rpath=$(CppMicroServices_ROOT)/lib -Wl,-rpath=. +LDLIBS = -lCppMicroServices + +INCLUDEDIRS = -I$(CppMicroServices_ROOT)/include/CppMicroServices +LIBDIRS = -L$(CppMicroServices_ROOT)/lib/CppMicroServices -L. + +all : main libmodule.so + +main: libmodule.so main.o + $(CXX) -o $@ $^ $(CXXFLAGS) $(LDFLAGS) $(INCLUDEDIRS) $(LIBDIRS) $(LDLIBS) -lmodule + +libmodule.so: module.o IDictionaryService.o + $(CXX) -shared -o $@ $^ $(CXXFLAGS) $(LDFLAGS) $(INCLUDEDIRS) $(LIBDIRS) $(LDLIBS) + +main.o: main.cpp + $(CXX) $(CXXFLAGS) $(INCLUDEDIRS) -c $< -o $@ + +%.o: %.cpp + $(CXX) $(CXXFLAGS) -DMODULE_EXPORTS $(INCLUDEDIRS) -c $< -o $@ + +.PHONY : clean + +clean: + rm -f *.o diff --git a/examples/makefile/main.cpp b/examples/makefile/main.cpp new file mode 100644 index 0000000000..fe66aa18b3 --- /dev/null +++ b/examples/makefile/main.cpp @@ -0,0 +1,25 @@ +#include +#include +#include + +#include "IDictionaryService.h" + +US_USE_NAMESPACE + +int main(int /*argc*/, char* /*argv*/[]) +{ + ServiceReference dictionaryServiceRef = + GetModuleContext()->GetServiceReference(); + if (dictionaryServiceRef) + { + IDictionaryService* dictionaryService = GetModuleContext()->GetService(dictionaryServiceRef); + if (dictionaryService) + { + std::cout << "Dictionary contains 'Tutorial': " << dictionaryService->CheckWord("Tutorial") << std::endl; + } + } +} + +#include + +US_INITIALIZE_EXECUTABLE("main") diff --git a/examples/makefile/module.cpp b/examples/makefile/module.cpp new file mode 100644 index 0000000000..e5260d7720 --- /dev/null +++ b/examples/makefile/module.cpp @@ -0,0 +1,102 @@ +#include +#include +#include +#include + +#include "IDictionaryService.h" + +#include +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module activator that uses the module + * context to register an English language dictionary service + * with the C++ Micro Services registry during static initialization + * of the module. The dictionary service interface is + * defined in a separate file and is implemented by a nested class. + */ +class US_ABI_LOCAL MyActivator : public ModuleActivator +{ + +private: + + /** + * A private inner class that implements a dictionary service; + * see DictionaryService for details of the service. + */ + class DictionaryImpl : public IDictionaryService + { + // The set of words contained in the dictionary. + std::set m_Dictionary; + + public: + + DictionaryImpl() + { + m_Dictionary.insert("welcome"); + m_Dictionary.insert("to"); + m_Dictionary.insert("the"); + m_Dictionary.insert("micro"); + m_Dictionary.insert("services"); + m_Dictionary.insert("tutorial"); + } + + /** + * Implements IDictionaryService::CheckWord(). Determines + * if the passed in word is contained in the dictionary. + * + * @param word the word to be checked. + * @return true if the word is in the dictionary, + * false otherwise. + **/ + bool CheckWord(const std::string& word) + { + 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(module, MyActivator) + +#include + +US_INITIALIZE_MODULE("My Module", "module") diff --git a/examples/spellcheckclient/Activator.cpp b/examples/spellcheckclient/Activator.cpp new file mode 100644 index 0000000000..7014fe46fa --- /dev/null +++ b/examples/spellcheckclient/Activator.cpp @@ -0,0 +1,143 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include "ISpellCheckService.h" + +#include +#include +#include + +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module that uses a spell checker + * service to check the spelling of a passage. This module + * is essentially identical to Example 5, in that it uses the + * Service Tracker to monitor the dynamic availability of the + * spell checker service. When loading this module, the thread + * calling the Load() method is used to read passages from + * standard input. You can stop spell checking passages by + * entering an empty line, but to start spell checking again + * you must un-load and then load the module again. +**/ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +public: + + Activator() + : m_context(NULL) + , m_tracker(NULL) + {} + + /** + * Implements ModuleActivator::Load(). Creates a service + * tracker object to monitor spell checker services. Enters + * a spell check loop where it reads passages from standard + * input and checks their spelling using the spell checker service. + * + * \note It is very bad practice to use the calling thread to perform a + * lengthy process like this; this is only done for the purpose of + * the tutorial. + * + * @param context the module context for this module. + */ + void Load(ModuleContext *context) + { + m_context = context; + + // Create a service tracker to monitor spell check services. + m_tracker = new ServiceTracker(m_context); + m_tracker->Open(); + + std::cout << "Enter a blank line to exit." << std::endl; + + // Loop endlessly until the user enters a blank line + while (std::cin) + { + // Ask the user to enter a passage. + std::cout << "Enter passage: "; + + std::string passage; + std::getline(std::cin, passage); + + // Get the selected spell check service, if available. + ISpellCheckService* checker = m_tracker->GetService(); + + // If the user entered a blank line, then + // exit the loop. + if (passage.empty()) + { + break; + } + // If there is no spell checker, then say so. + else if (checker == NULL) + { + std::cout << "No spell checker available." << std::endl; + } + // Otherwise check passage and print misspelled words. + else + { + std::vector errors = checker->Check(passage); + + if (errors.empty()) + { + std::cout << "Passage is correct." << std::endl; + } + else + { + std::cout << "Incorrect word(s):" << std::endl; + for (std::size_t i = 0; i < errors.size(); ++i) + { + std::cout << " " << errors[i] << std::endl; + } + } + } + } + + // This automatically closes the tracker + delete m_tracker; + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unget any used services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + } + +private: + + // Module context + ModuleContext* m_context; + + // The service tracker + ServiceTracker* m_tracker; +}; + +US_EXPORT_MODULE_ACTIVATOR(spellcheckclient, Activator) +//![Activator] diff --git a/examples/spellcheckclient/CMakeLists.txt b/examples/spellcheckclient/CMakeLists.txt new file mode 100644 index 0000000000..7e28ef4b12 --- /dev/null +++ b/examples/spellcheckclient/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Spell Check Client" + LIBRARY_NAME "spellcheckclient") + +set(spellcheckclient_DEPENDS spellcheckservice) +CreateExample(spellcheckclient ${_srcs}) diff --git a/examples/spellcheckservice/Activator.cpp b/examples/spellcheckservice/Activator.cpp new file mode 100644 index 0000000000..9ad3d882e4 --- /dev/null +++ b/examples/spellcheckservice/Activator.cpp @@ -0,0 +1,225 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" +#include "ISpellCheckService.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module that implements a spell + * checker service. The spell checker service uses all available + * dictionary services to check for the existence of words in + * a given sentence. This module uses a ServiceTracker to + * monitors the dynamic availability of dictionary services, + * and to aggregate all available dictionary services as they + * arrive and depart. The spell checker service is only registered + * if there are dictionary services available, thus the spell + * checker service will appear and disappear as dictionary + * services appear and disappear, respectively. +**/ +class US_ABI_LOCAL Activator : public ModuleActivator, public ServiceTrackerCustomizer +{ + +private: + + /** + * A private inner class that implements a spell check service; see + * ISpellCheckService for details of the service. + */ + class SpellCheckImpl : public ISpellCheckService + { + + private: + + typedef std::map, IDictionaryService*> RefToServiceType; + RefToServiceType m_refToSvcMap; + + public: + + /** + * Implements ISpellCheckService::Check(). Checks the given passage for + * misspelled words. + * + * @param passage the passage to spell check. + * @return A list of misspelled words. + */ + std::vector Check(const std::string& passage) + { + std::vector errorList; + + // No misspelled words for an empty string. + if (passage.empty()) + { + return errorList; + } + + // Tokenize the passage using spaces and punctuation. + const char* delimiters = " ,.!?;:"; + char* passageCopy = new char[passage.size()+1]; + std::memcpy(passageCopy, passage.c_str(), passage.size()+1); + char* pch = std::strtok(passageCopy, delimiters); + + { + // Lock the m_refToSvcMap member using your favorite thread library here... + // MutexLocker lock(&m_refToSvcMapMutex) + + // Loop through each word in the passage. + while (pch) + { + std::string word(pch); + + bool correct = false; + + // Check each available dictionary for the current word. + for (RefToServiceType::const_iterator i = m_refToSvcMap.begin(); + (!correct) && (i != m_refToSvcMap.end()); ++i) + { + IDictionaryService* dictionary = i->second; + + if (dictionary->CheckWord(word)) + { + correct = true; + } + } + + // If the word is not correct, then add it + // to the incorrect word list. + if (!correct) + { + errorList.push_back(word); + } + + pch = std::strtok(NULL, delimiters); + } + } + + delete[] passageCopy; + + return errorList; + } + + int AddDictionary(const ServiceReference& ref, IDictionaryService* dictionary) + { + // Lock the m_refToSvcMap member using your favorite thread library here... + // MutexLocker lock(&m_refToSvcMapMutex) + + m_refToSvcMap.insert(std::make_pair(ref, dictionary)); + + return m_refToSvcMap.size(); + } + + int RemoveDictionary(const ServiceReference& ref) + { + // Lock the m_refToSvcMap member using your favorite thread library here... + // MutexLocker lock(&m_refToSvcMapMutex) + + m_refToSvcMap.erase(ref); + + return m_refToSvcMap.size(); + } + }; + + virtual IDictionaryService* AddingService(const ServiceReference& reference) + { + IDictionaryService* dictionary = m_context->GetService(reference); + int count = m_spellCheckService->AddDictionary(reference, dictionary); + if (!m_spellCheckReg && count > 1) + { + m_spellCheckReg = m_context->RegisterService(m_spellCheckService.get()); + } + return dictionary; + } + + virtual void ModifiedService(const ServiceReference& /*reference*/, + IDictionaryService* /*service*/) + { + // do nothing + } + + virtual void RemovedService(const ServiceReference& reference, + IDictionaryService* /*service*/) + { + if (m_spellCheckService->RemoveDictionary(reference) < 2 && m_spellCheckReg) + { + m_spellCheckReg.Unregister(); + m_spellCheckReg = 0; + } + } + + std::auto_ptr m_spellCheckService; + ServiceRegistration m_spellCheckReg; + + ModuleContext* m_context; + std::auto_ptr > m_tracker; + +public: + + Activator() + : m_context(NULL) + {} + + /** + * Implements ModuleActivator::Load(). Registers an + * instance of a dictionary service using the module context; + * attaches properties to the service that can be queried + * when performing a service look-up. + * + * @param context the context for the module. + */ + void Load(ModuleContext* context) + { + m_context = context; + + m_spellCheckService.reset(new SpellCheckImpl); + m_tracker.reset(new ServiceTracker(context, this)); + m_tracker->Open(); + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unregister any registered services + * and release any used services. + * + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + // NOTE: The service is automatically unregistered + + m_tracker->Close(); + } + +}; + +US_EXPORT_MODULE_ACTIVATOR(spellcheckservice, Activator) +//![Activator] diff --git a/examples/spellcheckservice/CMakeLists.txt b/examples/spellcheckservice/CMakeLists.txt new file mode 100644 index 0000000000..a86d8153a6 --- /dev/null +++ b/examples/spellcheckservice/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp ISpellCheckService.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Spell Check Service" + LIBRARY_NAME "spellcheckservice") + +set(spellcheckservice_DEPENDS dictionaryservice) +CreateExample(spellcheckservice ${_srcs}) diff --git a/examples/spellcheckservice/ISpellCheckService.cpp b/examples/spellcheckservice/ISpellCheckService.cpp new file mode 100644 index 0000000000..4a2d238a38 --- /dev/null +++ b/examples/spellcheckservice/ISpellCheckService.cpp @@ -0,0 +1,25 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "ISpellCheckService.h" + +ISpellCheckService::~ISpellCheckService() +{} diff --git a/examples/spellcheckservice/ISpellCheckService.h b/examples/spellcheckservice/ISpellCheckService.h new file mode 100644 index 0000000000..679235801b --- /dev/null +++ b/examples/spellcheckservice/ISpellCheckService.h @@ -0,0 +1,64 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef ISPELLCHECKSERVICE_H +#define ISPELLCHECKSERVICE_H + +//! [service] +#include + +#include +#include + +#ifdef Example_spellcheckservice_EXPORTS + #define SPELLCHECKSERVICE_EXPORT US_ABI_EXPORT +#else + #define SPELLCHECKSERVICE_EXPORT US_ABI_IMPORT +#endif + +/** + * A simple service interface that defines a spell check service. A spell check + * service checks the spelling of all words in a given passage. A passage is any + * number of words separated by a space character and the following punctuation + * marks: comma, period, exclamation mark, question mark, semi-colon, and colon. + */ +struct SPELLCHECKSERVICE_EXPORT ISpellCheckService +{ + // Out-of-line virtual desctructor for proper dynamic cast + // support with older versions of gcc. + virtual ~ISpellCheckService(); + + /** + * Checks a given passage for spelling errors. A passage is any number of + * words separated by a space and any of the following punctuation marks: + * comma (,), period (.), exclamation mark (!), question mark (?), + * semi-colon (;), and colon(:). + * + * @param passage the passage to spell check. + * @return A list of misspelled words. + */ + virtual std::vector Check(const std::string& passage) = 0; +}; + +US_DECLARE_SERVICE_INTERFACE(ISpellCheckService, "ISpellCheckService/1.0") +//! [service] +//! +#endif // ISPELLCHECKSERVICE_H diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000000..5244cbb638 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,190 @@ +#----------------------------------------------------------------------------- +# US source files +#----------------------------------------------------------------------------- + +set(_srcs + util/usAny.cpp + util/jsoncpp.cpp + util/usSharedLibrary.cpp + util/usThreads.cpp + util/usUncompressResourceData.c + util/usUncompressResourceData.cpp + util/usUtils.cpp + + service/usLDAPExpr.cpp + service/usLDAPFilter.cpp + service/usServiceException.cpp + service/usServiceEvent.cpp + service/usServiceListenerEntry.cpp + service/usServiceListenerEntry_p.h + service/usServiceListeners.cpp + service/usServiceListeners_p.h + service/usServiceObjects.cpp + service/usServiceProperties.cpp + service/usServicePropertiesImpl.cpp + service/usServiceReferenceBase.cpp + service/usServiceReferenceBasePrivate.cpp + service/usServiceRegistrationBase.cpp + service/usServiceRegistrationBasePrivate.cpp + service/usServiceRegistry.cpp + service/usServiceRegistry_p.h + + module/usCoreModuleContext_p.h + module/usCoreModuleContext.cpp + module/usModuleContext.cpp + module/usModule.cpp + module/usModuleEvent.cpp + module/usModuleInfo.cpp + module/usModuleManifest.cpp + module/usModulePrivate.cpp + module/usModuleRegistry.cpp + module/usModuleResource.cpp + module/usModuleResourceBuffer.cpp + module/usModuleResourceStream.cpp + module/usModuleResourceTree.cpp + module/usModuleSettings.cpp + module/usModuleUtils.cpp + module/usModuleVersion.cpp +) + +set(_private_headers + util/usAtomicInt_p.h + util/usFunctor_p.h + util/usStaticInit_p.h + util/usThreads_p.h + util/usUtils_p.h + + util/dirent_win32_p.h + util/stdint_p.h + util/stdint_vc_p.h + + service/usServicePropertiesImpl_p.h + service/usServiceTracker.tpp + service/usServiceTrackerPrivate.h + service/usServiceTrackerPrivate.tpp + service/usTrackedService_p.h + service/usTrackedServiceListener_p.h + service/usTrackedService.tpp + + module/usModuleAbstractTracked_p.h + module/usModuleAbstractTracked.tpp + module/usModuleResourceBuffer_p.h + module/usModuleResourceTree_p.h + module/usModuleUtils_p.h +) + +set(_public_headers + util/usAny.h + util/usSharedData.h + util/usSharedLibrary.h + util/usUncompressResourceData.h + + service/usLDAPFilter.h + service/usPrototypeServiceFactory.h + service/usServiceEvent.h + service/usServiceException.h + service/usServiceFactory.h + service/usServiceInterface.h + service/usServiceObjects.h + service/usServiceProperties.h + service/usServiceReference.h + service/usServiceReferenceBase.h + service/usServiceRegistration.h + service/usServiceRegistrationBase.h + service/usServiceTracker.h + service/usServiceTrackerCustomizer.h + + module/usGetModuleContext.h + module/usModule.h + module/usModuleActivator.h + module/usModuleContext.h + module/usModuleEvent.h + module/usModuleImport.h + module/usModuleInfo.h + module/usModuleInitialization.h + module/usModuleRegistry.h + module/usModuleResource.h + module/usModuleResourceStream.h + module/usModuleSettings.h + module/usModuleVersion.h +) + +if(US_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}) + + usFunctionGenerateModuleInit(_srcs NAME ${PROJECT_NAME}) + usFunctionEmbedResources(_srcs LIBRARY_NAME ${PROJECT_NAME} + ROOT_DIR resources + FILES manifest.json) + + add_library(${PROJECT_NAME} ${_srcs} + ${_public_headers} ${_private_headers} ${us_config_h_file}) + if(US_LINK_FLAGS) + set_target_properties(${PROJECT_NAME} PROPERTIES LINK_FLAGS "${US_LINK_FLAGS}") + endif() + set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY COMPILE_DEFINITIONS US_FORCE_MODULE_INIT) + set_target_properties(${PROJECT_NAME} PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + ) + 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 PRIVATE_HEADER ${_private_headers} ${us_config_h_file}) +else() + set(US_PUBLIC_HEADERS ${US_PUBLIC_HEADERS} PARENT_SCOPE) + set(US_PRIVATE_HEADERS ${US_PRIVATE_HEADERS} PARENT_SCOPE) +endif() + +#----------------------------------------------------------------------------- +# Install support (only if not in embedded mode) +#----------------------------------------------------------------------------- + +if(NOT US_IS_EMBEDDED) + install(TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME}Targets + RUNTIME DESTINATION ${RUNTIME_INSTALL_DIR} COMPONENT sdk + LIBRARY DESTINATION ${LIBRARY_INSTALL_DIR} COMPONENT sdk + ARCHIVE DESTINATION ${ARCHIVE_INSTALL_DIR} COMPONENT sdk + PUBLIC_HEADER DESTINATION ${HEADER_INSTALL_DIR} COMPONENT sdk + PRIVATE_HEADER DESTINATION ${HEADER_INSTALL_DIR} COMPONENT sdk) +endif() diff --git a/src/module/usCoreModuleContext.cpp b/src/module/usCoreModuleContext.cpp new file mode 100644 index 0000000000..b2d4d9896c --- /dev/null +++ b/src/module/usCoreModuleContext.cpp @@ -0,0 +1,46 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#include +#include "usCoreModuleContext_p.h" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4355) +#endif + +US_BEGIN_NAMESPACE + +CoreModuleContext::CoreModuleContext() + : services(this) +{ +} + +CoreModuleContext::~CoreModuleContext() +{ +} + +US_END_NAMESPACE + +#ifdef _MSC_VER +#pragma warning(pop) +#endif diff --git a/src/module/usCoreModuleContext_p.h b/src/module/usCoreModuleContext_p.h new file mode 100644 index 0000000000..7f230f9ee5 --- /dev/null +++ b/src/module/usCoreModuleContext_p.h @@ -0,0 +1,60 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USCOREMODULECONTEXT_H +#define USCOREMODULECONTEXT_H + +#include "usServiceListeners_p.h" +#include "usServiceRegistry_p.h" + +US_BEGIN_NAMESPACE + +/** + * This class is not part of the public API. + */ +class CoreModuleContext +{ +public: + + /** + * All listeners in this framework. + */ + ServiceListeners listeners; + + /** + * All registered services in this framework. + */ + ServiceRegistry services; + + /** + * Contruct a core context + * + */ + CoreModuleContext(); + + ~CoreModuleContext(); + +}; + +US_END_NAMESPACE + +#endif // USCOREMODULECONTEXT_H diff --git a/src/module/usGetModuleContext.h b/src/module/usGetModuleContext.h new file mode 100644 index 0000000000..b6b56971d6 --- /dev/null +++ b/src/module/usGetModuleContext.h @@ -0,0 +1,54 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USGETMODULECONTEXT_H +#define USGETMODULECONTEXT_H + +#include + +US_BEGIN_NAMESPACE + +class ModuleContext; + +/** + * \ingroup MicroServices + * + * \brief Returns the module context of the calling module. + * + * This function allows easy access to the ModuleContext instance from + * inside a C++ Micro Services module. + * + * \return The ModuleContext of the calling module. + * + * \internal + * + * Note that the corresponding function definition is provided for each + * module by the usModuleInit.cpp file. This file is customized via CMake + * configure_file(...) and automatically compiled into each module. + * Consequently, the GetModuleContext function is not exported, since each + * module gets its "own version". + */ +US_ABI_LOCAL ModuleContext* GetModuleContext(); + +US_END_NAMESPACE + +#endif // USGETMODULECONTEXT_H diff --git a/src/module/usModule.cpp b/src/module/usModule.cpp new file mode 100644 index 0000000000..f12b12b6e4 --- /dev/null +++ b/src/module/usModule.cpp @@ -0,0 +1,319 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#include "usModule.h" + +#include "usModuleContext.h" +#include "usModuleActivator.h" +#include "usModulePrivate.h" +#include "usModuleResource.h" +#include "usModuleSettings.h" +#include "usCoreModuleContext_p.h" + + +US_BEGIN_NAMESPACE + +const std::string& Module::PROP_ID() +{ + static const std::string s("module.id"); + return s; +} +const std::string& Module::PROP_NAME() +{ + static const std::string s("module.name"); + return s; +} +const std::string& Module::PROP_LOCATION() +{ + static const std::string s("module.location"); + return s; +} +const std::string& Module::PROP_VERSION() +{ + static const std::string s("module.version"); + return s; +} + +const std::string&Module::PROP_VENDOR() +{ + static const std::string s("module.vendor"); + return s; +} + +const std::string&Module::PROP_DESCRIPTION() +{ + static const std::string s("module.description"); + return s; +} + +const std::string&Module::PROP_AUTOLOAD_DIR() +{ + static const std::string s("module.autoload_dir"); + return s; +} + +Module::Module() +: d(0) +{ + +} + +Module::~Module() +{ + delete d; +} + +void Module::Init(CoreModuleContext* coreCtx, + ModuleInfo* info) +{ + ModulePrivate* mp = new ModulePrivate(this, coreCtx, info); + std::swap(mp, d); + delete mp; +} + +void Module::Uninit() +{ + if (d->moduleContext) + { + delete d->moduleContext; + d->moduleContext = 0; + } + d->moduleActivator = 0; +} + +bool Module::IsLoaded() const +{ + return d->moduleContext != 0; +} + +void Module::Start() +{ + + if (d->moduleContext) + { + US_WARN << "Module " << d->info.name << " already started."; + return; + } + + d->moduleContext = new ModuleContext(this->d); + +// try +// { + d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::LOADING, this)); + // try to get a ModuleActivator instance + if (d->info.activatorHook) + { + try + { + d->moduleActivator = d->info.activatorHook(); + } + catch (...) + { + US_ERROR << "Creating the module activator of " << d->info.name << " failed"; + throw; + } + + d->moduleActivator->Load(d->moduleContext); + } + + d->StartStaticModules(); + +#ifdef US_ENABLE_AUTOLOADING_SUPPORT + if (ModuleSettings::IsAutoLoadingEnabled()) + { + AutoLoadModules(d->info); + } +#endif + + d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::LOADED, this)); +// } +// catch (...) +// { +// d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADING, this)); +// d->RemoveModuleResources(); + +// delete d->moduleContext; +// d->moduleContext = 0; + +// d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADED, this)); +// US_ERROR << "Calling the module activator Load() method of " << d->info.name << " failed!"; +// throw; +// } +} + +void Module::Stop() +{ + if (d->moduleContext == 0) + { + US_WARN << "Module " << d->info.name << " already stopped."; + return; + } + + try + { + d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADING, this)); + + d->StopStaticModules(); + + if (d->moduleActivator) + { + d->moduleActivator->Unload(d->moduleContext); + } + } + catch (...) + { + US_WARN << "Calling the module activator Unload() method of " << d->info.name << " failed!"; + + try + { + d->RemoveModuleResources(); + } + catch (...) {} + + delete d->moduleContext; + d->moduleContext = 0; + + d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADED, this)); + + throw; + } + + d->RemoveModuleResources(); + delete d->moduleContext; + d->moduleContext = 0; + d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADED, this)); +} + +ModuleContext* Module::GetModuleContext() const +{ + return d->moduleContext; +} + +long Module::GetModuleId() const +{ + return d->info.id; +} + +std::string Module::GetLocation() const +{ + return d->info.location; +} + +std::string Module::GetName() const +{ + return d->info.name; +} + +ModuleVersion Module::GetVersion() const +{ + return d->version; +} + +Any Module::GetProperty(const std::string& key) const +{ + return d->moduleManifest.GetValue(key); +} + +std::vector Module::GetPropertyKeys() const +{ + return d->moduleManifest.GetKeys(); +} + +std::vector Module::GetRegisteredServices() const +{ + std::vector sr; + std::vector res; + d->coreCtx->services.GetRegisteredByModule(d, sr); + for (std::vector::const_iterator i = sr.begin(); + i != sr.end(); ++i) + { + res.push_back(i->GetReference()); + } + return res; +} + +std::vector Module::GetServicesInUse() const +{ + std::vector sr; + std::vector res; + d->coreCtx->services.GetUsedByModule(const_cast(this), sr); + for (std::vector::const_iterator i = sr.begin(); + i != sr.end(); ++i) + { + res.push_back(i->GetReference()); + } + return res; +} + +ModuleResource Module::GetResource(const std::string& path) const +{ + if (d->resourceTreePtrs.empty()) + { + return ModuleResource(); + } + + for (std::size_t i = 0; i < d->resourceTreePtrs.size(); ++i) + { + if (!d->resourceTreePtrs[i]->IsValid()) continue; + ModuleResource result(path, d->resourceTreePtrs[i], d->resourceTreePtrs); + if (result) return result; + } + return ModuleResource(); +} + +std::vector Module::FindResources(const std::string& path, const std::string& filePattern, + bool recurse) const +{ + std::vector result; + if (d->resourceTreePtrs.empty()) return result; + + for (std::size_t i = 0; i < d->resourceTreePtrs.size(); ++i) + { + if (!d->resourceTreePtrs[i]->IsValid()) continue; + + std::vector nodes; + d->resourceTreePtrs[i]->FindNodes(path, filePattern, recurse, nodes); + for (std::vector::iterator nodeIter = nodes.begin(); + nodeIter != nodes.end(); ++nodeIter) + { + result.push_back(ModuleResource(*nodeIter, d->resourceTreePtrs[i], d->resourceTreePtrs)); + } + } + return result; +} + +US_END_NAMESPACE + +US_USE_NAMESPACE + +std::ostream& operator<<(std::ostream& os, const Module& module) +{ + os << "Module[" << "id=" << module.GetModuleId() << + ", loc=" << module.GetLocation() << + ", name=" << module.GetName() << "]"; + return os; +} + +std::ostream& operator<<(std::ostream& os, Module const * module) +{ + return operator<<(os, *module); +} diff --git a/src/module/usModule.h b/src/module/usModule.h new file mode 100644 index 0000000000..b92e2239cb --- /dev/null +++ b/src/module/usModule.h @@ -0,0 +1,368 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USMODULE_H +#define USMODULE_H + +#include "usModuleVersion.h" + +#include + +US_BEGIN_NAMESPACE + +class Any; +class CoreModuleContext; +struct ModuleInfo; +class ModuleContext; +class ModuleResource; +class ModulePrivate; + +template +class ServiceReference; + +typedef ServiceReference ServiceReferenceU; + +/** + * \ingroup MicroServices + * + * Represents a CppMicroServices module. + * + *

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

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

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

    + *
  • LOADED + *
  • UNLOADED + *
+ *

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

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

+ * The framework is the only entity that is allowed to create + * %Module objects. + * + * @remarks This class is thread safe. + */ +class US_EXPORT Module +{ + +public: + + /** + * Returns the property key for looking up this module's id. + * The property value is of type \c long. + * + * @return The id property key. + */ + static const std::string& PROP_ID(); + + /** + * Returns the property key for looking up this module's name. + * The property value is of type \c std::string. + * + * @return The name property key. + */ + static const std::string& PROP_NAME(); + + /** + * Returns the property key for looking up this module's + * location the file system. + * The property value is of type \c std::string. + * + * @return The location property key. + */ + static const std::string& PROP_LOCATION(); + + /** + * Returns the property key with a value of \c module.version for looking + * up this module's version identifier. + * The property value is of type \c std::string. + * + * @return The version property key. + */ + static const std::string& PROP_VERSION(); + + /** + * Returns the property key with a value of \c module.vendor for looking + * up this module's vendor information. + * The property value is of type \c std::string. + * + * @return The version property key. + */ + static const std::string& PROP_VENDOR(); + + /** + * Returns the property key with a value of \c module.description for looking + * up this module's description. + * The property value is of type \c std::string. + * + * @return The version property key. + */ + static const std::string& PROP_DESCRIPTION(); + + /** + * Returns the property key with a value of \c module.autoload_dir for looking + * up this module's auto-load directory. + * The property value is of type \c std::string. + * + * @return The version property key. + */ + static const std::string& PROP_AUTOLOAD_DIR(); + + ~Module(); + + /** + * Returns this module's current state. + * + *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ * ModuleContext methods allow a module to: + *

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

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

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

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

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

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

+ * A module can register a service object that implements the + * ServiceFactory or PrototypeServiceFactory interface to have more + * flexibility in providing service objects to other modules. + * + *

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

    + *
  1. The framework adds the following service properties to the service + * properties from the specified ServiceProperties (which may be + * omitted):
    + * A property named ServiceConstants#SERVICE_ID() identifying the + * registration number of the service
    + * A property named ServiceConstants#OBJECTCLASS() containing all the + * specified classes.
    + * A property named ServiceConstants#SERVICE_SCOPE() identifying the scope + * of the service.
    + * Properties with these names in the specified ServiceProperties will + * be ignored. + *
  2. The service is added to the framework service registry and may now be + * used by other modules. + *
  3. A service event of type ServiceEvent#REGISTERED is fired. + *
  4. A ServiceRegistration object for this registration is + * returned. + *
+ * + * @note This is a low-level method and should normally not be used directly. + * Use one of the templated RegisterService methods instead. + * + * @param service The service object, which is a map of interface identifiers + * to raw service pointers. + * @param properties The properties for this service. The keys in the + * properties object must all be std::string objects. See + * {@link ServiceConstants} for a list of standard service property keys. + * Changes should not be made to this object after calling this + * method. To update the service's properties the + * {@link ServiceRegistration::SetProperties} method must be called. + * The set of properties may be omitted if the service has + * no properties. + * @return A ServiceRegistration object for use by the module + * registering the service to update the service's properties or to + * unregister the service. + * + * @throws std::invalid_argument If one of the following is true: + *
    + *
  • service is 0. + *
  • properties contains case variants of the same key name. + *
+ * @throws std::logic_error If this ModuleContext is no longer valid. + * + * @see ServiceRegistration + * @see ServiceFactory + * @see PrototypeServiceFactory + */ + ServiceRegistrationU RegisterService(const InterfaceMap& 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 InterfaceMap&, const ServiceProperties&) but should be preferred + * since it avoids errors in the string literal identifying the class name or interface identifier. + * + * Example usage: + * \snippet uServices-registration/main.cpp 1-1 + * \snippet uServices-registration/main.cpp 1-2 + * + * @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. + * @throws ServiceException If the service type \c S is invalid or the + * \c service object is NULL. + * + * @see RegisterService(const InterfaceMap&, const ServiceProperties&) + */ + template + ServiceRegistration RegisterService(S* service, const ServiceProperties& properties = ServiceProperties()) + { + InterfaceMap servicePointers = MakeInterfaceMap(service); + return RegisterService(servicePointers, properties); + } + + /** + * Registers the specified service object with the specified properties + * using the specified template argument with the framework. + * + *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ * Version identifiers have four components. + *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ * This implementation returns the result of calling + * this->ToString() == other.ToString(). + * + * @param other The object to compare against this LDAPFilter. + * @return Returns the result of calling + * this->ToString() == other.ToString(). + */ + bool operator==(const LDAPFilter& other) const; + + LDAPFilter& operator=(const LDAPFilter& filter); + +protected: + + SharedDataPointer d; + +}; + +US_END_NAMESPACE + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +/** + * \ingroup MicroServices + */ +US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(LDAPFilter)& filter); + +#endif // USLDAPFILTER_H diff --git a/src/service/usPrototypeServiceFactory.h b/src/service/usPrototypeServiceFactory.h new file mode 100644 index 0000000000..080f1fe286 --- /dev/null +++ b/src/service/usPrototypeServiceFactory.h @@ -0,0 +1,102 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USPROTOTYPESERVICEFACTORY_H +#define USPROTOTYPESERVICEFACTORY_H + +#include + +US_BEGIN_NAMESPACE + +/** + * @ingroup MicroServices + * + * A factory for \link ServiceConstants::SCOPE_PROTOTYPE prototype scope\endlink services. + * The factory can provide multiple, unique service objects. + * + * When registering a service, a PrototypeServiceFactory object can be used + * instead of a service object, so that the module developer can create a + * unique service object for each caller that is using the service. + * When a caller uses a ServiceObjects to request a service instance, the + * framework calls the GetService method to return a service object specifically + * for the requesting caller. The caller can release the returned service object + * and the framework will call the UngetService method with the service object. + * When a module uses the ModuleContext::GetService(const ServiceReferenceBase&) + * method to obtain a service object, the framework acts as if the service + * has module scope. That is, the framework will call the GetService method to + * obtain a module-scoped instance which will be cached and have a use count. + * See ServiceFactory. + * + * A module can use both ServiceObjects and ModuleContext::GetService(const ServiceReferenceBase&) + * to obtain a service object for a service. ServiceObjects::GetService() will always + * return an instance provided by a call to GetService(Module*, const ServiceRegistrationBase&) + * and ModuleContext::GetService(const ServiceReferenceBase&) will always + * return the module-scoped instance. + * PrototypeServiceFactory objects are only used by the framework and are not made + * available to other modules. The framework may concurrently call a PrototypeServiceFactory. + * + * @see ModuleContext::GetServiceObjects() + * @see ServiceObjects + */ +struct PrototypeServiceFactory : public ServiceFactory +{ + + /** + * Returns a service object for a caller. + * + * The framework invokes this method for each caller requesting a service object using + * ServiceObjects::GetService(). The factory can then return a specific service object for the caller. + * The framework checks that the returned service object is valid. If the returned service + * object is empty or does not contain entries for all the interfaces named when the service + * was registered, a warning is issued and NULL is returned to the caller. If this + * method throws an exception, a warning is issued and NULL is returned to the caller. + * + * @param module The module requesting the service. + * @param registration The ServiceRegistrationBase object for the requested service. + * @return A service object that must contain entries for all the interfaces named when + * the service was registered. + * + * @see ServiceObjects#GetService() + * @see InterfaceMap + */ + virtual InterfaceMap GetService(Module* module, const ServiceRegistrationBase& registration) = 0; + + /** + * Releases a service object created for a caller. + * + * The framework invokes this method when a service has been released by a modules such as + * by calling ServiceObjects::UngetService(). The service object may then be destroyed. + * If this method throws an exception, a warning is issued. + * + * @param module The module releasing the service. + * @param registration The ServiceRegistrationBase object for the service being released. + * @param service The service object returned by a previous call to the GetService method. + * + * @see ServiceObjects::UngetService() + */ + virtual void UngetService(Module* module, const ServiceRegistrationBase& registration, + const InterfaceMap& service) = 0; + +}; + +US_END_NAMESPACE + +#endif // USPROTOTYPESERVICEFACTORY_H diff --git a/src/service/usServiceEvent.cpp b/src/service/usServiceEvent.cpp new file mode 100644 index 0000000000..e1b88f64f4 --- /dev/null +++ b/src/service/usServiceEvent.cpp @@ -0,0 +1,132 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usServiceEvent.h" + +#include "usServiceProperties.h" + +US_BEGIN_NAMESPACE + +class ServiceEventData : public SharedData +{ +public: + + ServiceEventData(const ServiceEvent::Type& type, const ServiceReferenceBase& reference) + : type(type), reference(reference) + { + + } + + ServiceEventData(const ServiceEventData& other) + : SharedData(other), type(other.type), reference(other.reference) + { + + } + + const ServiceEvent::Type type; + const ServiceReferenceBase reference; + +private: + + // purposely not implemented + ServiceEventData& operator=(const ServiceEventData&); +}; + +ServiceEvent::ServiceEvent() + : d(0) +{ + +} + +ServiceEvent::~ServiceEvent() +{ + +} + +bool ServiceEvent::IsNull() const +{ + return !d; +} + +ServiceEvent::ServiceEvent(Type type, const ServiceReferenceBase& reference) + : d(new ServiceEventData(type, reference)) +{ + +} + +ServiceEvent::ServiceEvent(const ServiceEvent& other) + : d(other.d) +{ + +} + +ServiceEvent& ServiceEvent::operator=(const ServiceEvent& other) +{ + d = other.d; + return *this; +} + +ServiceReferenceU ServiceEvent::GetServiceReference() const +{ + return d->reference; +} + +ServiceEvent::Type ServiceEvent::GetType() const +{ + return d->type; +} + +US_END_NAMESPACE + +US_USE_NAMESPACE + +std::ostream& operator<<(std::ostream& os, const ServiceEvent::Type& type) +{ + switch(type) + { + case ServiceEvent::MODIFIED: return os << "MODIFIED"; + case ServiceEvent::MODIFIED_ENDMATCH: return os << "MODIFIED_ENDMATCH"; + case ServiceEvent::REGISTERED: return os << "REGISTERED"; + case ServiceEvent::UNREGISTERING: return os << "UNREGISTERING"; + + default: return os << "unknown service event type (" << static_cast(type) << ")"; + } +} + +std::ostream& operator<<(std::ostream& os, const ServiceEvent& event) +{ + if (event.IsNull()) return os << "NONE"; + + os << event.GetType(); + + ServiceReferenceU sr = event.GetServiceReference(); + if (sr) + { + // Some events will not have a service reference + long int sid = any_cast(sr.GetProperty(ServiceConstants::SERVICE_ID())); + os << " " << sid; + + Any classes = sr.GetProperty(ServiceConstants::OBJECTCLASS()); + os << " objectClass=" << classes.ToString() << ")"; + } + + return os; +} diff --git a/src/service/usServiceEvent.h b/src/service/usServiceEvent.h new file mode 100644 index 0000000000..f5e2d45b17 --- /dev/null +++ b/src/service/usServiceEvent.h @@ -0,0 +1,197 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USSERVICEEVENT_H +#define USSERVICEEVENT_H + +#ifdef REGISTERED +#ifdef _WIN32 +#error The REGISTERED preprocessor define clashes with the ServiceEvent::REGISTERED\ + enum type. Try to reorder your includes, compile with WIN32_LEAN_AND_MEAN, or undef\ + the REGISTERED macro befor including this header. +#else +#error The REGISTERED preprocessor define clashes with the ServiceEvent::REGISTERED\ + enum type. Try to reorder your includes or undef the REGISTERED macro befor including\ + this header. +#endif +#endif + +#include "usSharedData.h" + +#include "usServiceReference.h" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4251) +#endif + +US_BEGIN_NAMESPACE + +class ServiceEventData; + +/** + * \ingroup MicroServices + * + * An event from the Micro Services framework describing a service lifecycle change. + *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ * The framework caches the value returned (unless the InterfaceMap is empty), + * and will return the same service object on any future call to + * ModuleContext::GetService for the same modules. This means the + * framework does not allow this method to be concurrently called for the + * same module. + * + * @param module The module using the service. + * @param registration The ServiceRegistrationBase object for the + * service. + * @return A service object that must contain entries for all + * the interfaces named when the service was registered. + * @see ModuleContext#GetService + * @see InterfaceMap + */ + virtual InterfaceMap GetService(Module* module, const ServiceRegistrationBase& registration) = 0; + + /** + * Releases a service object. + * + *

+ * The framework invokes this method when a service has been released by a + * module. The service object may then be destroyed. + * + * @param module The Module releasing the service. + * @param registration The ServiceRegistration object for the + * service. + * @param service The service object returned by a previous call to the + * ServiceFactory::GetService method. + * @see ModuleContext#UngetService + * @see InterfaceMap + */ + virtual void UngetService(Module* module, const ServiceRegistrationBase& registration, + const InterfaceMap& service) = 0; +}; + +US_END_NAMESPACE + +#endif // USSERVICEFACTORY_H diff --git a/src/service/usServiceInterface.h b/src/service/usServiceInterface.h new file mode 100644 index 0000000000..91efe207ff --- /dev/null +++ b/src/service/usServiceInterface.h @@ -0,0 +1,342 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USSERVICEINTERFACE_H +#define USSERVICEINTERFACE_H + +#include +#include + +#include +#include +#include + +/** + * \ingroup MicroServices + * + * Returns a unique id for a given type. + * + * This template method is specialized in the macro + * #US_DECLARE_SERVICE_INTERFACE to return a unique id + * for each service interface. + * + * @tparam T The service interface type. + * @return A unique id for the service interface type T. + */ +template inline const char* us_service_interface_iid(); + +/// \cond +template<> inline const char* us_service_interface_iid() { return ""; } +/// \endcond + +#if defined(QT_DEBUG) || defined(QT_NO_DEBUG) +#include + +#define US_DECLARE_SERVICE_INTERFACE(_service_interface_type, _service_interface_id) \ + template<> inline const char* qobject_interface_iid<_service_interface_type*>() \ + { return _service_interface_id; } \ + template<> inline const char* us_service_interface_iid<_service_interface_type>() \ + { return _service_interface_id; } \ + template<> inline _service_interface_type* qobject_cast<_service_interface_type*>(QObject* object) \ + { return reinterpret_cast<_service_interface_type*>(object ? object->qt_metacast(_service_interface_id) : 0); } \ + template<> inline _service_interface_type* qobject_cast<_service_interface_type*>(const QObject* object) \ + { return reinterpret_cast<_service_interface_type*>(object ? const_cast(object)->qt_metacast(_service_interface_id) : 0); } + +#else + +/** + * \ingroup MicroServices + * + * \brief Declare a CppMicroServices service interface. + * + * This macro associates the given identifier \e _service_interface_id (a string literal) to the + * interface class called _service_interface_type. The Identifier must be unique. For example: + * + * \code + * #include + * + * struct ISomeInterace { ... }; + * + * US_DECLARE_SERVICE_INTERFACE(ISomeInterface, "com.mycompany.service.ISomeInterface/1.0") + * \endcode + * + * This macro is normally used right after the class definition for _service_interface_type, in a header file. + * + * If you want to use #US_DECLARE_SERVICE_INTERFACE with interface classes declared in a + * namespace then you have to make sure the #US_DECLARE_SERVICE_INTERFACE macro call is not + * inside a namespace though. For example: + * + * \code + * #include + * + * namespace Foo + * { + * struct ISomeInterface { ... }; + * } + * + * US_DECLARE_SERVICE_INTERFACE(Foo::ISomeInterface, "com.mycompany.service.ISomeInterface/1.0") + * \endcode + * + * @param _service_interface_type The service interface type. + * @param _service_interface_id A string literal representing a globally unique identifier. + */ +#define US_DECLARE_SERVICE_INTERFACE(_service_interface_type, _service_interface_id) \ + template<> inline const char* us_service_interface_iid<_service_interface_type>() \ + { return _service_interface_id; } \ + +#endif + +US_BEGIN_NAMESPACE + +class ServiceFactory; + +/** + * @ingroup MicroServices + * + * A helper type used in several methods to get proper + * method overload resolutions. + */ +template +struct InterfaceT {}; + +/** + * @ingroup MicroServices + * + * A map containing interfaces ids and their corresponding service object + * pointers. InterfaceMap instances represent a complete service object + * which implementes one or more service interfaces. For each implemented + * service interface, there is an entry in the map with the key being + * the service interface id and the value a pointer to the service + * interface implementation. + * + * To create InterfaceMap instances, use the MakeInterfaceMap helper class. + * + * @note This is a low-level type and should only rarely be used. + * + * @see MakeInterfaceMap + */ +typedef std::map InterfaceMap; + + +template +bool InsertInterfaceType(InterfaceMap& im, I* i) +{ + if (us_service_interface_iid() == NULL) + { + throw ServiceException(std::string("The interface class ") + typeid(I).name() + + " uses an invalid id in its US_DECLARE_SERVICE_INTERFACE macro call."); + } + im.insert(std::make_pair(std::string(us_service_interface_iid()), + static_cast(static_cast(i)))); + return true; +} + +template<> +inline bool InsertInterfaceType(InterfaceMap&, void*) +{ + return false; +} + + +/** + * @ingroup MicroServices + * + * Helper class for constructing InterfaceMap instances based + * on service implementations or service factories. + * + * Example usage: + * \code + * MyService service; // implementes I1 and I2 + * InterfaceMap im = MakeInterfaceMap(&service); + * \endcode + * + * The MakeInterfaceMap supports service implementations with + * up to three service interfaces. + * + * @see InterfaceMap + */ +template +struct MakeInterfaceMap +{ + ServiceFactory* m_factory; + I1* m_interface1; + I2* m_interface2; + I3* m_interface3; + + /** + * Constructor taking a service implementation pointer. + * + * @param impl A service implementation pointer, which must + * be castable to a all specified service interfaces. + */ + template + MakeInterfaceMap(Impl* impl) + : m_factory(NULL) + , m_interface1(static_cast(impl)) + , m_interface2(static_cast(impl)) + , m_interface3(static_cast(impl)) + {} + + /** + * Constructor taking a service factory. + * + * @param factory A service factory. + */ + MakeInterfaceMap(ServiceFactory* factory) + : m_factory(factory) + , m_interface1(NULL) + , m_interface2(NULL) + , m_interface3(NULL) + { + if (factory == NULL) + { + throw ServiceException("The service factory argument must not be NULL."); + } + } + + operator InterfaceMap () + { + InterfaceMap sim; + InsertInterfaceType(sim, m_interface1); + InsertInterfaceType(sim, m_interface2); + InsertInterfaceType(sim, m_interface3); + + if (m_factory) + { + sim.insert(std::make_pair(std::string("org.cppmicroservices.factory"), + static_cast(m_factory))); + } + + return sim; + } +}; + +/// \cond +template +struct MakeInterfaceMap +{ + ServiceFactory* m_factory; + I1* m_interface1; + I2* m_interface2; + + template + MakeInterfaceMap(Impl* impl) + : m_factory(NULL) + , m_interface1(static_cast(impl)) + , m_interface2(static_cast(impl)) + {} + + MakeInterfaceMap(ServiceFactory* factory) + : m_factory(factory) + , m_interface1(NULL) + , m_interface2(NULL) + { + if (factory == NULL) + { + throw ServiceException("The service factory argument must not be NULL."); + } + } + + operator InterfaceMap () + { + InterfaceMap sim; + InsertInterfaceType(sim, m_interface1); + InsertInterfaceType(sim, m_interface2); + + if (m_factory) + { + sim.insert(std::make_pair(std::string("org.cppmicroservices.factory"), + static_cast(m_factory))); + } + + return sim; + } +}; + +template +struct MakeInterfaceMap +{ + ServiceFactory* m_factory; + I1* m_interface1; + + template + MakeInterfaceMap(Impl* impl) + : m_factory(NULL) + , m_interface1(static_cast(impl)) + {} + + MakeInterfaceMap(ServiceFactory* factory) + : m_factory(factory) + , m_interface1(NULL) + { + if (factory == NULL) + { + throw ServiceException("The service factory argument must not be NULL."); + } + } + + operator InterfaceMap () + { + InterfaceMap sim; + InsertInterfaceType(sim, m_interface1); + + if (m_factory) + { + sim.insert(std::make_pair(std::string("org.cppmicroservices.factory"), + static_cast(m_factory))); + } + + return sim; + } +}; + +template<> +struct MakeInterfaceMap; +/// \endcond + +/** + * @ingroup MicroServices + * + * Extract a service interface pointer from a given InterfaceMap instance. + * + * @param map a InterfaceMap instance. + * @return The service interface pointer for the service interface id of the + * \c I1 interface type or NULL if \c map does not contain an entry + * for the given type. + * + * @see MakeInterfaceMap + */ +template +I1* ExtractInterface(const InterfaceMap& map) +{ + InterfaceMap::const_iterator iter = map.find(us_service_interface_iid()); + if (iter != map.end()) + { + return reinterpret_cast(iter->second); + } + return NULL; +} + +US_END_NAMESPACE + + +#endif // USSERVICEINTERFACE_H diff --git a/src/service/usServiceListenerEntry.cpp b/src/service/usServiceListenerEntry.cpp new file mode 100644 index 0000000000..6dcb178ba0 --- /dev/null +++ b/src/service/usServiceListenerEntry.cpp @@ -0,0 +1,150 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#include "usServiceListenerEntry_p.h" + +US_BEGIN_NAMESPACE + +class ServiceListenerEntryData : public SharedData +{ +public: + + ServiceListenerEntryData(Module* mc, const ServiceListenerEntry::ServiceListener& l, + void* data, const std::string& filter) + : mc(mc), listener(l), data(data), bRemoved(false), ldap() + { + if (!filter.empty()) + { + ldap = LDAPExpr(filter); + } + } + + ~ServiceListenerEntryData() + { + + } + + Module* const mc; + ServiceListenerEntry::ServiceListener listener; + void* data; + bool bRemoved; + LDAPExpr ldap; + + /** + * The elements of "simple" filters are cached, for easy lookup. + * + * The grammar for simple filters is as follows: + * + *

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

+ * The index of the vector determines which key the cache is for + * (see ServiceListenerState#hashedKeys). For each key, there is + * a vector pointing out the values which are accepted by this + * ServiceListenerEntry's filter. This cache is maintained to make + * it easy to remove this service listener. + */ + LDAPExpr::LocalCache local_cache; + +private: + + // purposely not implemented + ServiceListenerEntryData(const ServiceListenerEntryData&); + ServiceListenerEntryData& operator=(const ServiceListenerEntryData&); +}; + +ServiceListenerEntry::ServiceListenerEntry(const ServiceListenerEntry& other) + : d(other.d) +{ + +} + +ServiceListenerEntry::~ServiceListenerEntry() +{ + +} + +ServiceListenerEntry& ServiceListenerEntry::operator=(const ServiceListenerEntry& other) +{ + d = other.d; + return *this; +} + +bool ServiceListenerEntry::operator==(const ServiceListenerEntry& other) const +{ + return ((d->mc == 0 || other.d->mc == 0) || d->mc == other.d->mc) && + (d->data == other.d->data) && ServiceListenerCompare()(d->listener, other.d->listener); +} + +bool ServiceListenerEntry::operator<(const ServiceListenerEntry& other) const +{ + return (d->mc == other.d->mc) ? (d->data < other.d->data) : (d->mc < other.d->mc); +} + +void ServiceListenerEntry::SetRemoved(bool removed) const +{ + d->bRemoved = removed; +} + +bool ServiceListenerEntry::IsRemoved() const +{ + return d->bRemoved; +} + +ServiceListenerEntry::ServiceListenerEntry(Module* mc, const ServiceListener& l, + void* data, const std::string& filter) + : d(new ServiceListenerEntryData(mc, l, data, filter)) +{ + +} + +Module* ServiceListenerEntry::GetModule() const +{ + return d->mc; +} + +std::string ServiceListenerEntry::GetFilter() const +{ + return d->ldap.IsNull() ? std::string() : d->ldap.ToString(); +} + +const LDAPExpr& ServiceListenerEntry::GetLDAPExpr() const +{ + return d->ldap; +} + +LDAPExpr::LocalCache& ServiceListenerEntry::GetLocalCache() const +{ + return d->local_cache; +} + +void ServiceListenerEntry::CallDelegate(const ServiceEvent& event) const +{ + d->listener(event); +} + +US_END_NAMESPACE diff --git a/src/service/usServiceListenerEntry_p.h b/src/service/usServiceListenerEntry_p.h new file mode 100644 index 0000000000..8bedffe193 --- /dev/null +++ b/src/service/usServiceListenerEntry_p.h @@ -0,0 +1,97 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USSERVICELISTENERENTRY_H +#define USSERVICELISTENERENTRY_H + +#include +#include + +#include "usLDAPExpr_p.h" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4396) +#endif + +US_BEGIN_NAMESPACE + +class Module; +class ServiceListenerEntryData; + +/** + * Data structure for saving service listener info. Contains + * the optional service listener filter, in addition to the info + * in ListenerEntry. + */ +class ServiceListenerEntry +{ + +public: + + typedef US_SERVICE_LISTENER_FUNCTOR ServiceListener; + + ServiceListenerEntry(const ServiceListenerEntry& other); + ~ServiceListenerEntry(); + ServiceListenerEntry& operator=(const ServiceListenerEntry& other); + + bool operator==(const ServiceListenerEntry& other) const; + + bool operator<(const ServiceListenerEntry& other) const; + + void SetRemoved(bool removed) const; + bool IsRemoved() const; + + ServiceListenerEntry(Module* mc, const ServiceListener& l, void* data, const std::string& filter = ""); + + Module* GetModule() const; + + std::string GetFilter() const; + + 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/src/service/usServiceListeners.cpp b/src/service/usServiceListeners.cpp new file mode 100644 index 0000000000..85df22931b --- /dev/null +++ b/src/service/usServiceListeners.cpp @@ -0,0 +1,290 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usUtils_p.h" + +#include "usServiceListeners_p.h" +#include "usServiceReferenceBasePrivate.h" + +#include "usModule.h" + +//#include + +US_BEGIN_NAMESPACE + +const int ServiceListeners::OBJECTCLASS_IX = 0; +const int ServiceListeners::SERVICE_ID_IX = 1; + +ServiceListeners::ServiceListeners() +{ + hashedServiceKeys.push_back(ServiceConstants::OBJECTCLASS()); + hashedServiceKeys.push_back(ServiceConstants::SERVICE_ID()); +} + +void ServiceListeners::AddServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, + void* data, const std::string& filter) +{ + MutexLocker lock(mutex); + + ServiceListenerEntry sle(mc->GetModule(), listener, data, filter); + if (serviceSet.find(sle) != serviceSet.end()) + { + RemoveServiceListener_unlocked(sle); + } + serviceSet.insert(sle); + CheckSimple(sle); +} + +void ServiceListeners::RemoveServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, + void* data) +{ + ServiceListenerEntry entryToRemove(mc->GetModule(), listener, data); + + MutexLocker lock(mutex); + RemoveServiceListener_unlocked(entryToRemove); +} + +void ServiceListeners::RemoveServiceListener_unlocked(const ServiceListenerEntry& entryToRemove) +{ + for (ServiceListenerEntries::iterator it = serviceSet.begin(); + it != serviceSet.end(); ++it) + { + if (it->operator ==(entryToRemove)) + { + it->SetRemoved(true); + RemoveFromCache(*it); + serviceSet.erase(it); + break; + } + } +} + +void ServiceListeners::AddModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data) +{ + MutexLocker lock(moduleListenerMapMutex); + ModuleListenerMap::value_type::second_type& listeners = moduleListenerMap[mc]; + if (std::find_if(listeners.begin(), listeners.end(), std::bind1st(ModuleListenerCompare(), std::make_pair(listener, data))) == listeners.end()) + { + listeners.push_back(std::make_pair(listener, data)); + } +} + +void ServiceListeners::RemoveModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data) +{ + MutexLocker lock(moduleListenerMapMutex); + moduleListenerMap[mc].remove_if(std::bind1st(ModuleListenerCompare(), std::make_pair(listener, data))); +} + +void ServiceListeners::ModuleChanged(const ModuleEvent& evt) +{ + MutexLocker lock(moduleListenerMapMutex); + for(ModuleListenerMap::iterator i = moduleListenerMap.begin(); + i != moduleListenerMap.end(); ++i) + { + for(std::list >::iterator j = i->second.begin(); + j != i->second.end(); ++j) + { + (j->first)(evt); + } + } +} + +void ServiceListeners::RemoveAllListeners(ModuleContext* mc) +{ + { + MutexLocker lock(mutex); + for (ServiceListenerEntries::iterator it = serviceSet.begin(); + it != serviceSet.end(); ) + { + + if (it->GetModule() == mc->GetModule()) + { + RemoveFromCache(*it); + serviceSet.erase(it++); + } + else + { + ++it; + } + } + } + + { + MutexLocker lock(moduleListenerMapMutex); + moduleListenerMap.erase(mc); + } +} + +void ServiceListeners::ServiceChanged(const ServiceListenerEntries& receivers, + const ServiceEvent& evt) +{ + ServiceListenerEntries matchBefore; + ServiceChanged(receivers, evt, matchBefore); +} + +void ServiceListeners::ServiceChanged(const ServiceListenerEntries& receivers, + const ServiceEvent& evt, + ServiceListenerEntries& matchBefore) +{ + int n = 0; + + for (ServiceListenerEntries::const_iterator l = receivers.begin(); + l != receivers.end(); ++l) + { + if (!matchBefore.empty()) + { + matchBefore.erase(*l); + } + + if (!l->IsRemoved()) + { + try + { + ++n; + l->CallDelegate(evt); + } + catch (...) + { + US_WARN << "Service listener" + #ifdef US_MODULE_SUPPORT_ENABLED + << " in " << l->GetModule()->GetName() + #endif + << " threw an exception!"; + } + } + } + + //US_DEBUG << "Notified " << n << " listeners"; +} + +void ServiceListeners::GetMatchingServiceListeners(const ServiceReferenceBase& sr, ServiceListenerEntries& set, + bool lockProps) +{ + MutexLocker lock(mutex); + + // Check complicated or empty listener filters + int n = 0; + for (std::list::const_iterator sse = complicatedListeners.begin(); + sse != complicatedListeners.end(); ++sse) + { + ++n; + const LDAPExpr& ldapExpr = sse->GetLDAPExpr(); + if (ldapExpr.IsNull() || + ldapExpr.Evaluate(sr.d->GetProperties(), false)) + { + set.insert(*sse); + } + } + + //US_DEBUG << "Added " << set.size() << " out of " << n + // << " listeners with complicated filters"; + + // Check the cache + const std::vector c(any_cast > + (sr.d->GetProperty(ServiceConstants::OBJECTCLASS(), lockProps))); + for (std::vector::const_iterator objClass = c.begin(); + objClass != c.end(); ++objClass) + { + AddToSet(set, OBJECTCLASS_IX, *objClass); + } + + long service_id = any_cast(sr.d->GetProperty(ServiceConstants::SERVICE_ID(), lockProps)); + std::stringstream ss; + ss << service_id; + AddToSet(set, SERVICE_ID_IX, ss.str()); +} + +void ServiceListeners::RemoveFromCache(const ServiceListenerEntry& sle) +{ + if (!sle.GetLocalCache().empty()) + { + for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) + { + CacheType& keymap = cache[i]; + std::vector& l = sle.GetLocalCache()[i]; + for (std::vector::const_iterator it = l.begin(); + it != l.end(); ++it) + { + std::list& sles = keymap[*it]; + sles.remove(sle); + if (sles.empty()) + { + keymap.erase(*it); + } + } + } + } + else + { + complicatedListeners.remove(sle); + } +} + + void ServiceListeners::CheckSimple(const ServiceListenerEntry& sle) { + if (sle.GetLDAPExpr().IsNull()) + { + complicatedListeners.push_back(sle); + } + else + { + LDAPExpr::LocalCache local_cache; + if (sle.GetLDAPExpr().IsSimple(hashedServiceKeys, local_cache, false)) + { + sle.GetLocalCache() = local_cache; + for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) + { + for (std::vector::const_iterator it = local_cache[i].begin(); + it != local_cache[i].end(); ++it) + { + std::list& sles = cache[i][*it]; + sles.push_back(sle); + } + } + } + else + { + //US_DEBUG << "Too complicated filter: " << sle.GetFilter(); + complicatedListeners.push_back(sle); + } + } + } + +void ServiceListeners::AddToSet(ServiceListenerEntries& set, + int cache_ix, const std::string& val) +{ + std::list& l = cache[cache_ix][val]; + if (!l.empty()) + { + //US_DEBUG << hashedServiceKeys[cache_ix] << " matches " << l.size(); + + for (std::list::const_iterator entry = l.begin(); + entry != l.end(); ++entry) + { + set.insert(*entry); + } + } + else + { + //US_DEBUG << hashedServiceKeys[cache_ix] << " matches none"; + } +} + +US_END_NAMESPACE diff --git a/src/service/usServiceListeners_p.h b/src/service/usServiceListeners_p.h new file mode 100644 index 0000000000..0544b58ee3 --- /dev/null +++ b/src/service/usServiceListeners_p.h @@ -0,0 +1,176 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USSERVICELISTENERS_H +#define USSERVICELISTENERS_H + +#include +#include +#include + +#include + +#include "usServiceListenerEntry_p.h" + +US_BEGIN_NAMESPACE + +class CoreModuleContext; +class ModuleContext; + +/** + * Here we handle all listeners that modules have registered. + * + */ +class ServiceListeners { + +private: + + typedef Mutex MutexType; + typedef MutexLock MutexLocker; + +public: + + typedef US_MODULE_LISTENER_FUNCTOR ModuleListener; + typedef US_UNORDERED_MAP_TYPE > > ModuleListenerMap; + ModuleListenerMap moduleListenerMap; + MutexType moduleListenerMapMutex; + + typedef US_UNORDERED_MAP_TYPE > CacheType; + typedef US_UNORDERED_SET_TYPE ServiceListenerEntries; + +private: + + std::vector hashedServiceKeys; + static const int OBJECTCLASS_IX; // = 0; + static const int SERVICE_ID_IX; // = 1; + + /* Service listeners with complicated or empty filters */ + std::list complicatedListeners; + + /* Service listeners with "simple" filters are cached. */ + CacheType cache[2]; + + ServiceListenerEntries serviceSet; + + MutexType mutex; + +public: + + ServiceListeners(); + + /** + * Add a new service listener. If an old one exists, and it has the + * same owning module, the old listener is removed first. + * + * @param mc The module context adding this listener. + * @param listener The service listener to add. + * @param data Additional data to distinguish ServiceListener objects. + * @param filter An LDAP filter string to check when a service is modified. + * @exception org.osgi.framework.InvalidSyntaxException + * If the filter is not a correct LDAP expression. + */ + void AddServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, + void* data, const std::string& filter); + + /** + * Remove service listener from current framework. Silently ignore + * if listener doesn't exist. If listener is registered more than + * once remove all instances. + * + * @param mc The module context who wants to remove listener. + * @param listener Object to remove. + * @param data Additional data to distinguish ServiceListener objects. + */ + void RemoveServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, + void* data); + + /** + * Add a new module listener. + * + * @param mc The module context adding this listener. + * @param listener The module listener to add. + * @param data Additional data to distinguish ModuleListener objects. + */ + void AddModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data); + + /** + * Remove module listener from current framework. Silently ignore + * if listener doesn't exist. + * + * @param mc The module context who wants to remove listener. + * @param listener Object to remove. + * @param data Additional data to distinguish ModuleListener objects. + */ + void RemoveModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data); + + void ModuleChanged(const ModuleEvent& evt); + + /** + * Remove all listener registered by a module in the current framework. + * + * @param mc Module context which listeners we want to remove. + */ + void RemoveAllListeners(ModuleContext* mc); + + /** + * Receive notification that a service has had a change occur in its lifecycle. + * + * @see org.osgi.framework.ServiceListener#serviceChanged + */ + void ServiceChanged(const ServiceListenerEntries& receivers, + const ServiceEvent& evt, + ServiceListenerEntries& matchBefore); + + void ServiceChanged(const ServiceListenerEntries& receivers, + const ServiceEvent& evt); + + /** + * + * + */ + void GetMatchingServiceListeners(const ServiceReferenceBase& sr, ServiceListenerEntries& listeners, + bool lockProps = true); + + +private: + + void RemoveServiceListener_unlocked(const ServiceListenerEntry& entryToRemove); + + /** + * Remove all references to a service listener from the service listener + * cache. + */ + void RemoveFromCache(const ServiceListenerEntry& sle); + + /** + * Checks if the specified service listener's filter is simple enough + * to cache. + */ + void CheckSimple(const ServiceListenerEntry& sle); + + void AddToSet(ServiceListenerEntries& set, int cache_ix, const std::string& val); + +}; + +US_END_NAMESPACE + +#endif // USSERVICELISTENERS_H diff --git a/src/service/usServiceObjects.cpp b/src/service/usServiceObjects.cpp new file mode 100644 index 0000000000..1595ec283d --- /dev/null +++ b/src/service/usServiceObjects.cpp @@ -0,0 +1,209 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usServiceObjects.h" + +#include "usServiceReferenceBasePrivate.h" + +#include + +US_BEGIN_NAMESPACE + +class ServiceObjectsBasePrivate +{ +public: + + AtomicInt ref; + + ModuleContext* m_context; + ServiceReferenceBase m_reference; + + // This is used by all ServiceObjects instances with S != void + std::map m_serviceInstances; + // This is used by ServiceObjects + std::set m_serviceInterfaceMaps; + + ServiceObjectsBasePrivate(ModuleContext* context, const ServiceReferenceBase& reference) + : m_context(context) + , m_reference(reference) + {} + + InterfaceMap GetServiceInterfaceMap() + { + InterfaceMap result; + + bool isPrototypeScope = m_reference.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == + ServiceConstants::SCOPE_PROTOTYPE(); + + if (isPrototypeScope) + { + result = m_reference.d->GetPrototypeService(m_context->GetModule()); + } + else + { + result = m_reference.d->GetServiceInterfaceMap(m_context->GetModule()); + } + + return result; + } +}; + +ServiceObjectsBase::ServiceObjectsBase(ModuleContext* context, const ServiceReferenceBase& reference) + : d(new ServiceObjectsBasePrivate(context, reference)) +{ + if (!reference) + { + delete d; + throw std::invalid_argument("The service reference is invalid"); + } +} + +void* ServiceObjectsBase::GetService() const +{ + if (!d->m_reference) + { + return NULL; + } + + InterfaceMap im = d->GetServiceInterfaceMap(); + void* result = im.find(d->m_reference.GetInterfaceId())->second; + + if (result) + { + d->m_serviceInstances.insert(std::make_pair(result, im)); + } + return result; +} + +InterfaceMap ServiceObjectsBase::GetServiceInterfaceMap() const +{ + InterfaceMap result; + if (!d->m_reference) + { + return result; + } + + result = d->GetServiceInterfaceMap(); + + if (!result.empty()) + { + d->m_serviceInterfaceMaps.insert(result); + } + return result; +} + +void ServiceObjectsBase::UngetService(void* service) +{ + if (service == NULL) + { + return; + } + + std::map::iterator serviceIter = d->m_serviceInstances.find(service); + if (serviceIter == d->m_serviceInstances.end()) + { + throw std::invalid_argument("The provided service has not been retrieved via this ServiceObjects instance"); + } + + if (!d->m_reference.d->UngetPrototypeService(d->m_context->GetModule(), serviceIter->second)) + { + US_WARN << "Ungetting service unsuccessful"; + } + else + { + d->m_serviceInstances.erase(serviceIter); + } +} + +void ServiceObjectsBase::UngetService(const InterfaceMap& interfaceMap) +{ + if (interfaceMap.empty()) + { + return; + } + + std::set::iterator serviceIter = d->m_serviceInterfaceMaps.find(interfaceMap); + if (serviceIter == d->m_serviceInterfaceMaps.end()) + { + throw std::invalid_argument("The provided service has not been retrieved via this ServiceObjects instance"); + } + + if (!d->m_reference.d->UngetPrototypeService(d->m_context->GetModule(), interfaceMap)) + { + US_WARN << "Ungetting service unsuccessful"; + } + else + { + d->m_serviceInterfaceMaps.erase(serviceIter); + } +} + +ServiceReferenceBase ServiceObjectsBase::GetReference() const +{ + return d->m_reference; +} + +ServiceObjectsBase::ServiceObjectsBase(const ServiceObjectsBase& other) + : d(other.d) +{ + d->ref.Ref(); +} + +ServiceObjectsBase::~ServiceObjectsBase() +{ + if (!d->ref.Deref()) + { + delete d; + } +} + +ServiceObjectsBase& ServiceObjectsBase::operator =(const ServiceObjectsBase& other) +{ + ServiceObjectsBasePrivate* curr_d = d; + d = other.d; + d->ref.Ref(); + + if (!curr_d->ref.Deref()) + delete curr_d; + + return *this; +} + +InterfaceMap ServiceObjects::GetService() const +{ + return this->ServiceObjectsBase::GetServiceInterfaceMap(); +} + +void ServiceObjects::UngetService(const InterfaceMap& service) +{ + this->ServiceObjectsBase::UngetService(service); +} + +ServiceReferenceU ServiceObjects::GetServiceReference() const +{ + return this->ServiceObjectsBase::GetReference(); +} + +ServiceObjects::ServiceObjects(ModuleContext* context, const ServiceReferenceU& reference) + : ServiceObjectsBase(context, reference) +{} + +US_END_NAMESPACE diff --git a/src/service/usServiceObjects.h b/src/service/usServiceObjects.h new file mode 100644 index 0000000000..f0db27accd --- /dev/null +++ b/src/service/usServiceObjects.h @@ -0,0 +1,259 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USSERVICEOBJECTS_H +#define USSERVICEOBJECTS_H + +#include + +#include +#include +#include +#include + +US_BEGIN_NAMESPACE + +class ServiceObjectsBasePrivate; + +class US_EXPORT ServiceObjectsBase +{ + +private: + + ServiceObjectsBasePrivate* d; + +protected: + + ServiceObjectsBase(ModuleContext* context, const ServiceReferenceBase& reference); + + ServiceObjectsBase(const ServiceObjectsBase& other); + + ~ServiceObjectsBase(); + + ServiceObjectsBase& operator=(const ServiceObjectsBase& other); + + // Called by ServiceObjects with S != void + void* GetService() const; + + // Called by the ServiceObjects specialization + InterfaceMap GetServiceInterfaceMap() const; + + // Called by ServiceObjects with S != void + void UngetService(void* service); + + // Called by the ServiceObjects specialization + void UngetService(const InterfaceMap& interfaceMap); + + ServiceReferenceBase GetReference() const; + +}; + +/** + * @ingroup MicroServices + * + * Allows multiple service objects for a service to be obtained. + * + * For services with \link ServiceConstants::SCOPE_PROTOTYPE prototype\endlink scope, + * multiple service objects for the service can be obtained. For services with + * \link ServiceConstants::SCOPE_SINGLETON singleton\endlink or + * \link ServiceConstants::SCOPE_MODULE module \endlink scope, only one, use-counted + * service object is available. Any unreleased service objects obtained from this + * ServiceObjects object are automatically released by the framework when the modules + * associated with the ModuleContext used to create this ServiceObjects object is + * stopped. + * + * @tparam S Type of Service. + */ +template +class ServiceObjects : private ServiceObjectsBase +{ + +public: + + /** + * Returns a service object for the referenced service. + * + * This ServiceObjects object can be used to obtain multiple service objects for + * the referenced service if the service has \link ServiceConstants::SCOPE_PROTOTYPE prototype\endlink + * scope. If the referenced service has \link ServiceConstants::SCOPE_SINGLETON singleton\endlink + * or \link ServiceConstants::SCOPE_MODULE module\endlink scope, this method + * behaves the same as calling the ModuleContext::GetService(const ServiceReferenceBase&) + * method for the referenced service. That is, only one, use-counted service object + * is available from this ServiceObjects object. + * + * This method will always return \c NULL when the referenced service has been unregistered. + * + * For a prototype scope service, the following steps are taken to get the service object: + * + *

    + *
  1. If the referenced service has been unregistered, \c NULL is returned.
  2. + *
  3. The PrototypeServiceFactory::GetService(Module*, const ServiceRegistrationBase&) + * method is called to create a service object for the caller.
  4. + *
  5. If the service object (an instance of InterfaceMap) returned by the + * PrototypeServiceFactory object is empty, does not contain all the interfaces + * named when the service was registered or the PrototypeServiceFactory object + * throws an exception, \c NULL is returned and a warning message is issued.
  6. + *
  7. The service object is returned.
  8. + *
+ * + * @return A service object for the referenced service or \c NULL if the service is not + * registered, the service object returned by a ServiceFactory does not contain + * all the classes under which it was registered or the ServiceFactory threw an + * exception. + * + * @throw std::logic_error If the ModuleContext used to create this ServiceObjects object + * is no longer valid. + * + * @see UngetService() + */ + S* GetService() const + { + return reinterpret_cast(this->ServiceObjectsBase::GetService()); + } + + /** + * Releases a service object for the referenced service. + * + * This ServiceObjects object can be used to obtain multiple service objects for + * the referenced service if the service has \link ServiceConstants::SCOPE_PROTOTYPE prototype\endlink + * scope. If the referenced service has \link ServiceConstants::SCOPE_SINGLETON singleton\endlink + * or \link ServiceConstants::SCOPE_MODULE module\endlink scope, this method + * behaves the same as calling the ModuleContext::UngetService(const ServiceReferenceBase&) + * method for the referenced service. That is, only one, use-counted service object + * is available from this ServiceObjects object. + * + * For a prototype scope service, the following steps are take to release the service object: + * + *
    + *
  1. If the referenced service has been unregistered, this method returns without + * doing anything.
  2. + *
  3. The PrototypeServiceFactory::UngetService(Module*, const ServiceRegistrationBase&, const InterfaceMap&) + * method is called to release the specified service object.
  4. + *
  5. The specified service object must no longer be used and all references to it + * should be destroyed after calling this method.
  6. + *
+ * + * @param service A service object previously provided by this ServiceObjects object. + * + * @throw std::logic_error If the ModuleContext used to create this ServiceObjects + * object is no longer valid. + * @throw std::invalid_argument If the specified service was not provided by this + * ServiceObjects object. + * + * @see GetService() + */ + void UngetService(S* service) + { + this->ServiceObjectsBase::UngetService(service); + } + + /** + * Returns the ServiceReference for this ServiceObjects object. + * + * @return The ServiceReference for this ServiceObjects object. + */ + ServiceReference GetServiceReference() const + { + return this->ServiceObjectsBase::GetReference(); + } + +private: + + friend class ModuleContext; + + ServiceObjects(ModuleContext* context, const ServiceReference& reference) + : ServiceObjectsBase(context, reference) + {} + +}; + +/** + * @ingroup MicroServices + * + * Allows multiple service objects for a service to be obtained. + * + * This is a specialization of the ServiceObjects class template for + * "void", which maps to all service interface types. + * + * @see ServiceObjects + */ +template<> +class US_EXPORT ServiceObjects : private ServiceObjectsBase +{ + +public: + + /** + * Returns a service object as a InterfaceMap instance for the referenced service. + * + * This method is the same as ServiceObjects::GetService() except for the + * return type. Further, this method will always return an empty InterfaeMap + * object when the referenced service has been unregistered. + * + * @return A InterfaceMap object for the referenced service, which is empty if the + * service is not registered, the InterfaceMap returned by a ServiceFactory + * does not contain all the classes under which the service object was + * registered or the ServiceFactory threw an exception. + * + * @throw std::logic_error If the ModuleContext used to create this ServiceObjects object + * is no longer valid. + * + * @see ServiceObjects::GetService() + * @see UngetService() + */ + InterfaceMap GetService() const; + + /** + * Releases a service object for the referenced service. + * + * This method is the same as ServiceObjects::UngetService() except for the + * parameter type. + * + * @param service An InterfaceMap object previously provided by this ServiceObjects object. + * + * @throw std::logic_error If the ModuleContext used to create this ServiceObjects + * object is no longer valid. + * @throw std::invalid_argument If the specified service was not provided by this + * ServiceObjects object. + * + * @see ServiceObjects::UngetService() + * @see GetService() + */ + void UngetService(const InterfaceMap& service); + + /** + * Returns the ServiceReference for this ServiceObjects object. + * + * @return The ServiceReference for this ServiceObjects object. + */ + ServiceReferenceU GetServiceReference() const; + +private: + + friend class ModuleContext; + + ServiceObjects(ModuleContext* context, const ServiceReferenceU& reference); + +}; + +US_END_NAMESPACE + +#endif // USSERVICEOBJECTS_H diff --git a/src/service/usServiceProperties.cpp b/src/service/usServiceProperties.cpp new file mode 100644 index 0000000000..d23acc7712 --- /dev/null +++ b/src/service/usServiceProperties.cpp @@ -0,0 +1,83 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usServiceProperties.h" +#include + +#include + +US_BEGIN_NAMESPACE + +const std::string& ServiceConstants::OBJECTCLASS() +{ + static const std::string s("objectclass"); + return s; +} + +const std::string& ServiceConstants::SERVICE_ID() +{ + static const std::string s("service.id"); + return s; +} + +const std::string& ServiceConstants::SERVICE_RANKING() +{ + static const std::string s("service.ranking"); + return s; +} + +const std::string& ServiceConstants::SERVICE_SCOPE() +{ + static const std::string s("service.scope"); + return s; +} + +const std::string& ServiceConstants::SCOPE_SINGLETON() +{ + static const std::string s("singleton"); + return s; +} + +const std::string& ServiceConstants::SCOPE_MODULE() +{ + static const std::string s("module"); + return s; +} + +const std::string& ServiceConstants::SCOPE_PROTOTYPE() +{ + static const std::string s("prototype"); + return s; +} + +US_END_NAMESPACE + +US_USE_NAMESPACE + +// make sure all static locals get constructed, so that they +// can be used in destructors of global statics. +std::string tmp1 = ServiceConstants::OBJECTCLASS(); +std::string tmp2 = ServiceConstants::SERVICE_ID(); +std::string tmp3 = ServiceConstants::SERVICE_RANKING(); +std::string tmp4 = ServiceConstants::SERVICE_SCOPE(); +std::string tmp5 = ServiceConstants::SCOPE_SINGLETON(); +std::string tmp6 = ServiceConstants::SCOPE_MODULE(); +std::string tmp7 = ServiceConstants::SCOPE_PROTOTYPE(); diff --git a/src/service/usServiceProperties.h b/src/service/usServiceProperties.h new file mode 100644 index 0000000000..208d84ea77 --- /dev/null +++ b/src/service/usServiceProperties.h @@ -0,0 +1,138 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef US_SERVICE_PROPERTIES_H +#define US_SERVICE_PROPERTIES_H + + +#include + +#include + +#include "usAny.h" + +US_BEGIN_NAMESPACE + +/** + * \ingroup MicroServices + * + * A hash table with std::string as the key type and Any as the value + * type. It is typically used for passing service properties to + * ModuleContext::RegisterService. + */ +typedef US_UNORDERED_MAP_TYPE ServiceProperties; + +/** + * \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::vector<std::string>. + * + *

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

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

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

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

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

+ * If the supplied property value is not of type int, it is + * deemed to have a ranking value of zero. + */ +US_EXPORT const std::string& SERVICE_RANKING(); // = "service.ranking" + +/** + * Service property identifying a service's scope. + * This property is set by the framework when a service is registered. If the + * registered object implements PrototypeServiceFactory, then the value of this + * service property will be SCOPE_PROTOTYPE(). Otherwise, if the registered + * object implements ServiceFactory, then the value of this service property will + * be SCOPE_MODULE(). Otherwise, the value of this service property will be + * SCOPE_SINGLETON(). + */ +US_EXPORT const std::string& SERVICE_SCOPE(); // = "service.scope" + +/** + * Service scope is singleton. All modules using the service receive the same + * service object. + * + * @see SERVICE_SCOPE() + */ +US_EXPORT const std::string& SCOPE_SINGLETON(); // = "singleton" + +/** + * Service scope is module. Each module using the service receives a distinct + * service object. + * + * @see SERVICE_SCOPE() + */ +US_EXPORT const std::string& SCOPE_MODULE(); // = "module" + +/** + * Service scope is prototype. Each module using the service receives either + * a distinct service object or can request multiple distinct service objects + * via ServiceObjects. + * + * @see SERVICE_SCOPE() + */ +US_EXPORT const std::string& SCOPE_PROTOTYPE(); // = "prototype" + +} + +US_END_NAMESPACE + +#endif // US_SERVICE_PROPERTIES_H diff --git a/src/service/usServicePropertiesImpl.cpp b/src/service/usServicePropertiesImpl.cpp new file mode 100644 index 0000000000..beca29c558 --- /dev/null +++ b/src/service/usServicePropertiesImpl.cpp @@ -0,0 +1,99 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usServicePropertiesImpl_p.h" + +#include +#ifdef US_PLATFORM_WINDOWS +#include +#define ci_compare strnicmp +#else +#include +#define ci_compare strncasecmp +#endif + +US_BEGIN_NAMESPACE + +Any ServicePropertiesImpl::emptyAny; + +ServicePropertiesImpl::ServicePropertiesImpl(const ServiceProperties& p) +{ + keys.reserve(p.size()); + values.reserve(p.size()); + + for (ServiceProperties::const_iterator iter = p.begin(); + iter != p.end(); ++iter) + { + if (Find(iter->first) > -1) + { + std::string msg = "ServiceProperties object contains case variants of the key: "; + msg += iter->first; + throw std::runtime_error(msg.c_str()); + } + keys.push_back(iter->first); + values.push_back(iter->second); + } +} + +const Any& ServicePropertiesImpl::Value(const std::string& key) const +{ + int i = Find(key); + if (i < 0) return emptyAny; + return values[i]; +} + +const Any& ServicePropertiesImpl::Value(int index) const +{ + if (index < 0 || static_cast(index) >= values.size()) + return emptyAny; + return values[index]; +} + +int ServicePropertiesImpl::Find(const std::string& key) const +{ + for (std::size_t i = 0; i < keys.size(); ++i) + { + if (ci_compare(key.c_str(), keys[i].c_str(), key.size()) == 0) + { + return i; + } + } + return -1; +} + +int ServicePropertiesImpl::FindCaseSensitive(const std::string& key) const +{ + for (std::size_t i = 0; i < keys.size(); ++i) + { + if (key == keys[i]) + { + return i; + } + } + return -1; +} + +const std::vector& ServicePropertiesImpl::Keys() const +{ + return keys; +} + +US_END_NAMESPACE diff --git a/src/service/usServicePropertiesImpl_p.h b/src/service/usServicePropertiesImpl_p.h new file mode 100644 index 0000000000..4012d1042e --- /dev/null +++ b/src/service/usServicePropertiesImpl_p.h @@ -0,0 +1,55 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USSERVICEPROPERTIESIMPL_P_H +#define USSERVICEPROPERTIESIMPL_P_H + +#include "usServiceProperties.h" + +US_BEGIN_NAMESPACE + +class ServicePropertiesImpl +{ + +public: + + explicit ServicePropertiesImpl(const ServiceProperties& props); + + const Any& Value(const std::string& key) const; + const Any& Value(int index) const; + + int Find(const std::string& key) const; + int FindCaseSensitive(const std::string& key) const; + + const std::vector& Keys() const; + +private: + + std::vector keys; + std::vector values; + + static Any emptyAny; + +}; + +US_END_NAMESPACE + +#endif // USSERVICEPROPERTIESIMPL_P_H diff --git a/src/service/usServiceReference.h b/src/service/usServiceReference.h new file mode 100644 index 0000000000..ff9bfc6cd0 --- /dev/null +++ b/src/service/usServiceReference.h @@ -0,0 +1,146 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USSERVICEREFERENCE_H +#define USSERVICEREFERENCE_H + +#include +#include + +//US_MSVC_PUSH_DISABLE_WARNING(4396) + +US_BEGIN_NAMESPACE + +/** + * \ingroup MicroServices + * + * A reference to a service. + * + *

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

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

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

+ * If the same service object is registered multiple times, + * ServiceReference objects associated with different + * ServiceRegistration objects are not equal. + * + * @tparam S The class type of the service interface + * @see ModuleContext::GetServiceReference + * @see ModuleContext::GetServiceReferences + * @see ModuleContext::GetService + * @remarks This class is thread safe. + */ +template +class ServiceReference : public ServiceReferenceBase { + +public: + + typedef S ServiceT; + + /** + * Creates an invalid ServiceReference object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceReference() : ServiceReferenceBase() + { + } + + ServiceReference(const ServiceReferenceBase& base) + : ServiceReferenceBase(base) + { + const std::string interfaceId(us_service_interface_iid()); + if (GetInterfaceId() != interfaceId) + { + if (this->IsConvertibleTo(interfaceId)) + { + this->SetInterfaceId(interfaceId); + } + else + { + this->operator =(0); + } + } + } + + using ServiceReferenceBase::operator=; + +}; + +/** + * \cond + * + * Specialization for void, representing a generic service + * reference not bound to any interface identifier. + * + */ +template<> +class ServiceReference : public ServiceReferenceBase +{ + +public: + + /** + * Creates an invalid ServiceReference object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceReference() : ServiceReferenceBase() + { + } + + ServiceReference(const ServiceReferenceBase& base) + : ServiceReferenceBase(base) + { + } + + using ServiceReferenceBase::operator=; + + typedef void ServiceType; +}; +/// \endcond + +/** + * \ingroup MicroServices + * + * A service reference of unknown type, which is not bound to any + * interface identifier. + */ +typedef ServiceReference ServiceReferenceU; + +US_END_NAMESPACE + +//US_MSVC_POP_WARNING + +#endif // USSERVICEREFERENCE_H diff --git a/src/service/usServiceReferenceBase.cpp b/src/service/usServiceReferenceBase.cpp new file mode 100644 index 0000000000..0ccd9d6559 --- /dev/null +++ b/src/service/usServiceReferenceBase.cpp @@ -0,0 +1,201 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usServiceReferenceBase.h" +#include "usServiceReferenceBasePrivate.h" +#include "usServiceRegistrationBasePrivate.h" + +#include "usModule.h" +#include "usModulePrivate.h" + + +US_BEGIN_NAMESPACE + +typedef ServiceRegistrationBasePrivate::MutexType MutexType; +typedef MutexLock MutexLocker; + +ServiceReferenceBase::ServiceReferenceBase() + : d(new ServiceReferenceBasePrivate(0)) +{ + +} + +ServiceReferenceBase::ServiceReferenceBase(const ServiceReferenceBase& ref) + : d(ref.d) +{ + d->ref.Ref(); +} + +ServiceReferenceBase::ServiceReferenceBase(ServiceRegistrationBasePrivate* reg) + : d(new ServiceReferenceBasePrivate(reg)) +{ +} + +void ServiceReferenceBase::SetInterfaceId(const std::string& interfaceId) +{ + if (d->ref > 1) + { + // detach + d->ref.Deref(); + d = new ServiceReferenceBasePrivate(d->registration); + } + d->interfaceId = interfaceId; +} + +ServiceReferenceBase::operator bool() const +{ + return GetModule() != 0; +} + +ServiceReferenceBase& ServiceReferenceBase::operator=(int null) +{ + if (null == 0) + { + if (!d->ref.Deref()) + delete d; + d = new ServiceReferenceBasePrivate(0); + } + return *this; +} + +ServiceReferenceBase::~ServiceReferenceBase() +{ + if (!d->ref.Deref()) + delete d; +} + +Any ServiceReferenceBase::GetProperty(const std::string& key) const +{ + MutexLocker lock(d->registration->propsLock); + + return d->registration->properties.Value(key); +} + +void ServiceReferenceBase::GetPropertyKeys(std::vector& keys) const +{ + MutexLocker lock(d->registration->propsLock); + + const std::vector& ks = d->registration->properties.Keys(); + keys.assign(ks.begin(), ks.end()); +} + +Module* ServiceReferenceBase::GetModule() const +{ + if (d->registration == 0 || d->registration->module == 0) + { + return 0; + } + + return d->registration->module->q; +} + +void ServiceReferenceBase::GetUsingModules(std::vector& modules) const +{ + MutexLocker lock(d->registration->propsLock); + + ServiceRegistrationBasePrivate::ModuleToRefsMap::const_iterator end = d->registration->dependents.end(); + for (ServiceRegistrationBasePrivate::ModuleToRefsMap::const_iterator iter = d->registration->dependents.begin(); + iter != end; ++iter) + { + modules.push_back(iter->first); + } +} + +bool ServiceReferenceBase::operator<(const ServiceReferenceBase& reference) const +{ + int r1 = 0; + int r2 = 0; + + Any anyR1 = GetProperty(ServiceConstants::SERVICE_RANKING()); + Any anyR2 = reference.GetProperty(ServiceConstants::SERVICE_RANKING()); + if (anyR1.Type() == typeid(int)) r1 = any_cast(anyR1); + if (anyR2.Type() == typeid(int)) r2 = any_cast(anyR2); + + if (r1 != r2) + { + // use ranking if ranking differs + return r1 < r2; + } + else + { + long int id1 = any_cast(GetProperty(ServiceConstants::SERVICE_ID())); + long int id2 = any_cast(reference.GetProperty(ServiceConstants::SERVICE_ID())); + + // otherwise compare using IDs, + // is less than if it has a higher ID. + return id2 < id1; + } +} + +bool ServiceReferenceBase::operator==(const ServiceReferenceBase& reference) const +{ + return d->registration == reference.d->registration; +} + +ServiceReferenceBase& ServiceReferenceBase::operator=(const ServiceReferenceBase& reference) +{ + ServiceReferenceBasePrivate* curr_d = d; + d = reference.d; + d->ref.Ref(); + + if (!curr_d->ref.Deref()) + delete curr_d; + + return *this; +} + +bool ServiceReferenceBase::IsConvertibleTo(const std::string& interfaceId) const +{ + return d->IsConvertibleTo(interfaceId); +} + +std::string ServiceReferenceBase::GetInterfaceId() const +{ + return d->interfaceId; +} + +std::size_t ServiceReferenceBase::Hash() const +{ + using namespace US_HASH_FUNCTION_NAMESPACE; + return US_HASH_FUNCTION(ServiceRegistrationBasePrivate*, this->d->registration); +} + +US_END_NAMESPACE + +US_USE_NAMESPACE + +std::ostream& operator<<(std::ostream& os, const ServiceReferenceBase& serviceRef) +{ + os << "Reference for service object registered from " + << serviceRef.GetModule()->GetName() << " " << serviceRef.GetModule()->GetVersion() + << " ("; + std::vector keys; + serviceRef.GetPropertyKeys(keys); + size_t keySize = keys.size(); + for(size_t i = 0; i < keySize; ++i) + { + os << keys[i] << "=" << serviceRef.GetProperty(keys[i]).ToString(); + if (i < keySize-1) os << ","; + } + os << ")"; + + return os; +} diff --git a/src/service/usServiceReferenceBase.h b/src/service/usServiceReferenceBase.h new file mode 100644 index 0000000000..9b132920d3 --- /dev/null +++ b/src/service/usServiceReferenceBase.h @@ -0,0 +1,228 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USSERVICEREFERENCEBASE_H +#define USSERVICEREFERENCEBASE_H + +#include + +US_MSVC_PUSH_DISABLE_WARNING(4396) + +US_BEGIN_NAMESPACE + +class Module; +class ServiceRegistrationBasePrivate; +class ServiceReferenceBasePrivate; + +/** + * \ingroup MicroServices + * + * A reference to a service. + * + * \note This class is provided as public API for low-level service queries only. + * In almost all cases you should use the template ServiceReference instead. + */ +class US_EXPORT ServiceReferenceBase { + +public: + + ServiceReferenceBase(const ServiceReferenceBase& ref); + + /** + * Converts this ServiceReferenceBase instance into a boolean + * expression. If this instance was default constructed or + * the service it references has been unregistered, the conversion + * returns false, otherwise it returns true. + */ + operator bool() const; + + /** + * Releases any resources held or locked by this + * ServiceReferenceBase and renders it invalid. + */ + ServiceReferenceBase& operator=(int null); + + ~ServiceReferenceBase(); + + /** + * Returns the property value to which the specified property key is mapped + * in the properties ServiceProperties object of the service + * referenced by this ServiceReferenceBase object. + * + *

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

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

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

+ * This method must return 0 when the service has been + * unregistered. This can be used to determine if the service has been + * unregistered. + * + * @return The module that registered the service referenced by this + * ServiceReferenceBase object; 0 if that + * service has already been unregistered. + * @see ModuleContext::RegisterService(const InterfaceMap&, const ServiceProperties&) + */ + Module* GetModule() const; + + /** + * Returns the modules that are using the service referenced by this + * ServiceReferenceBase object. Specifically, this method returns + * the modules whose usage count for that service is greater than zero. + * + * @param modules A list of modules whose usage count for the service referenced + * by this ServiceReferenceBase object is greater than + * zero. + */ + void GetUsingModules(std::vector& modules) const; + + /** + * Returns the interface identifier this ServiceReferenceBase object + * is bound to. + * + * A default constructed ServiceReferenceBase object is not bound to + * any interface identifier and calling this method will return an + * empty string. + * + * @return The interface identifier for this ServiceReferenceBase object. + */ + std::string GetInterfaceId() const; + + /** + * Checks wether this ServiceReferenceBase object can be converted to + * another ServiceReferenceBase object, which will be bound to the + * given interface identifier. + * + * ServiceReferenceBase objects can be converted if the underlying service + * implementation was registered under multiple service interfaces. + * + * @param interfaceid + * @return \c true if this ServiceReferenceBase object can be converted, + * \c false otherwise. + */ + bool IsConvertibleTo(const std::string& interfaceid) const; + + /** + * Compares this ServiceReferenceBase with the specified + * ServiceReferenceBase for order. + * + *

+ * If this ServiceReferenceBase and the specified + * ServiceReferenceBase have the same \link ServiceConstants::SERVICE_ID() + * service id\endlink they are equal. This ServiceReferenceBase is less + * than the specified ServiceReferenceBase if it has a lower + * {@link ServiceConstants::SERVICE_RANKING service ranking} and greater if it has a + * higher service ranking. Otherwise, if this ServiceReferenceBase + * and the specified ServiceReferenceBase have the same + * {@link ServiceConstants::SERVICE_RANKING service ranking}, this + * ServiceReferenceBase is less than the specified + * ServiceReferenceBase if it has a higher + * {@link ServiceConstants::SERVICE_ID service id} and greater if it has a lower + * service id. + * + * @param reference The ServiceReferenceBase to be compared. + * @return Returns a false or true if this + * ServiceReferenceBase is less than or greater + * than the specified ServiceReferenceBase. + */ + bool operator<(const ServiceReferenceBase& reference) const; + + bool operator==(const ServiceReferenceBase& reference) const; + + ServiceReferenceBase& operator=(const ServiceReferenceBase& reference); + +private: + + friend class ModulePrivate; + friend class ModuleContext; + friend class ServiceObjectsBase; + friend class ServiceObjectsBasePrivate; + friend class ServiceRegistrationBase; + friend class ServiceRegistrationBasePrivate; + friend class ServiceListeners; + friend class ServiceRegistry; + friend class LDAPFilter; + + template friend class ServiceReference; + + US_HASH_FUNCTION_FRIEND(ServiceReferenceBase); + + std::size_t Hash() const; + + /** + * Creates an invalid ServiceReferenceBase object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceReferenceBase(); + + ServiceReferenceBase(ServiceRegistrationBasePrivate* reg); + + void SetInterfaceId(const std::string& interfaceId); + + ServiceReferenceBasePrivate* d; + +}; + +US_END_NAMESPACE + +US_MSVC_POP_WARNING + +/** + * \ingroup MicroServices + */ +US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceReferenceBase)& serviceRef); + +US_HASH_FUNCTION_NAMESPACE_BEGIN +US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceReferenceBase)) + return arg.Hash(); +US_HASH_FUNCTION_END +US_HASH_FUNCTION_NAMESPACE_END + +#endif // USSERVICEREFERENCEBASE_H diff --git a/src/service/usServiceReferenceBasePrivate.cpp b/src/service/usServiceReferenceBasePrivate.cpp new file mode 100644 index 0000000000..adce2e1f36 --- /dev/null +++ b/src/service/usServiceReferenceBasePrivate.cpp @@ -0,0 +1,320 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#include + +#include "usServiceReferenceBasePrivate.h" + +#include "usServiceFactory.h" +#include "usServiceException.h" +#include "usServiceRegistry_p.h" +#include "usServiceRegistrationBasePrivate.h" + +#include "usModule.h" +#include "usModulePrivate.h" + +#include + +#include + +US_BEGIN_NAMESPACE + +typedef ServiceRegistrationBasePrivate::MutexLocker MutexLocker; + +ServiceReferenceBasePrivate::ServiceReferenceBasePrivate(ServiceRegistrationBasePrivate* reg) + : ref(1), registration(reg) +{ + if(registration) registration->ref.Ref(); +} + +ServiceReferenceBasePrivate::~ServiceReferenceBasePrivate() +{ + if (registration && !registration->ref.Deref()) + delete registration; +} + +InterfaceMap ServiceReferenceBasePrivate::GetServiceFromFactory(Module* module, + ServiceFactory* factory, + bool isModuleScope) +{ + assert(factory && "Factory service pointer is NULL"); + InterfaceMap s; + try + { + InterfaceMap smap = factory->GetService(module, + ServiceRegistrationBase(registration)); + if (smap.empty()) + { + US_WARN << "ServiceFactory produced null"; + return smap; + } + const std::vector& classes = + ref_any_cast >(registration->properties.Value(ServiceConstants::OBJECTCLASS())); + for (std::vector::const_iterator i = classes.begin(); + i != classes.end(); ++i) + { + if (smap.find(*i) == smap.end() && *i != "org.cppmicroservices.factory") + { + US_WARN << "ServiceFactory produced an object " + "that did not implement: " << (*i); + smap.clear(); + return smap; + } + } + s = smap; + + if (isModuleScope) + { + registration->moduleServiceInstance.insert(std::make_pair(module, smap)); + } + else + { + registration->prototypeServiceInstances[module].push_back(smap); + } + } + catch (...) + { + US_WARN << "ServiceFactory threw an exception"; + s.clear(); + } + return s; +} + +InterfaceMap ServiceReferenceBasePrivate::GetPrototypeService(Module* module) +{ + InterfaceMap s; + { + MutexLocker lock(registration->propsLock); + if (registration->available) + { + ServiceFactory* factory = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + s = GetServiceFromFactory(module, factory, false); + } + } + return s; +} + +void* ServiceReferenceBasePrivate::GetService(Module* module) +{ + void* s = NULL; + { + MutexLocker lock(registration->propsLock); + if (registration->available) + { + ServiceFactory* serviceFactory = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + + const int count = registration->dependents[module]; + if (count == 0) + { + if (serviceFactory) + { + const InterfaceMap im = GetServiceFromFactory(module, serviceFactory, true); + s = im.find(interfaceId)->second; + } + else + { + s = registration->GetService(interfaceId); + } + } + else + { + if (serviceFactory) + { + // return the already produced instance + s = registration->moduleServiceInstance[module][interfaceId]; + } + else + { + s = registration->GetService(interfaceId); + } + } + + if (s) + { + registration->dependents[module] = count + 1; + } + } + } + return s; +} + +InterfaceMap ServiceReferenceBasePrivate::GetServiceInterfaceMap(Module* module) +{ + InterfaceMap s; + { + MutexLocker lock(registration->propsLock); + if (registration->available) + { + ServiceFactory* serviceFactory = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + + const int count = registration->dependents[module]; + if (count == 0) + { + if (serviceFactory) + { + s = GetServiceFromFactory(module, serviceFactory, true); + } + else + { + s = registration->service; + } + } + else + { + if (serviceFactory) + { + // return the already produced instance + s = registration->moduleServiceInstance[module]; + } + else + { + s = registration->service; + } + } + + if (!s.empty()) + { + registration->dependents[module] = count + 1; + } + } + } + return s; +} + +bool ServiceReferenceBasePrivate::UngetPrototypeService(Module* module, const InterfaceMap& service) +{ + MutexLocker lock(registration->propsLock); + + ServiceRegistrationBasePrivate::ModuleToServicesMap::iterator iter = + registration->prototypeServiceInstances.find(module); + if (iter == registration->prototypeServiceInstances.end()) + { + return false; + } + + std::list& prototypeServiceMaps = iter->second; + + for (std::list::iterator imIter = prototypeServiceMaps.begin(); + imIter != prototypeServiceMaps.end(); ++imIter) + { + if (service == *imIter) + { + try + { + ServiceFactory* sf = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + sf->UngetService(module, ServiceRegistrationBase(registration), service); + } + catch (const std::exception& /*e*/) + { + US_WARN << "ServiceFactory threw an exception"; + } + prototypeServiceMaps.erase(imIter); + if (prototypeServiceMaps.empty()) + { + registration->prototypeServiceInstances.erase(iter); + } + return true; + } + } + + return false; +} + +bool ServiceReferenceBasePrivate::UngetService(Module* module, bool checkRefCounter) +{ + MutexLocker lock(registration->propsLock); + bool hadReferences = false; + bool removeService = false; + + int count= registration->dependents[module]; + if (count > 0) + { + hadReferences = true; + } + + if(checkRefCounter) + { + if (count > 1) + { + registration->dependents[module] = count - 1; + } + else if(count == 1) + { + removeService = true; + } + } + else + { + removeService = true; + } + + if (removeService) + { + InterfaceMap sfi = registration->moduleServiceInstance[module]; + registration->moduleServiceInstance.erase(module); + if (!sfi.empty()) + { + try + { + ServiceFactory* sf = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + sf->UngetService(module, ServiceRegistrationBase(registration), sfi); + } + catch (const std::exception& /*e*/) + { + US_WARN << "ServiceFactory threw an exception"; + } + } + registration->dependents.erase(module); + } + + return hadReferences; +} + +const ServicePropertiesImpl& ServiceReferenceBasePrivate::GetProperties() const +{ + return registration->properties; +} + +Any ServiceReferenceBasePrivate::GetProperty(const std::string& key, bool lock) const +{ + if (lock) + { + MutexLocker lock(registration->propsLock); + return registration->properties.Value(key); + } + else + { + return registration->properties.Value(key); + } +} + +bool ServiceReferenceBasePrivate::IsConvertibleTo(const std::string& interfaceId) const +{ + return registration->service.find(interfaceId) != registration->service.end(); +} + +US_END_NAMESPACE diff --git a/src/service/usServiceReferenceBasePrivate.h b/src/service/usServiceReferenceBasePrivate.h new file mode 100644 index 0000000000..39f9951435 --- /dev/null +++ b/src/service/usServiceReferenceBasePrivate.h @@ -0,0 +1,152 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USSERVICEREFERENCEBASEPRIVATE_H +#define USSERVICEREFERENCEBASEPRIVATE_H + +#include "usAtomicInt_p.h" + +#include "usServiceInterface.h" + +#include + +US_BEGIN_NAMESPACE + +class Any; +class Module; +class ServicePropertiesImpl; +class ServiceRegistrationBasePrivate; +class ServiceReferenceBasePrivate; + + +/** + * \ingroup MicroServices + */ +class ServiceReferenceBasePrivate +{ +public: + + ServiceReferenceBasePrivate(ServiceRegistrationBasePrivate* reg); + + ~ServiceReferenceBasePrivate(); + + /** + * Get the service object. + * + * @param module requester of service. + * @return Service requested or null in case of failure. + */ + void* GetService(Module* module); + + InterfaceMap GetServiceInterfaceMap(Module* module); + + /** + * Get new service instance. + * + * @param module requester of service. + * @return Service requested or null in case of failure. + */ + InterfaceMap GetPrototypeService(Module* module); + + /** + * Unget the service object. + * + * @param module Module who wants remove service. + * @param checkRefCounter If true decrement refence counter and remove service + * if we reach zero. If false remove service without + * checking refence counter. + * @return True if service was removed or false if only reference counter was + * decremented. + */ + bool UngetService(Module* module, bool checkRefCounter); + + /** + * Unget prototype scope service objects. + * + * @param module Module who wants to remove a prototype scope service. + * @param service The prototype scope service pointer. + * @return \c true if the service was removed, \c false otherwise. + */ + bool UngetPrototypeService(Module* module, void* service); + + bool UngetPrototypeService(Module* module, const InterfaceMap& service); + + /** + * Get all properties registered with this service. + * + * @return A ServiceProperties object containing properties or being empty + * if service has been removed. + */ + const ServicePropertiesImpl& GetProperties() const; + + /** + * Returns the property value to which the specified property key is mapped + * in the properties ServiceProperties object of the service + * referenced by this ServiceReference object. + * + *

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

+ * This method must continue to return property values after the service has + * been unregistered. This is so references to unregistered services can + * still be interrogated. + * + * @param key The property key. + * @param lock If true, access of the properties of the service + * referenced by this ServiceReference object will be + * synchronized. + * @return The property value to which the key is mapped; an invalid Any + * if there is no property named after the key. + */ + Any GetProperty(const std::string& key, bool lock) const; + + bool IsConvertibleTo(const std::string& interfaceId) const; + + /** + * Reference count for implicitly shared private implementation. + */ + AtomicInt ref; + + /** + * Link to registration object for this reference. + */ + ServiceRegistrationBasePrivate* const registration; + + /** + * The service interface id for this reference. + */ + std::string interfaceId; + +private: + + InterfaceMap GetServiceFromFactory(Module* module, ServiceFactory* factory, + bool isModuleScope); + + // purposely not implemented + ServiceReferenceBasePrivate(const ServiceReferenceBasePrivate&); + ServiceReferenceBasePrivate& operator=(const ServiceReferenceBasePrivate&); +}; + +US_END_NAMESPACE + +#endif // USSERVICEREFERENCEBASEPRIVATE_H diff --git a/src/service/usServiceRegistration.h b/src/service/usServiceRegistration.h new file mode 100644 index 0000000000..d604ee8a41 --- /dev/null +++ b/src/service/usServiceRegistration.h @@ -0,0 +1,203 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USSERVICEREGISTRATION_H +#define USSERVICEREGISTRATION_H + +#include "usServiceRegistrationBase.h" + +US_BEGIN_NAMESPACE + +/** + * \ingroup MicroServices + * + * A registered service. + * + *

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

+ * The ServiceRegistration object may be used to update the + * properties of the service or to unregister the service. + * + * @tparam S Class tyoe of the service interface + * @see ModuleContext#RegisterService() + * @remarks This class is thread safe. + */ +template +class ServiceRegistration : public ServiceRegistrationBase +{ + +public: + + /** + * Creates an invalid ServiceRegistration object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceRegistration() : ServiceRegistrationBase() + { + } + + ///@{ + /** + * Returns a ServiceReference object for a service being + * registered. + *

+ * The ServiceReference object may be shared with other + * modules. + * + * @throws std::logic_error If this + * ServiceRegistration object has already been + * unregistered or if it is invalid. + * @return ServiceReference object. + */ + ServiceReference GetReference(InterfaceT) const + { + return this->ServiceRegistrationBase::GetReference(us_service_interface_iid()); + } + ServiceReference GetReference(InterfaceT) const + { + return this->ServiceRegistrationBase::GetReference(us_service_interface_iid()); + } + ServiceReference GetReference(InterfaceT) const + { + return this->ServiceRegistrationBase::GetReference(us_service_interface_iid()); + } + ///@} + + using ServiceRegistrationBase::operator=; + + +private: + + friend class ModuleContext; + + ServiceRegistration(const ServiceRegistrationBase& base) + : ServiceRegistrationBase(base) + { + } + +}; + +/// \cond +template +class ServiceRegistration : public ServiceRegistrationBase +{ + +public: + + ServiceRegistration() : ServiceRegistrationBase() + { + } + + ServiceReference GetReference(InterfaceT) const + { + return ServiceReference(this->ServiceRegistrationBase::GetReference(us_service_interface_iid())); + } + + ServiceReference GetReference(InterfaceT) const + { + return ServiceReference(this->ServiceRegistrationBase::GetReference(us_service_interface_iid())); + } + + using ServiceRegistrationBase::operator=; + + +private: + + friend class ModuleContext; + + ServiceRegistration(const ServiceRegistrationBase& base) + : ServiceRegistrationBase(base) + { + } + +}; + +template +class ServiceRegistration : public ServiceRegistrationBase +{ + +public: + + ServiceRegistration() : ServiceRegistrationBase() + { + } + + ServiceReference GetReference() const + { + return this->GetReference(InterfaceT()); + } + + ServiceReference GetReference(InterfaceT) const + { + return ServiceReference(this->ServiceRegistrationBase::GetReference(us_service_interface_iid())); + } + + using ServiceRegistrationBase::operator=; + +private: + + friend class ModuleContext; + + ServiceRegistration(const ServiceRegistrationBase& base) + : ServiceRegistrationBase(base) + { + } + +}; + +template<> +class ServiceRegistration : public ServiceRegistrationBase +{ +public: + + /** + * Creates an invalid ServiceReference object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceRegistration() : ServiceRegistrationBase() + { + } + + ServiceRegistration(const ServiceRegistrationBase& base) + : ServiceRegistrationBase(base) + { + } + + using ServiceRegistrationBase::operator=; +}; +/// \endcond + +/** + * \ingroup MicroServices + * + * A service registration object of unknown type. + */ +typedef ServiceRegistration ServiceRegistrationU; + +US_END_NAMESPACE + +#endif // USSERVICEREGISTRATION_H diff --git a/src/service/usServiceRegistrationBase.cpp b/src/service/usServiceRegistrationBase.cpp new file mode 100644 index 0000000000..b121bb0a60 --- /dev/null +++ b/src/service/usServiceRegistrationBase.cpp @@ -0,0 +1,272 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +#include "usServiceRegistrationBase.h" +#include "usServiceRegistrationBasePrivate.h" +#include "usServiceListenerEntry_p.h" +#include "usServiceRegistry_p.h" +#include "usServiceFactory.h" + +#include "usModulePrivate.h" +#include "usCoreModuleContext_p.h" + +#include + +US_BEGIN_NAMESPACE + +typedef ServiceRegistrationBasePrivate::MutexLocker MutexLocker; + +ServiceRegistrationBase::ServiceRegistrationBase() + : d(0) +{ + +} + +ServiceRegistrationBase::ServiceRegistrationBase(const ServiceRegistrationBase& reg) + : d(reg.d) +{ + if (d) d->ref.Ref(); +} + +ServiceRegistrationBase::ServiceRegistrationBase(ServiceRegistrationBasePrivate* registrationPrivate) + : d(registrationPrivate) +{ + if (d) d->ref.Ref(); +} + +ServiceRegistrationBase::ServiceRegistrationBase(ModulePrivate* module, const InterfaceMap& service, + const ServicePropertiesImpl& props) + : d(new ServiceRegistrationBasePrivate(module, service, props)) +{ + +} + +ServiceRegistrationBase::operator bool() const +{ + return d != 0; +} + +ServiceRegistrationBase& ServiceRegistrationBase::operator=(int null) +{ + if (null == 0) + { + if (d && !d->ref.Deref()) + { + delete d; + } + d = 0; + } + return *this; +} + +ServiceRegistrationBase::~ServiceRegistrationBase() +{ + if (d && !d->ref.Deref()) + delete d; +} + +ServiceReferenceBase ServiceRegistrationBase::GetReference(const std::string& interfaceId) const +{ + if (!d) throw std::logic_error("ServiceRegistrationBase object invalid"); + if (!d->available) throw std::logic_error("Service is unregistered"); + + ServiceReferenceBase ref = d->reference; + ref.SetInterfaceId(interfaceId); + return ref; +} + +void ServiceRegistrationBase::SetProperties(const ServiceProperties& props) +{ + if (!d) throw std::logic_error("ServiceRegistrationBase object invalid"); + + MutexLocker lock(d->eventLock); + + ServiceListeners::ServiceListenerEntries before; + // TBD, optimize the locking of services + { + //MutexLocker lock2(d->module->coreCtx->globalFwLock); + + if (d->available) + { + // NYI! Optimize the MODIFIED_ENDMATCH code + int old_rank = 0; + int new_rank = 0; + + std::vector classes; + { + MutexLocker lock3(d->propsLock); + + { + const Any& any = d->properties.Value(ServiceConstants::SERVICE_RANKING()); + if (any.Type() == typeid(int)) old_rank = any_cast(any); + } + + d->module->coreCtx->listeners.GetMatchingServiceListeners(d->reference, before, false); + classes = ref_any_cast >(d->properties.Value(ServiceConstants::OBJECTCLASS())); + long int sid = any_cast(d->properties.Value(ServiceConstants::SERVICE_ID())); + d->properties = ServiceRegistry::CreateServiceProperties(props, classes, false, false, sid); + + { + const Any& any = d->properties.Value(ServiceConstants::SERVICE_RANKING()); + if (any.Type() == typeid(int)) new_rank = any_cast(any); + } + } + + if (old_rank != new_rank) + { + d->module->coreCtx->services.UpdateServiceRegistrationOrder(*this, classes); + } + } + else + { + throw std::logic_error("Service is unregistered"); + } + } + ServiceListeners::ServiceListenerEntries matchingListeners; + d->module->coreCtx->listeners.GetMatchingServiceListeners(d->reference, matchingListeners); + d->module->coreCtx->listeners.ServiceChanged(matchingListeners, + ServiceEvent(ServiceEvent::MODIFIED, d->reference), + before); + + d->module->coreCtx->listeners.ServiceChanged(before, + ServiceEvent(ServiceEvent::MODIFIED_ENDMATCH, d->reference)); +} + +void ServiceRegistrationBase::Unregister() +{ + if (!d) throw std::logic_error("ServiceRegistrationBase object invalid"); + + if (d->unregistering) return; // Silently ignore redundant unregistration. + { + MutexLocker lock(d->eventLock); + if (d->unregistering) return; + d->unregistering = true; + + if (d->available) + { + if (d->module) + { + d->module->coreCtx->services.RemoveServiceRegistration(*this); + } + } + else + { + throw std::logic_error("Service is unregistered"); + } + } + + if (d->module) + { + ServiceListeners::ServiceListenerEntries listeners; + d->module->coreCtx->listeners.GetMatchingServiceListeners(d->reference, listeners); + d->module->coreCtx->listeners.ServiceChanged( + listeners, + ServiceEvent(ServiceEvent::UNREGISTERING, d->reference)); + } + + { + MutexLocker lock(d->eventLock); + { + MutexLocker lock2(d->propsLock); + d->available = false; + InterfaceMap::const_iterator factoryIter = d->service.find("org.cppmicroservices.factory"); + if (d->module && factoryIter != d->service.end()) + { + ServiceFactory* serviceFactory = reinterpret_cast(factoryIter->second); + ServiceRegistrationBasePrivate::ModuleToServicesMap::const_iterator end = d->prototypeServiceInstances.end(); + + // unget all prototype services + for (ServiceRegistrationBasePrivate::ModuleToServicesMap::const_iterator i = d->prototypeServiceInstances.begin(); + i != end; ++i) + { + for (std::list::const_iterator listIter = i->second.begin(); + listIter != i->second.end(); ++listIter) + { + const InterfaceMap& service = *listIter; + try + { + // NYI, don't call inside lock + serviceFactory->UngetService(i->first, *this, service); + } + catch (const std::exception& /*ue*/) + { + US_WARN << "ServiceFactory UngetService implementation threw an exception"; + } + } + } + + // unget module scope services + ServiceRegistrationBasePrivate::ModuleToServiceMap::const_iterator moduleEnd = d->moduleServiceInstance.end(); + for (ServiceRegistrationBasePrivate::ModuleToServiceMap::const_iterator i = d->moduleServiceInstance.begin(); + i != moduleEnd; ++i) + { + try + { + // NYI, don't call inside lock + serviceFactory->UngetService(i->first, *this, i->second); + } + catch (const std::exception& /*ue*/) + { + US_WARN << "ServiceFactory UngetService implementation threw an exception"; + } + } + } + d->module = 0; + d->dependents.clear(); + d->service.clear(); + d->prototypeServiceInstances.clear(); + d->moduleServiceInstance.clear(); + // increment the reference count, since "d->reference" was used originally + // to keep d alive. + d->ref.Ref(); + d->reference = 0; + d->unregistering = false; + } + } +} + +bool ServiceRegistrationBase::operator<(const ServiceRegistrationBase& o) const +{ + if ((!d && !o.d) || !o.d) return false; + if (!d) return true; + return d->reference <(o.d->reference); +} + +bool ServiceRegistrationBase::operator==(const ServiceRegistrationBase& registration) const +{ + return d == registration.d; +} + +ServiceRegistrationBase& ServiceRegistrationBase::operator=(const ServiceRegistrationBase& registration) +{ + ServiceRegistrationBasePrivate* curr_d = d; + d = registration.d; + if (d) d->ref.Ref(); + + if (curr_d && !curr_d->ref.Deref()) + delete curr_d; + + return *this; +} + +US_END_NAMESPACE diff --git a/src/service/usServiceRegistrationBase.h b/src/service/usServiceRegistrationBase.h new file mode 100644 index 0000000000..f4dafda78f --- /dev/null +++ b/src/service/usServiceRegistrationBase.h @@ -0,0 +1,223 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USSERVICEREGISTRATIONBASE_H +#define USSERVICEREGISTRATIONBASE_H + +#include "usServiceProperties.h" +#include "usServiceReference.h" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4396) +#endif + +US_BEGIN_NAMESPACE + +class ModulePrivate; +class ServiceRegistrationBasePrivate; +class ServicePropertiesImpl; + +/** + * \ingroup MicroServices + * + * A registered service. + * + *

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

+ * The ServiceRegistrationBase object may be used to update the + * properties of the service or to unregister the service. + * + * \note This class is provided as public API for low-level service management only. + * In almost all cases you should use the template ServiceRegistration instead. + * + * @see ModuleContext#RegisterService() + * @remarks This class is thread safe. + */ +class US_EXPORT ServiceRegistrationBase { + +public: + + ServiceRegistrationBase(const ServiceRegistrationBase& reg); + + /** + * A boolean conversion operator converting this ServiceRegistrationBase object + * to \c true if it is valid and to \c false otherwise. A SeriveRegistration + * object is invalid if it was default-constructed or was invalidated by + * assigning 0 to it. + * + * \see operator=(int) + * + * \return \c true if this ServiceRegistrationBase object is valid, \c false + * otherwise. + */ + operator bool() const; + + /** + * Releases any resources held or locked by this + * ServiceRegistrationBase and renders it invalid. + * + * \return This ServiceRegistrationBase object. + */ + ServiceRegistrationBase& operator=(int null); + + ~ServiceRegistrationBase(); + + /** + * Returns a ServiceReference object for a service being + * registered. + *

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

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

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

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

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

    + *
  1. The service is removed from the framework service registry so that + * it can no longer be obtained. + *
  2. A service event of type ServiceEvent#UNREGISTERING is fired + * so that modules using this service can release their use of the service. + * Once delivery of the service event is complete, the + * ServiceRegistrationBase objects for the service may no longer be + * used to get a service object for the service. + *
  3. For each module whose use count for this service is greater than + * zero:
    + * The module's use count for this service is set to zero.
    + * If the service was registered with a ServiceFactory object, the + * ServiceFactory#UngetService method is called to release + * the service object for the module. + *
+ * + * @throws std::logic_error If this + * ServiceRegistrationBase object has already been + * unregistered or if it is invalid. + * @see ModuleContext#UngetService + * @see ServiceFactory#UngetService + */ + void Unregister(); + + /** + * Compare two ServiceRegistrationBase objects. + * + * If both ServiceRegistrationBase objects are valid, the comparison is done + * using the underlying ServiceReference object. Otherwise, this ServiceRegistrationBase + * object is less than the other object if and only if this object is invalid and + * the other object is valid. + * + * @param o The ServiceRegistrationBase object to compare with. + * @return \c true if this ServiceRegistrationBase object is less than the other object. + */ + bool operator<(const ServiceRegistrationBase& o) const; + + bool operator==(const ServiceRegistrationBase& registration) const; + + ServiceRegistrationBase& operator=(const ServiceRegistrationBase& registration); + + +private: + + friend class ServiceRegistry; + friend class ServiceReferenceBasePrivate; + + template friend class ServiceRegistration; + + US_HASH_FUNCTION_FRIEND(ServiceRegistrationBase); + + /** + * Creates an invalid ServiceRegistrationBase object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceRegistrationBase(); + + ServiceRegistrationBase(ServiceRegistrationBasePrivate* registrationPrivate); + + ServiceRegistrationBase(ModulePrivate* module, const InterfaceMap& service, + const ServicePropertiesImpl& props); + + ServiceRegistrationBasePrivate* d; + +}; + +US_END_NAMESPACE + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +US_HASH_FUNCTION_NAMESPACE_BEGIN +US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceRegistrationBase)) + return US_HASH_FUNCTION(US_PREPEND_NAMESPACE(ServiceRegistrationBasePrivate)*, arg.d); +US_HASH_FUNCTION_END +US_HASH_FUNCTION_NAMESPACE_END + + +inline std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceRegistrationBase)& /*reg*/) +{ + return os << "US_PREPEND_NAMESPACE(ServiceRegistrationBase) object"; +} + +#endif // USSERVICEREGISTRATIONBASE_H diff --git a/src/service/usServiceRegistrationBasePrivate.cpp b/src/service/usServiceRegistrationBasePrivate.cpp new file mode 100644 index 0000000000..078ee6fb37 --- /dev/null +++ b/src/service/usServiceRegistrationBasePrivate.cpp @@ -0,0 +1,76 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usServiceRegistrationBasePrivate.h" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4355) +#endif + +US_BEGIN_NAMESPACE + +ServiceRegistrationBasePrivate::ServiceRegistrationBasePrivate( + ModulePrivate* module, const InterfaceMap& service, + const ServicePropertiesImpl& props) + : ref(0), service(service), module(module), reference(this), + properties(props), available(true), unregistering(false) +{ + // The reference counter is initialized to 0 because it will be + // incremented by the "reference" member. +} + +ServiceRegistrationBasePrivate::~ServiceRegistrationBasePrivate() +{ + +} + +bool ServiceRegistrationBasePrivate::IsUsedByModule(Module* p) const +{ + return (dependents.find(p) != dependents.end()) || + (prototypeServiceInstances.find(p) != prototypeServiceInstances.end()); +} + +const InterfaceMap& ServiceRegistrationBasePrivate::GetInterfaces() const +{ + return service; +} + +void* ServiceRegistrationBasePrivate::GetService(const std::string& interfaceId) const +{ + if (interfaceId.empty() && service.size() > 0) + { + return service.begin()->second; + } + + InterfaceMap::const_iterator iter = service.find(interfaceId); + if (iter != service.end()) + { + return iter->second; + } + return NULL; +} + +US_END_NAMESPACE + +#ifdef _MSC_VER +#pragma warning(pop) +#endif diff --git a/src/service/usServiceRegistrationBasePrivate.h b/src/service/usServiceRegistrationBasePrivate.h new file mode 100644 index 0000000000..504907f61f --- /dev/null +++ b/src/service/usServiceRegistrationBasePrivate.h @@ -0,0 +1,152 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USSERVICEREGISTRATIONBASEPRIVATE_H +#define USSERVICEREGISTRATIONBASEPRIVATE_H + +#include "usServiceInterface.h" +#include "usServiceReference.h" +#include "usServicePropertiesImpl_p.h" +#include "usAtomicInt_p.h" + +US_BEGIN_NAMESPACE + +class ModulePrivate; +class ServiceRegistrationBase; + +/** + * \ingroup MicroServices + */ +class ServiceRegistrationBasePrivate +{ + +protected: + + friend class ServiceRegistrationBase; + + // The ServiceReferenceBasePrivate class holds a pointer to a + // ServiceRegistrationBasePrivate instance and needs to manipulate + // its reference count. This way it can keep the ServiceRegistrationBasePrivate + // instance alive and keep returning service properties for + // unregistered service instances. + friend class ServiceReferenceBasePrivate; + + /** + * Reference count for implicitly shared private implementation. + */ + AtomicInt ref; + + /** + * Service or ServiceFactory object. + */ + InterfaceMap service; + +public: + + typedef Mutex MutexType; + typedef MutexLock MutexLocker; + + typedef US_UNORDERED_MAP_TYPE ModuleToRefsMap; + typedef US_UNORDERED_MAP_TYPE ModuleToServiceMap; + typedef US_UNORDERED_MAP_TYPE > ModuleToServicesMap; + + /** + * Modules dependent on this service. Integer is used as + * reference counter, counting number of unbalanced getService(). + */ + ModuleToRefsMap dependents; + + /** + * Object instances that a prototype factory has produced. + */ + ModuleToServicesMap prototypeServiceInstances; + + /** + * Object instance with module scope that a factory may have produced. + */ + ModuleToServiceMap moduleServiceInstance; + + /** + * Module registering this service. + */ + ModulePrivate* module; + + /** + * Reference object to this service registration. + */ + ServiceReferenceBase reference; + + /** + * Service properties. + */ + ServicePropertiesImpl properties; + + /** + * Is service available. I.e., if true then holders + * of a ServiceReference for the service are allowed to get it. + */ + volatile bool available; + + /** + * Avoid recursive unregistrations. I.e., if true then + * unregistration of this service has started but is not yet + * finished. + */ + volatile bool unregistering; + + /** + * Lock object for synchronous event delivery. + */ + MutexType eventLock; + + // needs to be recursive + MutexType propsLock; + + ServiceRegistrationBasePrivate(ModulePrivate* module, const InterfaceMap& service, + const ServicePropertiesImpl& props); + + ~ServiceRegistrationBasePrivate(); + + /** + * Check if a module uses this service + * + * @param p Module to check + * @return true if module uses this service + */ + bool IsUsedByModule(Module* m) const; + + const InterfaceMap& GetInterfaces() const; + + void* GetService(const std::string& interfaceId) const; + +private: + + // purposely not implemented + ServiceRegistrationBasePrivate(const ServiceRegistrationBasePrivate&); + ServiceRegistrationBasePrivate& operator=(const ServiceRegistrationBasePrivate&); + +}; + +US_END_NAMESPACE + + +#endif // USSERVICEREGISTRATIONBASEPRIVATE_H diff --git a/src/service/usServiceRegistry.cpp b/src/service/usServiceRegistry.cpp new file mode 100644 index 0000000000..92222eba19 --- /dev/null +++ b/src/service/usServiceRegistry.cpp @@ -0,0 +1,322 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +#include +#include + +#include "usServiceRegistry_p.h" +#include "usServiceFactory.h" +#include "usPrototypeServiceFactory.h" +#include "usServiceRegistry_p.h" +#include "usServiceRegistrationBasePrivate.h" +#include "usModulePrivate.h" +#include "usCoreModuleContext_p.h" + + +US_BEGIN_NAMESPACE + +typedef MutexLock MutexLocker; + + +ServicePropertiesImpl ServiceRegistry::CreateServiceProperties(const ServiceProperties& in, + const std::vector& classes, + bool isFactory, bool isPrototypeFactory, + long sid) +{ + static long nextServiceID = 1; + ServiceProperties props(in); + + if (!classes.empty()) + { + props.insert(std::make_pair(ServiceConstants::OBJECTCLASS(), classes)); + } + + props.insert(std::make_pair(ServiceConstants::SERVICE_ID(), sid != -1 ? sid : nextServiceID++)); + + if (isPrototypeFactory) + { + props.insert(std::make_pair(ServiceConstants::SERVICE_SCOPE(), ServiceConstants::SCOPE_PROTOTYPE())); + } + else if (isFactory) + { + props.insert(std::make_pair(ServiceConstants::SERVICE_SCOPE(), ServiceConstants::SCOPE_MODULE())); + } + else + { + props.insert(std::make_pair(ServiceConstants::SERVICE_SCOPE(), ServiceConstants::SCOPE_SINGLETON())); + } + + return ServicePropertiesImpl(props); +} + +ServiceRegistry::ServiceRegistry(CoreModuleContext* coreCtx) + : core(coreCtx) +{ + +} + +ServiceRegistry::~ServiceRegistry() +{ + Clear(); +} + +void ServiceRegistry::Clear() +{ + services.clear(); + serviceRegistrations.clear(); + classServices.clear(); + core = 0; +} + +ServiceRegistrationBase ServiceRegistry::RegisterService(ModulePrivate* module, + const InterfaceMap& service, + const ServiceProperties& properties) +{ + if (service.empty()) + { + throw std::invalid_argument("Can't register empty InterfaceMap as a service"); + } + + // Check if we got a service factory + bool isFactory = service.count("org.cppmicroservices.factory") > 0; + bool isPrototypeFactory = (isFactory ? dynamic_cast(reinterpret_cast(service.find("org.cppmicroservices.factory")->second)) != NULL : false); + + std::vector classes; + // Check if service implements claimed classes and that they exist. + for (InterfaceMap::const_iterator i = service.begin(); + i != service.end(); ++i) + { + if (i->first.empty() || (!isFactory && i->second == NULL)) + { + throw std::invalid_argument("Can't register as null class"); + } + classes.push_back(i->first); + } + + ServiceRegistrationBase res(module, service, + CreateServiceProperties(properties, classes, isFactory, isPrototypeFactory)); + { + MutexLocker lock(mutex); + services.insert(std::make_pair(res, classes)); + serviceRegistrations.push_back(res); + for (std::vector::const_iterator i = classes.begin(); + i != classes.end(); ++i) + { + std::vector& s = classServices[*i]; + std::vector::iterator ip = + std::lower_bound(s.begin(), s.end(), res); + s.insert(ip, res); + } + } + + ServiceReferenceBase r = res.GetReference(std::string()); + ServiceListeners::ServiceListenerEntries listeners; + module->coreCtx->listeners.GetMatchingServiceListeners(r, listeners); + module->coreCtx->listeners.ServiceChanged(listeners, + ServiceEvent(ServiceEvent::REGISTERED, r)); + return res; +} + +void ServiceRegistry::UpdateServiceRegistrationOrder(const ServiceRegistrationBase& sr, + const std::vector& classes) +{ + MutexLocker lock(mutex); + for (std::vector::const_iterator i = classes.begin(); + i != classes.end(); ++i) + { + std::vector& s = classServices[*i]; + s.erase(std::remove(s.begin(), s.end(), sr), s.end()); + s.insert(std::lower_bound(s.begin(), s.end(), sr), sr); + } +} + +void ServiceRegistry::Get(const std::string& clazz, + std::vector& serviceRegs) const +{ + MutexLocker lock(mutex); + MapClassServices::const_iterator i = classServices.find(clazz); + if (i != classServices.end()) + { + serviceRegs = i->second; + } +} + +ServiceReferenceBase ServiceRegistry::Get(ModulePrivate* module, const std::string& clazz) const +{ + MutexLocker lock(mutex); + try + { + std::vector srs; + Get_unlocked(clazz, "", module, srs); + US_DEBUG << "get service ref " << clazz << " for module " + << module->info.name << " = " << srs.size() << " refs"; + + if (!srs.empty()) + { + return srs.back(); + } + } + catch (const std::invalid_argument& ) + { } + + return ServiceReferenceBase(); +} + +void ServiceRegistry::Get(const std::string& clazz, const std::string& filter, + ModulePrivate* module, std::vector& res) const +{ + MutexLocker lock(mutex); + Get_unlocked(clazz, filter, module, res); +} + +void ServiceRegistry::Get_unlocked(const std::string& clazz, const std::string& filter, + ModulePrivate* /*module*/, std::vector& res) const +{ + std::vector::const_iterator s; + std::vector::const_iterator send; + std::vector v; + LDAPExpr ldap; + if (clazz.empty()) + { + if (!filter.empty()) + { + ldap = LDAPExpr(filter); + LDAPExpr::ObjectClassSet matched; + if (ldap.GetMatchedObjectClasses(matched)) + { + v.clear(); + for(LDAPExpr::ObjectClassSet::const_iterator className = matched.begin(); + className != matched.end(); ++className) + { + MapClassServices::const_iterator i = classServices.find(*className); + if (i != classServices.end()) + { + std::copy(i->second.begin(), i->second.end(), std::back_inserter(v)); + } + } + if (!v.empty()) + { + s = v.begin(); + send = v.end(); + } + else + { + return; + } + } + else + { + s = serviceRegistrations.begin(); + send = serviceRegistrations.end(); + } + } + else + { + s = serviceRegistrations.begin(); + send = serviceRegistrations.end(); + } + } + else + { + MapClassServices::const_iterator it = classServices.find(clazz); + if (it != classServices.end()) + { + s = it->second.begin(); + send = it->second.end(); + } + else + { + return; + } + if (!filter.empty()) + { + ldap = LDAPExpr(filter); + } + } + + for (; s != send; ++s) + { + ServiceReferenceBase sri = s->GetReference(clazz); + + if (filter.empty() || ldap.Evaluate(s->d->properties, false)) + { + res.push_back(sri); + } + } +} + +void ServiceRegistry::RemoveServiceRegistration(const ServiceRegistrationBase& sr) +{ + MutexLocker lock(mutex); + + const std::vector& classes = ref_any_cast >( + sr.d->properties.Value(ServiceConstants::OBJECTCLASS())); + services.erase(sr); + serviceRegistrations.erase(std::remove(serviceRegistrations.begin(), serviceRegistrations.end(), sr), + serviceRegistrations.end()); + for (std::vector::const_iterator i = classes.begin(); + i != classes.end(); ++i) + { + std::vector& s = classServices[*i]; + if (s.size() > 1) + { + s.erase(std::remove(s.begin(), s.end(), sr), s.end()); + } + else + { + classServices.erase(*i); + } + } +} + +void ServiceRegistry::GetRegisteredByModule(ModulePrivate* p, + std::vector& res) const +{ + MutexLocker lock(mutex); + + for (std::vector::const_iterator i = serviceRegistrations.begin(); + i != serviceRegistrations.end(); ++i) + { + if (i->d->module == p) + { + res.push_back(*i); + } + } +} + +void ServiceRegistry::GetUsedByModule(Module* p, + std::vector& res) const +{ + MutexLocker lock(mutex); + + for (std::vector::const_iterator i = serviceRegistrations.begin(); + i != serviceRegistrations.end(); ++i) + { + if (i->d->IsUsedByModule(p)) + { + res.push_back(*i); + } + } +} + +US_END_NAMESPACE diff --git a/src/service/usServiceRegistry_p.h b/src/service/usServiceRegistry_p.h new file mode 100644 index 0000000000..9d780ab707 --- /dev/null +++ b/src/service/usServiceRegistry_p.h @@ -0,0 +1,185 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USSERVICEREGISTRY_H +#define USSERVICEREGISTRY_H + +#include "usServiceInterface.h" +#include "usServiceRegistration.h" + +#include "usThreads_p.h" + +US_BEGIN_NAMESPACE + +class CoreModuleContext; +class ModulePrivate; +class ServicePropertiesImpl; + + +/** + * Here we handle all the CppMicroServices services that are registered. + */ +class ServiceRegistry +{ + +public: + + typedef Mutex MutexType; + + mutable MutexType mutex; + + /** + * Creates a new ServiceProperties object containing in + * with the keys converted to lower case. + * + * @param classes A list of class names which will be added to the + * created ServiceProperties object under the key + * ModuleConstants::OBJECTCLASS. + * @param sid A service id which will be used instead of a default one. + */ + static ServicePropertiesImpl CreateServiceProperties(const ServiceProperties& in, + const std::vector& classes = std::vector(), + bool isFactory = false, bool isPrototypeFactory = false, long sid = -1); + + typedef US_UNORDERED_MAP_TYPE > MapServiceClasses; + typedef US_UNORDERED_MAP_TYPE > MapClassServices; + + /** + * All registered services in the current framework. + * Mapping of registered service to class names under which + * the service is registerd. + */ + MapServiceClasses services; + + std::vector serviceRegistrations; + + /** + * Mapping of classname to registered service. + * The List of registered services are ordered with the highest + * ranked service first. + */ + MapClassServices classServices; + + CoreModuleContext* core; + + ServiceRegistry(CoreModuleContext* coreCtx); + + ~ServiceRegistry(); + + void Clear(); + + /** + * Register a service in the framework wide register. + * + * @param module The module registering the service. + * @param classes The class names under which the service can be located. + * @param service The service object. + * @param properties The properties for this service. + * @return A ServiceRegistration object. + * @exception std::invalid_argument If one of the following is true: + *
    + *
  • The service object is 0.
  • + *
  • The service parameter is not a ServiceFactory or an + * instance of all the named classes in the classes parameter.
  • + *
+ */ + ServiceRegistrationBase RegisterService(ModulePrivate* module, + const InterfaceMap& service, + const ServiceProperties& properties); + + /** + * Service ranking changed, reorder registered services + * according to ranking. + * + * @param serviceRegistration The ServiceRegistrationPrivate object. + * @param rank New rank of object. + */ + void UpdateServiceRegistrationOrder(const ServiceRegistrationBase& sr, + const std::vector& classes); + + /** + * Get all services implementing a certain class. + * Only used internally by the framework. + * + * @param clazz The class name of the requested service. + * @return A sorted list of {@link ServiceRegistrationPrivate} objects. + */ + void Get(const std::string& clazz, std::vector& serviceRegs) const; + + /** + * Get a service implementing a certain class. + * + * @param module The module requesting reference + * @param clazz The class name of the requested service. + * @return A {@link ServiceReference} object. + */ + ServiceReferenceBase Get(ModulePrivate* module, const std::string& clazz) const; + + /** + * Get all services implementing a certain class and then + * filter these with a property filter. + * + * @param clazz The class name of requested service. + * @param filter The property filter. + * @param module The module requesting reference. + * @return A list of {@link ServiceReference} object. + */ + void Get(const std::string& clazz, const std::string& filter, + ModulePrivate* module, std::vector& serviceRefs) const; + + /** + * Remove a registered service. + * + * @param sr The ServiceRegistration object that is registered. + */ + void RemoveServiceRegistration(const ServiceRegistrationBase& sr) ; + + /** + * Get all services that a module has registered. + * + * @param p The module + * @return A set of {@link ServiceRegistration} objects + */ + void GetRegisteredByModule(ModulePrivate* m, std::vector& serviceRegs) const; + + /** + * Get all services that a module uses. + * + * @param p The module + * @return A set of {@link ServiceRegistration} objects + */ + void GetUsedByModule(Module* m, std::vector& serviceRegs) const; + +private: + + void Get_unlocked(const std::string& clazz, const std::string& filter, + ModulePrivate* module, std::vector& serviceRefs) const; + + // purposely not implemented + ServiceRegistry(const ServiceRegistry&); + ServiceRegistry& operator=(const ServiceRegistry&); + +}; + +US_END_NAMESPACE + +#endif // USSERVICEREGISTRY_H diff --git a/src/service/usServiceTracker.h b/src/service/usServiceTracker.h new file mode 100644 index 0000000000..1dee7e7eec --- /dev/null +++ b/src/service/usServiceTracker.h @@ -0,0 +1,600 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USSERVICETRACKER_H +#define USSERVICETRACKER_H + +#include + +#include "usServiceReference.h" +#include "usServiceTrackerCustomizer.h" +#include "usLDAPFilter.h" + +US_BEGIN_NAMESPACE + +template class TrackedService; +template class ServiceTrackerPrivate; +class ModuleContext; + +/** + * \ingroup MicroServices + * + * A base class template for type traits for objects tracked by a + * ServiceTracker instance. It provides the \c TrackedType typedef + * and two dummy method definitions. + * + * Tracked type traits (TTT) classes must additionally provide the + * following methods: + * + *
    + *
  • static bool IsValid(const TrackedType& t) Returns \c true if \c t is a valid object, \c false otherwise.
  • + *
  • static void Dispose(TrackedType& t) Clears any resources held by the tracked object \c t.
  • + *
  • static TrackedType DefaultValue() Returns the default value for newly created tracked objects.
  • + *
+ * + * @tparam T The type of the tracked object. + * @tparam TTT The tracked type traits class deriving from this class. + * + * @see ServiceTracker + */ +template +struct TrackedTypeTraitsBase +{ + typedef T TrackedType; + + // Needed for S == void + static TrackedType ConvertToTrackedType(const InterfaceMap&) + { + throw std::runtime_error("A custom ServiceTrackerCustomizer instance is required for custom tracked objects."); + return TTT::DefaultValue(); + } + + // Needed for S != void + static TrackedType ConvertToTrackedType(void*) + { + throw std::runtime_error("A custom ServiceTrackerCustomizer instance is required for custom tracked objects."); + return TTT::DefaultValue(); + } +}; + +/// \cond +template +struct TrackedTypeTraits; +/// \endcond + +/** + * \ingroup MicroServices + * + * Default type traits for custom tracked objects of pointer type. + * + * Use this tracked type traits template for custom tracked objects of + * pointer type with the ServiceTracker class. + * + * @tparam S The type of the service being tracked. + * @tparam T The type of the tracked object. + */ +template +struct TrackedTypeTraits : public TrackedTypeTraitsBase > +{ + typedef T* TrackedType; + + static bool IsValid(const TrackedType& t) + { + return t != NULL; + } + + static TrackedType DefaultValue() + { + return NULL; + } + + static void Dispose(TrackedType& t) + { + t = 0; + } +}; + +/// \cond +template +struct TrackedTypeTraits +{ + typedef S* TrackedType; + + static bool IsValid(const TrackedType& t) + { + return t != NULL; + } + + static TrackedType DefaultValue() + { + return NULL; + } + + static void Dispose(TrackedType& t) + { + t = 0; + } + + static TrackedType ConvertToTrackedType(S* s) + { + return s; + } +}; +/// \endcond + +/// \cond +/* + * This specialization is "special" because the tracked type is not + * void* (as specified in the second template parameter) but InterfaceMap. + * This is in line with the ModuleContext::GetService(...) overloads to + * return either S* or InterfaceMap dependening on the template parameter. + */ +template<> +struct TrackedTypeTraits +{ + typedef InterfaceMap TrackedType; + + static bool IsValid(const TrackedType& t) + { + return !t.empty(); + } + + static TrackedType DefaultValue() + { + return TrackedType(); + } + + static void Dispose(TrackedType& t) + { + t.clear(); + } + + static TrackedType ConvertToTrackedType(const InterfaceMap& im) + { + return im; + } +}; +/// \endcond + +/** + * \ingroup MicroServices + * + * The ServiceTracker class simplifies using services from the + * framework's service registry. + *

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

+ * The GetServiceReferences method can be called to get references + * to the services being tracked. The GetService and + * GetServices methods can be called to get the service objects for + * the tracked service. + * + * \note The ServiceTracker class is thread-safe. It does not call a + * ServiceTrackerCustomizer while holding any locks. + * ServiceTrackerCustomizer implementations must also be + * thread-safe. + * + * Customization of the services to be tracked requires a custom tracked type traits + * class if the custom tracked type is not a pointer type. To customize a tracked + * service using a custom type with value-semantics like + * \snippet uServices-servicetracker/main.cpp tt + * the custom tracked type traits class should look like this: + * \snippet uServices-servicetracker/main.cpp ttt + * + * For a custom tracked type, a ServiceTrackerCustomizer is required, which knows + * how to associate the tracked service with the custom tracked type: + * \snippet uServices-servicetracker/main.cpp customizer + * The custom tracking type traits class and customizer can now be used to instantiate + * a ServiceTracker: + * \snippet uServices-servicetracker/main.cpp tracker + * + * If the custom tracked type is a pointer type, a suitable tracked type traits + * template is provided by the framework and only a ServiceTrackerCustomizer needs + * to be provided: + * \snippet uServices-servicetracker/main.cpp tracker2 + * + * + * @tparam S The type of the service being tracked. The type S* must be an + * assignable datatype. Further, if the + * ServiceTracker(ModuleContext*, ServiceTrackerCustomizer*) + * constructor is used, the type must have an associated interface id via + * #US_DECLARE_SERVICE_INTERFACE. + * @tparam TTT Type traits of the tracked object. The type traits class provides + * information about the customized service object, see TrackedTypeTraitsBase. + * + * @remarks This class is thread safe. + */ +template > +class ServiceTracker : protected ServiceTrackerCustomizer +{ +public: + + /// The type of the service being tracked + typedef S ServiceT; + /// The type of the tracked object + typedef typename TTT::TrackedType T; + + typedef ServiceReference ServiceReferenceT; + + typedef std::map,T> TrackingMap; + + ~ServiceTracker(); + + /** + * Create a ServiceTracker on the specified + * ServiceReference. + * + *

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

+ * Services registered under the specified class name will be tracked by + * this ServiceTracker. + * + * @param context The ModuleContext against which the tracking + * is done. + * @param clazz The class name of the services to be tracked. + * @param customizer The customizer object to call when services are added, + * modified, or removed in this ServiceTracker. If + * customizer is null, then this + * ServiceTracker will be used as the + * ServiceTrackerCustomizer and this + * ServiceTracker will call the + * ServiceTrackerCustomizer methods on itself. + */ + ServiceTracker(ModuleContext* context, const std::string& clazz, + ServiceTrackerCustomizer* customizer = 0); + + /** + * 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::vector& refs) const; + + /** + * Returns a ServiceReference for one of the services being + * tracked by this ServiceTracker. + * + *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ * This method is called after a service is no longer being tracked by the + * ServiceTracker. + * + * @param reference The reference to the service that has been removed. + * @param service The service object for the specified referenced service. + */ + virtual void RemovedService(const ServiceReferenceT& reference, T service) = 0; +}; + +US_END_NAMESPACE + +#endif // USSERVICETRACKERCUSTOMIZER_H diff --git a/src/service/usServiceTrackerPrivate.h b/src/service/usServiceTrackerPrivate.h new file mode 100644 index 0000000000..0d0d4f3efa --- /dev/null +++ b/src/service/usServiceTrackerPrivate.h @@ -0,0 +1,172 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USSERVICETRACKERPRIVATE_H +#define USSERVICETRACKERPRIVATE_H + +#include "usServiceReference.h" +#include "usLDAPFilter.h" + + +US_BEGIN_NAMESPACE + +/** + * \ingroup MicroServices + */ +template +class ServiceTrackerPrivate : US_DEFAULT_THREADING > +{ + +public: + + typedef typename TTT::TrackedType T; + + ServiceTrackerPrivate(ServiceTracker* st, + ModuleContext* context, + const ServiceReference& reference, + ServiceTrackerCustomizer* customizer); + + ServiceTrackerPrivate(ServiceTracker* st, + ModuleContext* context, const std::string& clazz, + ServiceTrackerCustomizer* customizer); + + ServiceTrackerPrivate(ServiceTracker* st, + ModuleContext* context, const LDAPFilter& filter, + ServiceTrackerCustomizer* customizer); + + ~ServiceTrackerPrivate(); + + /** + * Returns the list of initial ServiceReferences that will be + * tracked by this ServiceTracker. + * + * @param className The class name with which the service was registered, or + * null for all services. + * @param filterString The filter criteria or null for all + * services. + * @return The list of initial ServiceReferences. + * @throws std::invalid_argument If the specified filterString has an + * invalid syntax. + */ + std::vector > GetInitialReferences(const std::string& className, + const std::string& filterString); + + void GetServiceReferences_unlocked(std::vector >& refs, TrackedService* t) const; + + /* set this to true to compile in debug messages */ + static const bool DEBUG_OUTPUT; // = false; + + /** + * The Module Context used by this ServiceTracker. + */ + ModuleContext* const context; + + /** + * The filter used by this ServiceTracker which specifies the + * search criteria for the services to track. + */ + LDAPFilter filter; + + /** + * The ServiceTrackerCustomizer for this tracker. + */ + ServiceTrackerCustomizer* customizer; + + /** + * Filter string for use when adding the ServiceListener. If this field is + * set, then certain optimizations can be taken since we don't have a user + * supplied filter. + */ + std::string listenerFilter; + + /** + * Class name to be tracked. If this field is set, then we are tracking by + * class name. + */ + std::string trackClass; + + /** + * Reference to be tracked. If this field is set, then we are tracking a + * single ServiceReference. + */ + ServiceReference trackReference; + + /** + * Tracked services: ServiceReference -> customized Object and + * ServiceListenerEntry object + */ + TrackedService* trackedService; + + /** + * Accessor method for the current TrackedService object. This method is only + * intended to be used by the unsynchronized methods which do not modify the + * trackedService field. + * + * @return The current Tracked object. + */ + TrackedService* Tracked() const; + + /** + * Called by the TrackedService object whenever the set of tracked services is + * modified. Clears the cache. + */ + /* + * This method must not be synchronized since it is called by TrackedService while + * TrackedService is synchronized. We don't want synchronization interactions + * between the listener thread and the user thread. + */ + void Modified(); + + /** + * Cached ServiceReference for getServiceReference. + */ + mutable ServiceReference cachedReference; + + /** + * Cached service object for GetService. + */ + mutable T cachedService; + + +private: + + inline ServiceTracker* q_func() + { + return static_cast *>(q_ptr); + } + + inline const ServiceTracker* q_func() const + { + return static_cast *>(q_ptr); + } + + friend class ServiceTracker; + + ServiceTracker * const q_ptr; + +}; + +US_END_NAMESPACE + +#include "usServiceTrackerPrivate.tpp" + +#endif // USSERVICETRACKERPRIVATE_H diff --git a/src/service/usServiceTrackerPrivate.tpp b/src/service/usServiceTrackerPrivate.tpp new file mode 100644 index 0000000000..e4f7fd6e2b --- /dev/null +++ b/src/service/usServiceTrackerPrivate.tpp @@ -0,0 +1,155 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#include "usTrackedService_p.h" + +#include "usModuleContext.h" +#include "usLDAPFilter.h" + +#include + +US_BEGIN_NAMESPACE + +template +const bool ServiceTrackerPrivate::DEBUG_OUTPUT = true; + +template +ServiceTrackerPrivate::ServiceTrackerPrivate( + ServiceTracker* st, ModuleContext* context, + const ServiceReference& reference, + ServiceTrackerCustomizer* customizer) + : context(context), customizer(customizer), trackReference(reference), + trackedService(0), cachedReference(), cachedService(TTT::DefaultValue()), q_ptr(st) +{ + this->customizer = customizer ? customizer : q_func(); + std::stringstream ss; + ss << "(" << ServiceConstants::SERVICE_ID() << "=" + << any_cast(reference.GetProperty(ServiceConstants::SERVICE_ID())) << ")"; + this->listenerFilter = ss.str(); + try + { + this->filter = LDAPFilter(listenerFilter); + } + catch (const std::invalid_argument& e) + { + /* + * we could only get this exception if the ServiceReference was + * invalid + */ + std::invalid_argument ia(std::string("unexpected std::invalid_argument exception: ") + e.what()); + throw ia; + } +} + +template +ServiceTrackerPrivate::ServiceTrackerPrivate( + ServiceTracker* st, + ModuleContext* context, const std::string& clazz, + ServiceTrackerCustomizer* customizer) + : context(context), customizer(customizer), trackClass(clazz), + trackReference(), trackedService(0), cachedReference(), + cachedService(TTT::DefaultValue()), q_ptr(st) +{ + this->customizer = customizer ? customizer : q_func(); + this->listenerFilter = std::string("(") + US_PREPEND_NAMESPACE(ServiceConstants)::OBJECTCLASS() + "=" + + clazz + ")"; + try + { + this->filter = LDAPFilter(listenerFilter); + } + catch (const std::invalid_argument& e) + { + /* + * we could only get this exception if the clazz argument was + * malformed + */ + std::invalid_argument ia( + std::string("unexpected std::invalid_argument exception: ") + e.what()); + throw ia; + } +} + +template +ServiceTrackerPrivate::ServiceTrackerPrivate( + ServiceTracker* st, + ModuleContext* context, const LDAPFilter& filter, + ServiceTrackerCustomizer* customizer) + : context(context), filter(filter), customizer(customizer), + listenerFilter(filter.ToString()), trackReference(), + trackedService(0), cachedReference(), cachedService(TTT::DefaultValue()), q_ptr(st) +{ + this->customizer = customizer ? customizer : q_func(); + if (context == 0) + { + throw std::invalid_argument("The module context cannot be null."); + } +} + +template +ServiceTrackerPrivate::~ServiceTrackerPrivate() +{ + +} + +template +std::vector > ServiceTrackerPrivate::GetInitialReferences( + const std::string& className, const std::string& filterString) +{ + std::vector > result; + std::vector refs = context->GetServiceReferences(className, filterString); + for(std::vector::const_iterator iter = refs.begin(); + iter != refs.end(); ++iter) + { + ServiceReference ref(*iter); + if (ref) + { + result.push_back(ref); + } + } + return result; +} + +template +void ServiceTrackerPrivate::GetServiceReferences_unlocked(std::vector >& 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 */ + TTT::Dispose(cachedService); /* clear cached value */ + US_DEBUG(DEBUG_OUTPUT) << "ServiceTracker::Modified(): " << filter; +} + +US_END_NAMESPACE diff --git a/src/service/usTrackedService.tpp b/src/service/usTrackedService.tpp new file mode 100644 index 0000000000..8851affbbe --- /dev/null +++ b/src/service/usTrackedService.tpp @@ -0,0 +1,124 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +US_BEGIN_NAMESPACE + +template +TrackedService::TrackedService(ServiceTracker* serviceTracker, + ServiceTrackerCustomizer* customizer) + : serviceTracker(serviceTracker), customizer(customizer) +{ + +} + +template +void TrackedService::ServiceChanged(const ServiceEvent event) +{ + /* + * Check if we had a delayed call (which could happen when we + * close). + */ + if (this->closed) + { + return; + } + + ServiceReference reference = event.GetServiceReference(InterfaceT()); + US_DEBUG(serviceTracker->d->DEBUG_OUTPUT) << "TrackedService::ServiceChanged[" + << event.GetType() << "]: " << reference; + + switch (event.GetType()) + { + case ServiceEvent::REGISTERED : + case ServiceEvent::MODIFIED : + { + if (!serviceTracker->d->listenerFilter.empty()) + { // service listener added with filter + this->Track(reference, event); + /* + * If the customizer throws an unchecked exception, it + * is safe to let it propagate + */ + } + else + { // service listener added without filter + if (serviceTracker->d->filter.Match(reference)) + { + this->Track(reference, event); + /* + * If the customizer throws an unchecked exception, + * it is safe to let it propagate + */ + } + else + { + this->Untrack(reference, event); + /* + * If the customizer throws an unchecked exception, + * it is safe to let it propagate + */ + } + } + break; + } + case ServiceEvent::MODIFIED_ENDMATCH : + case ServiceEvent::UNREGISTERING : + this->Untrack(reference, event); + /* + * If the customizer throws an unchecked exception, it is + * safe to let it propagate + */ + break; + } +} + +template +void TrackedService::Modified() +{ + Superclass::Modified(); /* increment the modification count */ + serviceTracker->d->Modified(); +} + +template +typename TrackedService::T +TrackedService::CustomizerAdding(ServiceReference item, + const ServiceEvent& /*related*/) +{ + return customizer->AddingService(item); +} + +template +void TrackedService::CustomizerModified(ServiceReference item, + const ServiceEvent& /*related*/, + T object) +{ + customizer->ModifiedService(item, object); +} + +template +void TrackedService::CustomizerRemoved(ServiceReference item, + const ServiceEvent& /*related*/, + T object) +{ + customizer->RemovedService(item, object); +} + +US_END_NAMESPACE diff --git a/src/service/usTrackedServiceListener_p.h b/src/service/usTrackedServiceListener_p.h new file mode 100644 index 0000000000..7870bdbfd5 --- /dev/null +++ b/src/service/usTrackedServiceListener_p.h @@ -0,0 +1,51 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USTRACKEDSERVICELISTENER_H +#define USTRACKEDSERVICELISTENER_H + +#include "usServiceEvent.h" + +US_BEGIN_NAMESPACE + +/** + * This class is not intended to be used directly. It is exported to support + * the CppMicroServices module system. + */ +struct TrackedServiceListener +{ + virtual ~TrackedServiceListener() {} + + /** + * Slot connected to service events for the + * ServiceTracker class. This method must NOT be + * synchronized to avoid deadlock potential. + * + * @param event ServiceEvent object from the framework. + */ + virtual void ServiceChanged(const ServiceEvent event) = 0; + +}; + +US_END_NAMESPACE + +#endif // USTRACKEDSERVICELISTENER_H diff --git a/src/service/usTrackedService_p.h b/src/service/usTrackedService_p.h new file mode 100644 index 0000000000..7f0aa6378f --- /dev/null +++ b/src/service/usTrackedService_p.h @@ -0,0 +1,110 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USTRACKEDSERVICE_H +#define USTRACKEDSERVICE_H + +#include "usTrackedServiceListener_p.h" +#include "usModuleAbstractTracked_p.h" +#include "usServiceEvent.h" + +US_BEGIN_NAMESPACE + +/** + * This class is not intended to be used directly. It is exported to support + * the CppMicroServices module system. + */ +template +class TrackedService : public TrackedServiceListener, + public ModuleAbstractTracked, TTT, ServiceEvent> +{ + +public: + + typedef typename TTT::TrackedType T; + + TrackedService(ServiceTracker* serviceTracker, + ServiceTrackerCustomizer* customizer); + + /** + * Method connected to service events for the + * ServiceTracker class. This method must NOT be + * synchronized to avoid deadlock potential. + * + * @param event ServiceEvent object from the framework. + */ + void ServiceChanged(const ServiceEvent event); + +private: + + typedef ModuleAbstractTracked, TTT, ServiceEvent> 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/src/util/dirent_win32_p.h b/src/util/dirent_win32_p.h new file mode 100644 index 0000000000..d7dd7fc048 --- /dev/null +++ b/src/util/dirent_win32_p.h @@ -0,0 +1,374 @@ +/***************************************************************************** + * dirent.h - dirent API for Microsoft Visual Studio + * + * Copyright (C) 2006 Toni Ronkko + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * ``Software''), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * Mar 15, 2011, Toni Ronkko + * Defined FILE_ATTRIBUTE_DEVICE for MSVC 6.0. + * + * Aug 11, 2010, Toni Ronkko + * Added d_type and d_namlen fields to dirent structure. The former is + * especially useful for determining whether directory entry represents a + * file or a directory. For more information, see + * http://www.delorie.com/gnu/docs/glibc/libc_270.html + * + * Aug 11, 2010, Toni Ronkko + * Improved conformance to the standards. For example, errno is now set + * properly on failure and assert() is never used. Thanks to Peter Brockam + * for suggestions. + * + * Aug 11, 2010, Toni Ronkko + * Fixed a bug in rewinddir(): when using relative directory names, change + * of working directory no longer causes rewinddir() to fail. + * + * Dec 15, 2009, John Cunningham + * Added rewinddir member function + * + * Jan 18, 2008, Toni Ronkko + * Using FindFirstFileA and WIN32_FIND_DATAA to avoid converting string + * between multi-byte and unicode representations. This makes the + * code simpler and also allows the code to be compiled under MingW. Thanks + * to Azriel Fasten for the suggestion. + * + * Mar 4, 2007, Toni Ronkko + * Bug fix: due to the strncpy_s() function this file only compiled in + * Visual Studio 2005. Using the new string functions only when the + * compiler version allows. + * + * Nov 2, 2006, Toni Ronkko + * Major update: removed support for Watcom C, MS-DOS and Turbo C to + * simplify the file, updated the code to compile cleanly on Visual + * Studio 2005 with both unicode and multi-byte character strings, + * removed rewinddir() as it had a bug. + * + * Aug 20, 2006, Toni Ronkko + * Removed all remarks about MSVC 1.0, which is antiqued now. Simplified + * comments by removing SGML tags. + * + * May 14 2002, Toni Ronkko + * Embedded the function definitions directly to the header so that no + * source modules need to be included in the Visual Studio project. Removed + * all the dependencies to other projects so that this very header can be + * used independently. + * + * May 28 1998, Toni Ronkko + * First version. + *****************************************************************************/ +#ifndef DIRENT_H +#define DIRENT_H + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include +#include +#include +#include +#include + +/* Entries missing from MSVC 6.0 */ +#if !defined(FILE_ATTRIBUTE_DEVICE) +# define FILE_ATTRIBUTE_DEVICE 0x40 +#endif + +/* File type and permission flags for stat() */ +#if defined(_MSC_VER) && !defined(S_IREAD) +# define S_IFMT _S_IFMT /* file type mask */ +# define S_IFDIR _S_IFDIR /* directory */ +# define S_IFCHR _S_IFCHR /* character device */ +# define S_IFFIFO _S_IFFIFO /* pipe */ +# define S_IFREG _S_IFREG /* regular file */ +# define S_IREAD _S_IREAD /* read permission */ +# define S_IWRITE _S_IWRITE /* write permission */ +# define S_IEXEC _S_IEXEC /* execute permission */ +#endif +#define S_IFBLK 0 /* block device */ +#define S_IFLNK 0 /* link */ +#define S_IFSOCK 0 /* socket */ + +#if defined(_MSC_VER) +# define S_IRUSR S_IREAD /* read, user */ +# define S_IWUSR S_IWRITE /* write, user */ +# define S_IXUSR 0 /* execute, user */ +# define S_IRGRP 0 /* read, group */ +# define S_IWGRP 0 /* write, group */ +# define S_IXGRP 0 /* execute, group */ +# define S_IROTH 0 /* read, others */ +# define S_IWOTH 0 /* write, others */ +# define S_IXOTH 0 /* execute, others */ +#endif + +/* Indicates that d_type field is available in dirent structure */ +#define _DIRENT_HAVE_D_TYPE + +/* File type flags for d_type */ +#define DT_UNKNOWN 0 +#define DT_REG S_IFREG +#define DT_DIR S_IFDIR +#define DT_FIFO S_IFFIFO +#define DT_SOCK S_IFSOCK +#define DT_CHR S_IFCHR +#define DT_BLK S_IFBLK + +/* Macros for converting between st_mode and d_type */ +#define IFTODT(mode) ((mode) & S_IFMT) +#define DTTOIF(type) (type) + +/* + * File type macros. Note that block devices, sockets and links cannot be + * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are + * only defined for compatibility. These macros should always return false + * on Windows. + */ +#define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFFIFO) +#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) +#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) +#define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK) +#define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK) +#define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR) +#define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK) + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct dirent +{ + char d_name[MAX_PATH + 1]; /* File name */ + size_t d_namlen; /* Length of name without \0 */ + int d_type; /* File type */ +} dirent; + + +typedef struct DIR +{ + dirent curentry; /* Current directory entry */ + WIN32_FIND_DATAA find_data; /* Private file data */ + int cached; /* True if data is valid */ + HANDLE search_handle; /* Win32 search handle */ + char patt[MAX_PATH + 3]; /* Initial directory name */ +} DIR; + + +/* Forward declarations */ +static DIR *opendir(const char *dirname); +static struct dirent *readdir(DIR *dirp); +static int closedir(DIR *dirp); +static void rewinddir(DIR* dirp); + + +/* Use the new safe string functions introduced in Visual Studio 2005 */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +# define DIRENT_STRNCPY(dest,src,size) strncpy_s((dest),(size),(src),_TRUNCATE) +#else +# define DIRENT_STRNCPY(dest,src,size) strncpy((dest),(src),(size)) +#endif + +/* Set errno variable */ +#if defined(_MSC_VER) +#define DIRENT_SET_ERRNO(x) _set_errno (x) +#else +#define DIRENT_SET_ERRNO(x) (errno = (x)) +#endif + + +/***************************************************************************** + * Open directory stream DIRNAME for read and return a pointer to the + * internal working area that is used to retrieve individual directory + * entries. + */ +static DIR *opendir(const char *dirname) +{ + DIR *dirp; + + /* ensure that the resulting search pattern will be a valid file name */ + if (dirname == NULL) { + DIRENT_SET_ERRNO (ENOENT); + return NULL; + } + if (strlen (dirname) + 3 >= MAX_PATH) { + DIRENT_SET_ERRNO (ENAMETOOLONG); + return NULL; + } + + /* construct new DIR structure */ + dirp = (DIR*) malloc (sizeof (struct DIR)); + if (dirp != NULL) { + int error; + + /* + * Convert relative directory name to an absolute one. This + * allows rewinddir() to function correctly when the current working + * directory is changed between opendir() and rewinddir(). + */ + if (GetFullPathNameA (dirname, MAX_PATH, dirp->patt, NULL)) { + char *p; + + /* append the search pattern "\\*\0" to the directory name */ + p = strchr (dirp->patt, '\0'); + if (dirp->patt < p && *(p-1) != '\\' && *(p-1) != ':') { + *p++ = '\\'; + } + *p++ = '*'; + *p = '\0'; + + /* open directory stream and retrieve the first entry */ + dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->find_data); + if (dirp->search_handle != INVALID_HANDLE_VALUE) { + /* a directory entry is now waiting in memory */ + dirp->cached = 1; + error = 0; + } else { + /* search pattern is not a directory name? */ + DIRENT_SET_ERRNO (ENOENT); + error = 1; + } + } else { + /* buffer too small */ + DIRENT_SET_ERRNO (ENOMEM); + error = 1; + } + + if (error) { + free (dirp); + dirp = NULL; + } + } + + return dirp; +} + + +/***************************************************************************** + * Read a directory entry, and return a pointer to a dirent structure + * containing the name of the entry in d_name field. Individual directory + * entries returned by this very function include regular files, + * sub-directories, pseudo-directories "." and "..", but also volume labels, + * hidden files and system files may be returned. + */ +static struct dirent *readdir(DIR *dirp) +{ + DWORD attr; + if (dirp == NULL) { + /* directory stream did not open */ + DIRENT_SET_ERRNO (EBADF); + return NULL; + } + + /* get next directory entry */ + if (dirp->cached != 0) { + /* a valid directory entry already in memory */ + dirp->cached = 0; + } else { + /* get the next directory entry from stream */ + if (dirp->search_handle == INVALID_HANDLE_VALUE) { + return NULL; + } + if (FindNextFileA (dirp->search_handle, &dirp->find_data) == FALSE) { + /* the very last entry has been processed or an error occured */ + FindClose (dirp->search_handle); + dirp->search_handle = INVALID_HANDLE_VALUE; + return NULL; + } + } + + /* copy as a multibyte character string */ + DIRENT_STRNCPY ( dirp->curentry.d_name, + dirp->find_data.cFileName, + sizeof(dirp->curentry.d_name) ); + dirp->curentry.d_name[MAX_PATH] = '\0'; + + /* compute the length of name */ + dirp->curentry.d_namlen = strlen (dirp->curentry.d_name); + + /* determine file type */ + attr = dirp->find_data.dwFileAttributes; + if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { + dirp->curentry.d_type = DT_CHR; + } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { + dirp->curentry.d_type = DT_DIR; + } else { + dirp->curentry.d_type = DT_REG; + } + return &dirp->curentry; +} + + +/***************************************************************************** + * Close directory stream opened by opendir() function. Close of the + * directory stream invalidates the DIR structure as well as any previously + * read directory entry. + */ +static int closedir(DIR *dirp) +{ + if (dirp == NULL) { + /* invalid directory stream */ + DIRENT_SET_ERRNO (EBADF); + return -1; + } + + /* release search handle */ + if (dirp->search_handle != INVALID_HANDLE_VALUE) { + FindClose (dirp->search_handle); + dirp->search_handle = INVALID_HANDLE_VALUE; + } + + /* release directory structure */ + free (dirp); + return 0; +} + + +/***************************************************************************** + * Resets the position of the directory stream to which dirp refers to the + * beginning of the directory. It also causes the directory stream to refer + * to the current state of the corresponding directory, as a call to opendir() + * would have done. If dirp does not refer to a directory stream, the effect + * is undefined. + */ +static void rewinddir(DIR* dirp) +{ + if (dirp != NULL) { + /* release search handle */ + if (dirp->search_handle != INVALID_HANDLE_VALUE) { + FindClose (dirp->search_handle); + } + + /* open new search handle and retrieve the first entry */ + dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->find_data); + if (dirp->search_handle != INVALID_HANDLE_VALUE) { + /* a directory entry is now waiting in memory */ + dirp->cached = 1; + } else { + /* failed to re-open directory: no directory entry in memory */ + dirp->cached = 0; + } + } +} + + +#ifdef __cplusplus +} +#endif +#endif /*DIRENT_H*/ diff --git a/src/util/json_p.h b/src/util/json_p.h new file mode 100644 index 0000000000..0ab8e50d88 --- /dev/null +++ b/src/util/json_p.h @@ -0,0 +1,1855 @@ +/// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/). +/// It is intented to be used with #include + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + +/* +The JsonCpp library's source code, including accompanying documentation, +tests and demonstration applications, are licensed under the following +conditions... + +The author (Baptiste Lepilleur) explicitly disclaims copyright in all +jurisdictions which recognize such a disclaimer. In such jurisdictions, +this software is released into the Public Domain. + +In jurisdictions which do not recognize Public Domain property (e.g. Germany as of +2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is +released under the terms of the MIT License (see below). + +In jurisdictions which recognize Public Domain property, the user of this +software may choose to accept it either as 1) Public Domain, 2) under the +conditions of the MIT License (see below), or 3) under the terms of dual +Public Domain/MIT License conditions described here, as they choose. + +The MIT License is about as close to Public Domain as a license can get, and is +described in clear, concise terms at: + + http://en.wikipedia.org/wiki/MIT_License + +The full text of the MIT License follows: + +======================================================================== +Copyright (c) 2007-2010 Baptiste Lepilleur + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, +modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +======================================================================== +(END LICENSE TEXT) + +The MIT license is compatible with both the GPL and commercial +software, affording one all of the rights of Public Domain with the +minor nuisance of being required to keep the above copyright notice +and license text in the source code. Note also that by accepting the +Public Domain "license" you can re-license your copy using whatever +license you like. + +*/ + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + + + + + +#ifndef JSON_AMALGATED_H_INCLUDED +# define JSON_AMALGATED_H_INCLUDED +/// If defined, indicates that the source file is amalgated +/// to prevent private header inclusion. +#define JSON_IS_AMALGATED + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/config.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSON_CONFIG_H_INCLUDED +# define JSON_CONFIG_H_INCLUDED + +/// If defined, indicates that json library is embedded in CppTL library. +//# define JSON_IN_CPPTL 1 + +/// If defined, indicates that json may leverage CppTL library +//# define JSON_USE_CPPTL 1 +/// If defined, indicates that cpptl vector based map should be used instead of std::map +/// as Value container. +//# define JSON_USE_CPPTL_SMALLMAP 1 +/// If defined, indicates that Json specific container should be used +/// (hash table & simple deque container with customizable allocator). +/// THIS FEATURE IS STILL EXPERIMENTAL! There is know bugs: See #3177332 +//# define JSON_VALUE_USE_INTERNAL_MAP 1 +/// Force usage of standard new/malloc based allocator instead of memory pool based allocator. +/// The memory pools allocator used optimization (initializing Value and ValueInternalLink +/// as if it was a POD) that may cause some validation tool to report errors. +/// Only has effects if JSON_VALUE_USE_INTERNAL_MAP is defined. +//# define JSON_USE_SIMPLE_INTERNAL_ALLOCATOR 1 + +/// If defined, indicates that Json use exception to report invalid type manipulation +/// instead of C assert macro. +# define JSON_USE_EXCEPTION 1 + +/// If defined, indicates that the source file is amalgated +/// to prevent private header inclusion. +/// Remarks: it is automatically defined in the generated amalgated header. +#define JSON_IS_AMALGAMATION + + +# ifdef JSON_IN_CPPTL +# include +# ifndef JSON_USE_CPPTL +# define JSON_USE_CPPTL 1 +# endif +# endif + +# ifdef JSON_IN_CPPTL +# define JSON_API CPPTL_API +# elif defined(JSON_DLL_BUILD) +# define JSON_API __declspec(dllexport) +# elif defined(JSON_DLL) +# define JSON_API __declspec(dllimport) +# else +# define JSON_API +# endif + +// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for integer +// Storages, and 64 bits integer support is disabled. +// #define JSON_NO_INT64 1 + +#if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC 6 +// Microsoft Visual Studio 6 only support conversion from __int64 to double +// (no conversion from unsigned __int64). +#define JSON_USE_INT64_DOUBLE_CONVERSION 1 +#endif // if defined(_MSC_VER) && _MSC_VER < 1200 // MSVC 6 + +#if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008 +/// Indicates that the following function is deprecated. +# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message)) +#endif + +#if !defined(JSONCPP_DEPRECATED) +# define JSONCPP_DEPRECATED(message) +#endif // if !defined(JSONCPP_DEPRECATED) + +namespace Json { + typedef int Int; + typedef unsigned int UInt; +# if defined(JSON_NO_INT64) + typedef int LargestInt; + typedef unsigned int LargestUInt; +# undef JSON_HAS_INT64 +# else // if defined(JSON_NO_INT64) + // For Microsoft Visual use specific types as long long is not supported +# if defined(_MSC_VER) // Microsoft Visual Studio + typedef __int64 Int64; + typedef unsigned __int64 UInt64; +# else // if defined(_MSC_VER) // Other platforms, use long long + typedef long long int Int64; + typedef unsigned long long int UInt64; +# endif // if defined(_MSC_VER) + typedef Int64 LargestInt; + typedef UInt64 LargestUInt; +# define JSON_HAS_INT64 +# endif // if defined(JSON_NO_INT64) +} // end namespace Json + + +#endif // JSON_CONFIG_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/config.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/forwards.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSON_FORWARDS_H_INCLUDED +# define JSON_FORWARDS_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "config.h" +#endif // if !defined(JSON_IS_AMALGAMATION) + +namespace Json { + + // writer.h + class FastWriter; + class StyledWriter; + + // reader.h + class Reader; + + // features.h + class Features; + + // value.h + typedef unsigned int ArrayIndex; + class StaticString; + class Path; + class PathArgument; + class Value; + class ValueIteratorBase; + class ValueIterator; + class ValueConstIterator; +#ifdef JSON_VALUE_USE_INTERNAL_MAP + class ValueMapAllocator; + class ValueInternalLink; + class ValueInternalArray; + class ValueInternalMap; +#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP + +} // namespace Json + + +#endif // JSON_FORWARDS_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/forwards.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/features.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef CPPTL_JSON_FEATURES_H_INCLUDED +# define CPPTL_JSON_FEATURES_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "forwards.h" +#endif // if !defined(JSON_IS_AMALGAMATION) + +namespace Json { + + /** \brief Configuration passed to reader and writer. + * This configuration object can be used to force the Reader or Writer + * to behave in a standard conforming way. + */ + class JSON_API Features + { + public: + /** \brief A configuration that allows all features and assumes all strings are UTF-8. + * - C & C++ comments are allowed + * - Root object can be any JSON value + * - Assumes Value strings are encoded in UTF-8 + */ + static Features all(); + + /** \brief A configuration that is strictly compatible with the JSON specification. + * - Comments are forbidden. + * - Root object must be either an array or an object value. + * - Assumes Value strings are encoded in UTF-8 + */ + static Features strictMode(); + + /** \brief Initialize the configuration like JsonConfig::allFeatures; + */ + Features(); + + /// \c true if comments are allowed. Default: \c true. + bool allowComments_; + + /// \c true if root must be either an array or an object value. Default: \c false. + bool strictRoot_; + }; + +} // namespace Json + +#endif // CPPTL_JSON_FEATURES_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/features.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/value.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef CPPTL_JSON_H_INCLUDED +# define CPPTL_JSON_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "forwards.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +# include +# include + +# ifndef JSON_USE_CPPTL_SMALLMAP +# include +# else +# include +# endif +# ifdef JSON_USE_CPPTL +# include +# endif + +/** \brief JSON (JavaScript Object Notation). + */ +namespace Json { + + /** \brief Type of the value held by a Value object. + */ + enum ValueType + { + nullValue = 0, ///< 'null' value + intValue, ///< signed integer value + uintValue, ///< unsigned integer value + realValue, ///< double value + stringValue, ///< UTF-8 string value + booleanValue, ///< bool value + arrayValue, ///< array value (ordered list) + objectValue ///< object value (collection of name/value pairs). + }; + + enum CommentPlacement + { + commentBefore = 0, ///< a comment placed on the line before a value + commentAfterOnSameLine, ///< a comment just after a value on the same line + commentAfter, ///< a comment on the line after a value (only make sense for root value) + numberOfCommentPlacement + }; + +//# ifdef JSON_USE_CPPTL +// typedef CppTL::AnyEnumerator EnumMemberNames; +// typedef CppTL::AnyEnumerator EnumValues; +//# endif + + /** \brief Lightweight wrapper to tag static string. + * + * Value constructor and objectValue member assignement takes advantage of the + * StaticString and avoid the cost of string duplication when storing the + * string or the member name. + * + * Example of usage: + * \code + * Json::Value aValue( StaticString("some text") ); + * Json::Value object; + * static const StaticString code("code"); + * object[code] = 1234; + * \endcode + */ + class JSON_API StaticString + { + public: + explicit StaticString( const char *czstring ) + : str_( czstring ) + { + } + + operator const char *() const + { + return str_; + } + + const char *c_str() const + { + return str_; + } + + private: + const char *str_; + }; + + /** \brief Represents a JSON value. + * + * This class is a discriminated union wrapper that can represents a: + * - signed integer [range: Value::minInt - Value::maxInt] + * - unsigned integer (range: 0 - Value::maxUInt) + * - double + * - UTF-8 string + * - boolean + * - 'null' + * - an ordered list of Value + * - collection of name/value pairs (javascript object) + * + * The type of the held value is represented by a #ValueType and + * can be obtained using type(). + * + * values of an #objectValue or #arrayValue can be accessed using operator[]() methods. + * Non const methods will automatically create the a #nullValue element + * if it does not exist. + * The sequence of an #arrayValue will be automatically resize and initialized + * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue. + * + * The get() methods can be used to obtanis default value in the case the required element + * does not exist. + * + * It is possible to iterate over the list of a #objectValue values using + * the getMemberNames() method. + */ + class JSON_API Value + { + friend class ValueIteratorBase; +# ifdef JSON_VALUE_USE_INTERNAL_MAP + friend class ValueInternalLink; + friend class ValueInternalMap; +# endif + public: + typedef std::vector Members; + typedef ValueIterator iterator; + typedef ValueConstIterator const_iterator; + typedef Json::UInt UInt; + typedef Json::Int Int; +# if defined(JSON_HAS_INT64) + typedef Json::UInt64 UInt64; + typedef Json::Int64 Int64; +#endif // defined(JSON_HAS_INT64) + typedef Json::LargestInt LargestInt; + typedef Json::LargestUInt LargestUInt; + typedef Json::ArrayIndex ArrayIndex; + + static const Value null; + /// Minimum signed integer value that can be stored in a Json::Value. + static const LargestInt minLargestInt; + /// Maximum signed integer value that can be stored in a Json::Value. + static const LargestInt maxLargestInt; + /// Maximum unsigned integer value that can be stored in a Json::Value. + static const LargestUInt maxLargestUInt; + + /// Minimum signed int value that can be stored in a Json::Value. + static const Int minInt; + /// Maximum signed int value that can be stored in a Json::Value. + static const Int maxInt; + /// Maximum unsigned int value that can be stored in a Json::Value. + static const UInt maxUInt; + + /// Minimum signed 64 bits int value that can be stored in a Json::Value. + static const Int64 minInt64; + /// Maximum signed 64 bits int value that can be stored in a Json::Value. + static const Int64 maxInt64; + /// Maximum unsigned 64 bits int value that can be stored in a Json::Value. + static const UInt64 maxUInt64; + + private: +#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION +# ifndef JSON_VALUE_USE_INTERNAL_MAP + class CZString + { + public: + enum DuplicationPolicy + { + noDuplication = 0, + duplicate, + duplicateOnCopy + }; + CZString( ArrayIndex index ); + CZString( const char *cstr, DuplicationPolicy allocate ); + CZString( const CZString &other ); + ~CZString(); + CZString &operator =( const CZString &other ); + bool operator<( const CZString &other ) const; + bool operator==( const CZString &other ) const; + ArrayIndex index() const; + const char *c_str() const; + bool isStaticString() const; + private: + void swap( CZString &other ); + const char *cstr_; + ArrayIndex index_; + }; + + public: +# ifndef JSON_USE_CPPTL_SMALLMAP + typedef std::map ObjectValues; +# else + typedef CppTL::SmallMap ObjectValues; +# endif // ifndef JSON_USE_CPPTL_SMALLMAP +# endif // ifndef JSON_VALUE_USE_INTERNAL_MAP +#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + + public: + /** \brief Create a default Value of the given type. + + This is a very useful constructor. + To create an empty array, pass arrayValue. + To create an empty object, pass objectValue. + Another Value can then be set to this one by assignment. + This is useful since clear() and resize() will not alter types. + + Examples: + \code + Json::Value null_value; // null + Json::Value arr_value(Json::arrayValue); // [] + Json::Value obj_value(Json::objectValue); // {} + \endcode + */ + Value( ValueType type = nullValue ); + Value( Int value ); + Value( UInt value ); +#if defined(JSON_HAS_INT64) + Value( Int64 value ); + Value( UInt64 value ); +#endif // if defined(JSON_HAS_INT64) + Value( double value ); + Value( const char *value ); + Value( const char *beginValue, const char *endValue ); + /** \brief Constructs a value from a static string. + + * Like other value string constructor but do not duplicate the string for + * internal storage. The given string must remain alive after the call to this + * constructor. + * Example of usage: + * \code + * Json::Value aValue( StaticString("some text") ); + * \endcode + */ + Value( const StaticString &value ); + Value( const std::string &value ); +# ifdef JSON_USE_CPPTL + Value( const CppTL::ConstString &value ); +# endif + Value( bool value ); + Value( const Value &other ); + ~Value(); + + Value &operator=( const Value &other ); + /// Swap values. + /// \note Currently, comments are intentionally not swapped, for + /// both logic and efficiency. + void swap( Value &other ); + + ValueType type() const; + + bool operator <( const Value &other ) const; + bool operator <=( const Value &other ) const; + bool operator >=( const Value &other ) const; + bool operator >( const Value &other ) const; + + bool operator ==( const Value &other ) const; + bool operator !=( const Value &other ) const; + + int compare( const Value &other ) const; + + const char *asCString() const; + std::string asString() const; +# ifdef JSON_USE_CPPTL + CppTL::ConstString asConstString() const; +# endif + Int asInt() const; + UInt asUInt() const; + Int64 asInt64() const; + UInt64 asUInt64() const; + LargestInt asLargestInt() const; + LargestUInt asLargestUInt() const; + float asFloat() const; + double asDouble() const; + bool asBool() const; + + bool isNull() const; + bool isBool() const; + bool isInt() const; + bool isUInt() const; + bool isIntegral() const; + bool isDouble() const; + bool isNumeric() const; + bool isString() const; + bool isArray() const; + bool isObject() const; + + bool isConvertibleTo( ValueType other ) const; + + /// Number of values in array or object + ArrayIndex size() const; + + /// \brief Return true if empty array, empty object, or null; + /// otherwise, false. + bool empty() const; + + /// Return isNull() + bool operator!() const; + + /// Remove all object members and array elements. + /// \pre type() is arrayValue, objectValue, or nullValue + /// \post type() is unchanged + void clear(); + + /// Resize the array to size elements. + /// New elements are initialized to null. + /// May only be called on nullValue or arrayValue. + /// \pre type() is arrayValue or nullValue + /// \post type() is arrayValue + void resize( ArrayIndex size ); + + /// Access an array element (zero based index ). + /// If the array contains less than index element, then null value are inserted + /// in the array so that its size is index+1. + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + Value &operator[]( ArrayIndex index ); + + /// Access an array element (zero based index ). + /// If the array contains less than index element, then null value are inserted + /// in the array so that its size is index+1. + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + Value &operator[]( int index ); + + /// Access an array element (zero based index ) + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + const Value &operator[]( ArrayIndex index ) const; + + /// Access an array element (zero based index ) + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + const Value &operator[]( int index ) const; + + /// If the array contains at least index+1 elements, returns the element value, + /// otherwise returns defaultValue. + Value get( ArrayIndex index, + const Value &defaultValue ) const; + /// Return true if index < size(). + bool isValidIndex( ArrayIndex index ) const; + /// \brief Append value to array at the end. + /// + /// Equivalent to jsonvalue[jsonvalue.size()] = value; + Value &append( const Value &value ); + + /// Access an object value by name, create a null member if it does not exist. + Value &operator[]( const char *key ); + /// Access an object value by name, returns null if there is no member with that name. + const Value &operator[]( const char *key ) const; + /// Access an object value by name, create a null member if it does not exist. + Value &operator[]( const std::string &key ); + /// Access an object value by name, returns null if there is no member with that name. + const Value &operator[]( const std::string &key ) const; + /** \brief Access an object value by name, create a null member if it does not exist. + + * If the object as no entry for that name, then the member name used to store + * the new entry is not duplicated. + * Example of use: + * \code + * Json::Value object; + * static const StaticString code("code"); + * object[code] = 1234; + * \endcode + */ + Value &operator[]( const StaticString &key ); +# ifdef JSON_USE_CPPTL + /// Access an object value by name, create a null member if it does not exist. + Value &operator[]( const CppTL::ConstString &key ); + /// Access an object value by name, returns null if there is no member with that name. + const Value &operator[]( const CppTL::ConstString &key ) const; +# endif + /// Return the member named key if it exist, defaultValue otherwise. + Value get( const char *key, + const Value &defaultValue ) const; + /// Return the member named key if it exist, defaultValue otherwise. + Value get( const std::string &key, + const Value &defaultValue ) const; +# ifdef JSON_USE_CPPTL + /// Return the member named key if it exist, defaultValue otherwise. + Value get( const CppTL::ConstString &key, + const Value &defaultValue ) const; +# endif + /// \brief Remove and return the named member. + /// + /// Do nothing if it did not exist. + /// \return the removed Value, or null. + /// \pre type() is objectValue or nullValue + /// \post type() is unchanged + Value removeMember( const char* key ); + /// Same as removeMember(const char*) + Value removeMember( const std::string &key ); + + /// Return true if the object has a member named key. + bool isMember( const char *key ) const; + /// Return true if the object has a member named key. + bool isMember( const std::string &key ) const; +# ifdef JSON_USE_CPPTL + /// Return true if the object has a member named key. + bool isMember( const CppTL::ConstString &key ) const; +# endif + + /// \brief Return a list of the member names. + /// + /// If null, return an empty list. + /// \pre type() is objectValue or nullValue + /// \post if type() was nullValue, it remains nullValue + Members getMemberNames() const; + +//# ifdef JSON_USE_CPPTL +// EnumMemberNames enumMemberNames() const; +// EnumValues enumValues() const; +//# endif + + /// Comments must be //... or /* ... */ + void setComment( const char *comment, + CommentPlacement placement ); + /// Comments must be //... or /* ... */ + void setComment( const std::string &comment, + CommentPlacement placement ); + bool hasComment( CommentPlacement placement ) const; + /// Include delimiters and embedded newlines. + std::string getComment( CommentPlacement placement ) const; + + std::string toStyledString() const; + + const_iterator begin() const; + const_iterator end() const; + + iterator begin(); + iterator end(); + + private: + Value &resolveReference( const char *key, + bool isStatic ); + +# ifdef JSON_VALUE_USE_INTERNAL_MAP + inline bool isItemAvailable() const + { + return itemIsUsed_ == 0; + } + + inline void setItemUsed( bool isUsed = true ) + { + itemIsUsed_ = isUsed ? 1 : 0; + } + + inline bool isMemberNameStatic() const + { + return memberNameIsStatic_ == 0; + } + + inline void setMemberNameIsStatic( bool isStatic ) + { + memberNameIsStatic_ = isStatic ? 1 : 0; + } +# endif // # ifdef JSON_VALUE_USE_INTERNAL_MAP + + private: + struct CommentInfo + { + CommentInfo(); + ~CommentInfo(); + + void setComment( const char *text ); + + char *comment_; + }; + + //struct MemberNamesTransform + //{ + // typedef const char *result_type; + // const char *operator()( const CZString &name ) const + // { + // return name.c_str(); + // } + //}; + + union ValueHolder + { + LargestInt int_; + LargestUInt uint_; + double real_; + bool bool_; + char *string_; +# ifdef JSON_VALUE_USE_INTERNAL_MAP + ValueInternalArray *array_; + ValueInternalMap *map_; +#else + ObjectValues *map_; +# endif + } value_; + ValueType type_ : 8; + int allocated_ : 1; // Notes: if declared as bool, bitfield is useless. +# ifdef JSON_VALUE_USE_INTERNAL_MAP + unsigned int itemIsUsed_ : 1; // used by the ValueInternalMap container. + int memberNameIsStatic_ : 1; // used by the ValueInternalMap container. +# endif + CommentInfo *comments_; + }; + + + /** \brief Experimental and untested: represents an element of the "path" to access a node. + */ + class PathArgument + { + public: + friend class Path; + + PathArgument(); + PathArgument( ArrayIndex index ); + PathArgument( const char *key ); + PathArgument( const std::string &key ); + + private: + enum Kind + { + kindNone = 0, + kindIndex, + kindKey + }; + std::string key_; + ArrayIndex index_; + Kind kind_; + }; + + /** \brief Experimental and untested: represents a "path" to access a node. + * + * Syntax: + * - "." => root node + * - ".[n]" => elements at index 'n' of root node (an array value) + * - ".name" => member named 'name' of root node (an object value) + * - ".name1.name2.name3" + * - ".[0][1][2].name1[3]" + * - ".%" => member name is provided as parameter + * - ".[%]" => index is provied as parameter + */ + class Path + { + public: + Path( const std::string &path, + const PathArgument &a1 = PathArgument(), + const PathArgument &a2 = PathArgument(), + const PathArgument &a3 = PathArgument(), + const PathArgument &a4 = PathArgument(), + const PathArgument &a5 = PathArgument() ); + + const Value &resolve( const Value &root ) const; + Value resolve( const Value &root, + const Value &defaultValue ) const; + /// Creates the "path" to access the specified node and returns a reference on the node. + Value &make( Value &root ) const; + + private: + typedef std::vector InArgs; + typedef std::vector Args; + + void makePath( const std::string &path, + const InArgs &in ); + void addPathInArg( const std::string &path, + const InArgs &in, + InArgs::const_iterator &itInArg, + PathArgument::Kind kind ); + void invalidPath( const std::string &path, + int location ); + + Args args_; + }; + + + +#ifdef JSON_VALUE_USE_INTERNAL_MAP + /** \brief Allocator to customize Value internal map. + * Below is an example of a simple implementation (default implementation actually + * use memory pool for speed). + * \code + class DefaultValueMapAllocator : public ValueMapAllocator + { + public: // overridden from ValueMapAllocator + virtual ValueInternalMap *newMap() + { + return new ValueInternalMap(); + } + + virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) + { + return new ValueInternalMap( other ); + } + + virtual void destructMap( ValueInternalMap *map ) + { + delete map; + } + + virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) + { + return new ValueInternalLink[size]; + } + + virtual void releaseMapBuckets( ValueInternalLink *links ) + { + delete [] links; + } + + virtual ValueInternalLink *allocateMapLink() + { + return new ValueInternalLink(); + } + + virtual void releaseMapLink( ValueInternalLink *link ) + { + delete link; + } + }; + * \endcode + */ + class JSON_API ValueMapAllocator + { + public: + virtual ~ValueMapAllocator(); + virtual ValueInternalMap *newMap() = 0; + virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) = 0; + virtual void destructMap( ValueInternalMap *map ) = 0; + virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) = 0; + virtual void releaseMapBuckets( ValueInternalLink *links ) = 0; + virtual ValueInternalLink *allocateMapLink() = 0; + virtual void releaseMapLink( ValueInternalLink *link ) = 0; + }; + + /** \brief ValueInternalMap hash-map bucket chain link (for internal use only). + * \internal previous_ & next_ allows for bidirectional traversal. + */ + class JSON_API ValueInternalLink + { + public: + enum { itemPerLink = 6 }; // sizeof(ValueInternalLink) = 128 on 32 bits architecture. + enum InternalFlags { + flagAvailable = 0, + flagUsed = 1 + }; + + ValueInternalLink(); + + ~ValueInternalLink(); + + Value items_[itemPerLink]; + char *keys_[itemPerLink]; + ValueInternalLink *previous_; + ValueInternalLink *next_; + }; + + + /** \brief A linked page based hash-table implementation used internally by Value. + * \internal ValueInternalMap is a tradional bucket based hash-table, with a linked + * list in each bucket to handle collision. There is an addional twist in that + * each node of the collision linked list is a page containing a fixed amount of + * value. This provides a better compromise between memory usage and speed. + * + * Each bucket is made up of a chained list of ValueInternalLink. The last + * link of a given bucket can be found in the 'previous_' field of the following bucket. + * The last link of the last bucket is stored in tailLink_ as it has no following bucket. + * Only the last link of a bucket may contains 'available' item. The last link always + * contains at least one element unless is it the bucket one very first link. + */ + class JSON_API ValueInternalMap + { + friend class ValueIteratorBase; + friend class Value; + public: + typedef unsigned int HashKey; + typedef unsigned int BucketIndex; + +# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + struct IteratorState + { + IteratorState() + : map_(0) + , link_(0) + , itemIndex_(0) + , bucketIndex_(0) + { + } + ValueInternalMap *map_; + ValueInternalLink *link_; + BucketIndex itemIndex_; + BucketIndex bucketIndex_; + }; +# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + + ValueInternalMap(); + ValueInternalMap( const ValueInternalMap &other ); + ValueInternalMap &operator =( const ValueInternalMap &other ); + ~ValueInternalMap(); + + void swap( ValueInternalMap &other ); + + BucketIndex size() const; + + void clear(); + + bool reserveDelta( BucketIndex growth ); + + bool reserve( BucketIndex newItemCount ); + + const Value *find( const char *key ) const; + + Value *find( const char *key ); + + Value &resolveReference( const char *key, + bool isStatic ); + + void remove( const char *key ); + + void doActualRemove( ValueInternalLink *link, + BucketIndex index, + BucketIndex bucketIndex ); + + ValueInternalLink *&getLastLinkInBucket( BucketIndex bucketIndex ); + + Value &setNewItem( const char *key, + bool isStatic, + ValueInternalLink *link, + BucketIndex index ); + + Value &unsafeAdd( const char *key, + bool isStatic, + HashKey hashedKey ); + + HashKey hash( const char *key ) const; + + int compare( const ValueInternalMap &other ) const; + + private: + void makeBeginIterator( IteratorState &it ) const; + void makeEndIterator( IteratorState &it ) const; + static bool equals( const IteratorState &x, const IteratorState &other ); + static void increment( IteratorState &iterator ); + static void incrementBucket( IteratorState &iterator ); + static void decrement( IteratorState &iterator ); + static const char *key( const IteratorState &iterator ); + static const char *key( const IteratorState &iterator, bool &isStatic ); + static Value &value( const IteratorState &iterator ); + static int distance( const IteratorState &x, const IteratorState &y ); + + private: + ValueInternalLink *buckets_; + ValueInternalLink *tailLink_; + BucketIndex bucketsSize_; + BucketIndex itemCount_; + }; + + /** \brief A simplified deque implementation used internally by Value. + * \internal + * It is based on a list of fixed "page", each page contains a fixed number of items. + * Instead of using a linked-list, a array of pointer is used for fast item look-up. + * Look-up for an element is as follow: + * - compute page index: pageIndex = itemIndex / itemsPerPage + * - look-up item in page: pages_[pageIndex][itemIndex % itemsPerPage] + * + * Insertion is amortized constant time (only the array containing the index of pointers + * need to be reallocated when items are appended). + */ + class JSON_API ValueInternalArray + { + friend class Value; + friend class ValueIteratorBase; + public: + enum { itemsPerPage = 8 }; // should be a power of 2 for fast divide and modulo. + typedef Value::ArrayIndex ArrayIndex; + typedef unsigned int PageIndex; + +# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + struct IteratorState // Must be a POD + { + IteratorState() + : array_(0) + , currentPageIndex_(0) + , currentItemIndex_(0) + { + } + ValueInternalArray *array_; + Value **currentPageIndex_; + unsigned int currentItemIndex_; + }; +# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + + ValueInternalArray(); + ValueInternalArray( const ValueInternalArray &other ); + ValueInternalArray &operator =( const ValueInternalArray &other ); + ~ValueInternalArray(); + void swap( ValueInternalArray &other ); + + void clear(); + void resize( ArrayIndex newSize ); + + Value &resolveReference( ArrayIndex index ); + + Value *find( ArrayIndex index ) const; + + ArrayIndex size() const; + + int compare( const ValueInternalArray &other ) const; + + private: + static bool equals( const IteratorState &x, const IteratorState &other ); + static void increment( IteratorState &iterator ); + static void decrement( IteratorState &iterator ); + static Value &dereference( const IteratorState &iterator ); + static Value &unsafeDereference( const IteratorState &iterator ); + static int distance( const IteratorState &x, const IteratorState &y ); + static ArrayIndex indexOf( const IteratorState &iterator ); + void makeBeginIterator( IteratorState &it ) const; + void makeEndIterator( IteratorState &it ) const; + void makeIterator( IteratorState &it, ArrayIndex index ) const; + + void makeIndexValid( ArrayIndex index ); + + Value **pages_; + ArrayIndex size_; + PageIndex pageCount_; + }; + + /** \brief Experimental: do not use. Allocator to customize Value internal array. + * Below is an example of a simple implementation (actual implementation use + * memory pool). + \code +class DefaultValueArrayAllocator : public ValueArrayAllocator +{ +public: // overridden from ValueArrayAllocator + virtual ~DefaultValueArrayAllocator() + { + } + + virtual ValueInternalArray *newArray() + { + return new ValueInternalArray(); + } + + virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) + { + return new ValueInternalArray( other ); + } + + virtual void destruct( ValueInternalArray *array ) + { + delete array; + } + + virtual void reallocateArrayPageIndex( Value **&indexes, + ValueInternalArray::PageIndex &indexCount, + ValueInternalArray::PageIndex minNewIndexCount ) + { + ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1; + if ( minNewIndexCount > newIndexCount ) + newIndexCount = minNewIndexCount; + void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount ); + if ( !newIndexes ) + throw std::bad_alloc(); + indexCount = newIndexCount; + indexes = static_cast( newIndexes ); + } + virtual void releaseArrayPageIndex( Value **indexes, + ValueInternalArray::PageIndex indexCount ) + { + if ( indexes ) + free( indexes ); + } + + virtual Value *allocateArrayPage() + { + return static_cast( malloc( sizeof(Value) * ValueInternalArray::itemsPerPage ) ); + } + + virtual void releaseArrayPage( Value *value ) + { + if ( value ) + free( value ); + } +}; + \endcode + */ + class JSON_API ValueArrayAllocator + { + public: + virtual ~ValueArrayAllocator(); + virtual ValueInternalArray *newArray() = 0; + virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) = 0; + virtual void destructArray( ValueInternalArray *array ) = 0; + /** \brief Reallocate array page index. + * Reallocates an array of pointer on each page. + * \param indexes [input] pointer on the current index. May be \c NULL. + * [output] pointer on the new index of at least + * \a minNewIndexCount pages. + * \param indexCount [input] current number of pages in the index. + * [output] number of page the reallocated index can handle. + * \b MUST be >= \a minNewIndexCount. + * \param minNewIndexCount Minimum number of page the new index must be able to + * handle. + */ + virtual void reallocateArrayPageIndex( Value **&indexes, + ValueInternalArray::PageIndex &indexCount, + ValueInternalArray::PageIndex minNewIndexCount ) = 0; + virtual void releaseArrayPageIndex( Value **indexes, + ValueInternalArray::PageIndex indexCount ) = 0; + virtual Value *allocateArrayPage() = 0; + virtual void releaseArrayPage( Value *value ) = 0; + }; +#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP + + + /** \brief base class for Value iterators. + * + */ + class ValueIteratorBase + { + public: + typedef unsigned int size_t; + typedef int difference_type; + typedef ValueIteratorBase SelfType; + + ValueIteratorBase(); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + explicit ValueIteratorBase( const Value::ObjectValues::iterator ¤t ); +#else + ValueIteratorBase( const ValueInternalArray::IteratorState &state ); + ValueIteratorBase( const ValueInternalMap::IteratorState &state ); +#endif + + bool operator ==( const SelfType &other ) const + { + return isEqual( other ); + } + + bool operator !=( const SelfType &other ) const + { + return !isEqual( other ); + } + + difference_type operator -( const SelfType &other ) const + { + return computeDistance( other ); + } + + /// Return either the index or the member name of the referenced value as a Value. + Value key() const; + + /// Return the index of the referenced Value. -1 if it is not an arrayValue. + UInt index() const; + + /// Return the member name of the referenced Value. "" if it is not an objectValue. + const char *memberName() const; + + protected: + Value &deref() const; + + void increment(); + + void decrement(); + + difference_type computeDistance( const SelfType &other ) const; + + bool isEqual( const SelfType &other ) const; + + void copy( const SelfType &other ); + + private: +#ifndef JSON_VALUE_USE_INTERNAL_MAP + Value::ObjectValues::iterator current_; + // Indicates that iterator is for a null value. + bool isNull_; +#else + union + { + ValueInternalArray::IteratorState array_; + ValueInternalMap::IteratorState map_; + } iterator_; + bool isArray_; +#endif + }; + + /** \brief const iterator for object and array value. + * + */ + class ValueConstIterator : public ValueIteratorBase + { + friend class Value; + public: + typedef unsigned int size_t; + typedef int difference_type; + typedef const Value &reference; + typedef const Value *pointer; + typedef ValueConstIterator SelfType; + + ValueConstIterator(); + private: + /*! \internal Use by Value to create an iterator. + */ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + explicit ValueConstIterator( const Value::ObjectValues::iterator ¤t ); +#else + ValueConstIterator( const ValueInternalArray::IteratorState &state ); + ValueConstIterator( const ValueInternalMap::IteratorState &state ); +#endif + public: + SelfType &operator =( const ValueIteratorBase &other ); + + SelfType operator++( int ) + { + SelfType temp( *this ); + ++*this; + return temp; + } + + SelfType operator--( int ) + { + SelfType temp( *this ); + --*this; + return temp; + } + + SelfType &operator--() + { + decrement(); + return *this; + } + + SelfType &operator++() + { + increment(); + return *this; + } + + reference operator *() const + { + return deref(); + } + }; + + + /** \brief Iterator for object and array value. + */ + class ValueIterator : public ValueIteratorBase + { + friend class Value; + public: + typedef unsigned int size_t; + typedef int difference_type; + typedef Value &reference; + typedef Value *pointer; + typedef ValueIterator SelfType; + + ValueIterator(); + ValueIterator( const ValueConstIterator &other ); + ValueIterator( const ValueIterator &other ); + private: + /*! \internal Use by Value to create an iterator. + */ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + explicit ValueIterator( const Value::ObjectValues::iterator ¤t ); +#else + ValueIterator( const ValueInternalArray::IteratorState &state ); + ValueIterator( const ValueInternalMap::IteratorState &state ); +#endif + public: + + SelfType &operator =( const SelfType &other ); + + SelfType operator++( int ) + { + SelfType temp( *this ); + ++*this; + return temp; + } + + SelfType operator--( int ) + { + SelfType temp( *this ); + --*this; + return temp; + } + + SelfType &operator--() + { + decrement(); + return *this; + } + + SelfType &operator++() + { + increment(); + return *this; + } + + reference operator *() const + { + return deref(); + } + }; + + +} // namespace Json + + +#endif // CPPTL_JSON_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/value.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/reader.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef CPPTL_JSON_READER_H_INCLUDED +# define CPPTL_JSON_READER_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "features.h" +# include "value.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +# include +# include +# include +# include + +namespace Json { + + /** \brief Unserialize a JSON document into a Value. + * + */ + class JSON_API Reader + { + public: + typedef char Char; + typedef const Char *Location; + + /** \brief Constructs a Reader allowing all features + * for parsing. + */ + Reader(); + + /** \brief Constructs a Reader allowing the specified feature set + * for parsing. + */ + Reader( const Features &features ); + + /** \brief Read a Value from a JSON document. + * \param document UTF-8 encoded string containing the document to read. + * \param root [out] Contains the root value of the document if it was + * successfully parsed. + * \param collectComments \c true to collect comment and allow writing them back during + * serialization, \c false to discard comments. + * This parameter is ignored if Features::allowComments_ + * is \c false. + * \return \c true if the document was successfully parsed, \c false if an error occurred. + */ + bool parse( const std::string &document, + Value &root, + bool collectComments = true ); + + /** \brief Read a Value from a JSON document. + * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the document to read. + * \param endDoc Pointer on the end of the UTF-8 encoded string of the document to read. + \ Must be >= beginDoc. + * \param root [out] Contains the root value of the document if it was + * successfully parsed. + * \param collectComments \c true to collect comment and allow writing them back during + * serialization, \c false to discard comments. + * This parameter is ignored if Features::allowComments_ + * is \c false. + * \return \c true if the document was successfully parsed, \c false if an error occurred. + */ + bool parse( const char *beginDoc, const char *endDoc, + Value &root, + bool collectComments = true ); + + /// \brief Parse from input stream. + /// \see Json::operator>>(std::istream&, Json::Value&). + bool parse( std::istream &is, + Value &root, + bool collectComments = true ); + + /** \brief Returns a user friendly string that list errors in the parsed document. + * \return Formatted error message with the list of errors with their location in + * the parsed document. An empty string is returned if no error occurred + * during parsing. + * \deprecated Use getFormattedErrorMessages() instead (typo fix). + */ + JSONCPP_DEPRECATED("Use getFormattedErrorMessages instead") + std::string getFormatedErrorMessages() const; + + /** \brief Returns a user friendly string that list errors in the parsed document. + * \return Formatted error message with the list of errors with their location in + * the parsed document. An empty string is returned if no error occurred + * during parsing. + */ + std::string getFormattedErrorMessages() const; + + private: + enum TokenType + { + tokenEndOfStream = 0, + tokenObjectBegin, + tokenObjectEnd, + tokenArrayBegin, + tokenArrayEnd, + tokenString, + tokenNumber, + tokenTrue, + tokenFalse, + tokenNull, + tokenArraySeparator, + tokenMemberSeparator, + tokenComment, + tokenError + }; + + class Token + { + public: + TokenType type_; + Location start_; + Location end_; + }; + + class ErrorInfo + { + public: + Token token_; + std::string message_; + Location extra_; + }; + + typedef std::deque Errors; + + bool expectToken( TokenType type, Token &token, const char *message ); + bool readToken( Token &token ); + void skipSpaces(); + bool match( Location pattern, + int patternLength ); + bool readComment(); + bool readCStyleComment(); + bool readCppStyleComment(); + bool readString(); + void readNumber(); + bool readValue(); + bool readObject( Token &token ); + bool readArray( Token &token ); + bool decodeNumber( Token &token ); + bool decodeString( Token &token ); + bool decodeString( Token &token, std::string &decoded ); + bool decodeDouble( Token &token ); + bool decodeUnicodeCodePoint( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ); + bool decodeUnicodeEscapeSequence( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ); + bool addError( const std::string &message, + Token &token, + Location extra = 0 ); + bool recoverFromError( TokenType skipUntilToken ); + bool addErrorAndRecover( const std::string &message, + Token &token, + TokenType skipUntilToken ); + void skipUntilSpace(); + Value ¤tValue(); + Char getNextChar(); + void getLocationLineAndColumn( Location location, + int &line, + int &column ) const; + std::string getLocationLineAndColumn( Location location ) const; + void addComment( Location begin, + Location end, + CommentPlacement placement ); + void skipCommentTokens( Token &token ); + + typedef std::stack Nodes; + Nodes nodes_; + Errors errors_; + std::string document_; + Location begin_; + Location end_; + Location current_; + Location lastValueEnd_; + Value *lastValue_; + std::string commentsBefore_; + Features features_; + bool collectComments_; + }; + + /** \brief Read from 'sin' into 'root'. + + Always keep comments from the input JSON. + + This can be used to read a file into a particular sub-object. + For example: + \code + Json::Value root; + cin >> root["dir"]["file"]; + cout << root; + \endcode + Result: + \verbatim + { + "dir": { + "file": { + // The input stream JSON would be nested here. + } + } + } + \endverbatim + \throw std::exception on parse error. + \see Json::operator<<() + */ + std::istream& operator>>( std::istream&, Value& ); + +} // namespace Json + +#endif // CPPTL_JSON_READER_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/reader.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/writer.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSON_WRITER_H_INCLUDED +# define JSON_WRITER_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "value.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +# include +# include +# include + +namespace Json { + + class Value; + + /** \brief Abstract class for writers. + */ + class JSON_API Writer + { + public: + virtual ~Writer(); + + virtual std::string write( const Value &root ) = 0; + }; + + /** \brief Outputs a Value in JSON format without formatting (not human friendly). + * + * The JSON document is written in a single line. It is not intended for 'human' consumption, + * but may be usefull to support feature such as RPC where bandwith is limited. + * \sa Reader, Value + */ + class JSON_API FastWriter : public Writer + { + public: + FastWriter(); + virtual ~FastWriter(){} + + void enableYAMLCompatibility(); + + public: // overridden from Writer + virtual std::string write( const Value &root ); + + private: + void writeValue( const Value &value ); + + std::string document_; + bool yamlCompatiblityEnabled_; + }; + + /** \brief Writes a Value in JSON format in a human friendly way. + * + * The rules for line break and indent are as follow: + * - Object value: + * - if empty then print {} without indent and line break + * - if not empty the print '{', line break & indent, print one value per line + * and then unindent and line break and print '}'. + * - Array value: + * - if empty then print [] without indent and line break + * - if the array contains no object value, empty array or some other value types, + * and all the values fit on one lines, then print the array on a single line. + * - otherwise, it the values do not fit on one line, or the array contains + * object or non empty array, then print one value per line. + * + * If the Value have comments then they are outputed according to their #CommentPlacement. + * + * \sa Reader, Value, Value::setComment() + */ + class JSON_API StyledWriter: public Writer + { + public: + StyledWriter(); + virtual ~StyledWriter(){} + + public: // overridden from Writer + /** \brief Serialize a Value in JSON format. + * \param root Value to serialize. + * \return String containing the JSON document that represents the root value. + */ + virtual std::string write( const Value &root ); + + private: + void writeValue( const Value &value ); + void writeArrayValue( const Value &value ); + bool isMultineArray( const Value &value ); + void pushValue( const std::string &value ); + void writeIndent(); + void writeWithIndent( const std::string &value ); + void indent(); + void unindent(); + void writeCommentBeforeValue( const Value &root ); + void writeCommentAfterValueOnSameLine( const Value &root ); + bool hasCommentForValue( const Value &value ); + static std::string normalizeEOL( const std::string &text ); + + typedef std::vector ChildValues; + + ChildValues childValues_; + std::string document_; + std::string indentString_; + int rightMargin_; + int indentSize_; + bool addChildValues_; + }; + + /** \brief Writes a Value in JSON format in a human friendly way, + to a stream rather than to a string. + * + * The rules for line break and indent are as follow: + * - Object value: + * - if empty then print {} without indent and line break + * - if not empty the print '{', line break & indent, print one value per line + * and then unindent and line break and print '}'. + * - Array value: + * - if empty then print [] without indent and line break + * - if the array contains no object value, empty array or some other value types, + * and all the values fit on one lines, then print the array on a single line. + * - otherwise, it the values do not fit on one line, or the array contains + * object or non empty array, then print one value per line. + * + * If the Value have comments then they are outputed according to their #CommentPlacement. + * + * \param indentation Each level will be indented by this amount extra. + * \sa Reader, Value, Value::setComment() + */ + class JSON_API StyledStreamWriter + { + public: + StyledStreamWriter( std::string indentation="\t" ); + ~StyledStreamWriter(){} + + public: + /** \brief Serialize a Value in JSON format. + * \param out Stream to write to. (Can be ostringstream, e.g.) + * \param root Value to serialize. + * \note There is no point in deriving from Writer, since write() should not return a value. + */ + void write( std::ostream &out, const Value &root ); + + private: + void writeValue( const Value &value ); + void writeArrayValue( const Value &value ); + bool isMultineArray( const Value &value ); + void pushValue( const std::string &value ); + void writeIndent(); + void writeWithIndent( const std::string &value ); + void indent(); + void unindent(); + void writeCommentBeforeValue( const Value &root ); + void writeCommentAfterValueOnSameLine( const Value &root ); + bool hasCommentForValue( const Value &value ); + static std::string normalizeEOL( const std::string &text ); + + typedef std::vector ChildValues; + + ChildValues childValues_; + std::ostream* document_; + std::string indentString_; + int rightMargin_; + std::string indentation_; + bool addChildValues_; + }; + +# if defined(JSON_HAS_INT64) + std::string JSON_API valueToString( Int value ); + std::string JSON_API valueToString( UInt value ); +# endif // if defined(JSON_HAS_INT64) + std::string JSON_API valueToString( LargestInt value ); + std::string JSON_API valueToString( LargestUInt value ); + std::string JSON_API valueToString( double value ); + std::string JSON_API valueToString( bool value ); + std::string JSON_API valueToQuotedString( const char *value ); + + /// \brief Output using the StyledStreamWriter. + /// \see Json::operator>>() + std::ostream& operator<<( std::ostream&, const Value &root ); + +} // namespace Json + + + +#endif // JSON_WRITER_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/writer.h +// ////////////////////////////////////////////////////////////////////// + + + + + +#endif //ifndef JSON_AMALGATED_H_INCLUDED diff --git a/src/util/jsoncpp.cpp b/src/util/jsoncpp.cpp new file mode 100644 index 0000000000..8b2781c281 --- /dev/null +++ b/src/util/jsoncpp.cpp @@ -0,0 +1,4225 @@ +/// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/). +/// It is intented to be used with #include + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + +/* +The JsonCpp library's source code, including accompanying documentation, +tests and demonstration applications, are licensed under the following +conditions... + +The author (Baptiste Lepilleur) explicitly disclaims copyright in all +jurisdictions which recognize such a disclaimer. In such jurisdictions, +this software is released into the Public Domain. + +In jurisdictions which do not recognize Public Domain property (e.g. Germany as of +2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is +released under the terms of the MIT License (see below). + +In jurisdictions which recognize Public Domain property, the user of this +software may choose to accept it either as 1) Public Domain, 2) under the +conditions of the MIT License (see below), or 3) under the terms of dual +Public Domain/MIT License conditions described here, as they choose. + +The MIT License is about as close to Public Domain as a license can get, and is +described in clear, concise terms at: + + http://en.wikipedia.org/wiki/MIT_License + +The full text of the MIT License follows: + +======================================================================== +Copyright (c) 2007-2010 Baptiste Lepilleur + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, +modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +======================================================================== +(END LICENSE TEXT) + +The MIT license is compatible with both the GPL and commercial +software, affording one all of the rights of Public Domain with the +minor nuisance of being required to keep the above copyright notice +and license text in the source code. Note also that by accepting the +Public Domain "license" you can re-license your copy using whatever +license you like. + +*/ + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + + + + + + +#include + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_tool.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED +# define LIB_JSONCPP_JSON_TOOL_H_INCLUDED + +/* This header provides common string manipulation support, such as UTF-8, + * portable conversion from/to string... + * + * It is an internal header that must not be exposed. + */ + +namespace Json { + +/// Converts a unicode code-point to UTF-8. +static inline std::string +codePointToUTF8(unsigned int cp) +{ + std::string result; + + // based on description from http://en.wikipedia.org/wiki/UTF-8 + + if (cp <= 0x7f) + { + result.resize(1); + result[0] = static_cast(cp); + } + else if (cp <= 0x7FF) + { + result.resize(2); + result[1] = static_cast(0x80 | (0x3f & cp)); + result[0] = static_cast(0xC0 | (0x1f & (cp >> 6))); + } + else if (cp <= 0xFFFF) + { + result.resize(3); + result[2] = static_cast(0x80 | (0x3f & cp)); + result[1] = 0x80 | static_cast((0x3f & (cp >> 6))); + result[0] = 0xE0 | static_cast((0xf & (cp >> 12))); + } + else if (cp <= 0x10FFFF) + { + result.resize(4); + result[3] = static_cast(0x80 | (0x3f & cp)); + result[2] = static_cast(0x80 | (0x3f & (cp >> 6))); + result[1] = static_cast(0x80 | (0x3f & (cp >> 12))); + result[0] = static_cast(0xF0 | (0x7 & (cp >> 18))); + } + + return result; +} + + +/// Returns true if ch is a control character (in range [0,32[). +static inline bool +isControlCharacter(char ch) +{ + return ch > 0 && ch <= 0x1F; +} + + +enum { + /// Constant that specify the size of the buffer that must be passed to uintToString. + uintToStringBufferSize = 3*sizeof(LargestUInt)+1 +}; + +// Defines a char buffer for use with uintToString(). +typedef char UIntToStringBuffer[uintToStringBufferSize]; + + +/** Converts an unsigned integer to string. + * @param value Unsigned interger to convert to string + * @param current Input/Output string buffer. + * Must have at least uintToStringBufferSize chars free. + */ +static inline void +uintToString( LargestUInt value, + char *¤t ) +{ + *--current = 0; + do + { + *--current = char(value % 10) + '0'; + value /= 10; + } + while ( value != 0 ); +} + +} // namespace Json { + +#endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_tool.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_reader.cpp +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#if !defined(JSON_IS_AMALGAMATION) +# include +# include +# include "json_tool.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +#include +#include +#include +#include +#include +#include + +#if _MSC_VER >= 1400 // VC++ 8.0 +#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated. +#endif + +namespace Json { + +// Implementation of class Features +// //////////////////////////////// + +Features::Features() + : allowComments_( true ) + , strictRoot_( false ) +{ +} + + +Features +Features::all() +{ + return Features(); +} + + +Features +Features::strictMode() +{ + Features features; + features.allowComments_ = false; + features.strictRoot_ = true; + return features; +} + +// Implementation of class Reader +// //////////////////////////////// + + +static inline bool +in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4 ) +{ + return c == c1 || c == c2 || c == c3 || c == c4; +} + +static inline bool +in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4, Reader::Char c5 ) +{ + return c == c1 || c == c2 || c == c3 || c == c4 || c == c5; +} + + +static bool +containsNewLine( Reader::Location begin, + Reader::Location end ) +{ + for ( ;begin < end; ++begin ) + if ( *begin == '\n' || *begin == '\r' ) + return true; + return false; +} + + +// Class Reader +// ////////////////////////////////////////////////////////////////// + +Reader::Reader() + : features_( Features::all() ) +{ +} + + +Reader::Reader( const Features &features ) + : features_( features ) +{ +} + + +bool +Reader::parse( const std::string &document, + Value &root, + bool collectComments ) +{ + document_ = document; + const char *begin = document_.c_str(); + const char *end = begin + document_.length(); + return parse( begin, end, root, collectComments ); +} + + +bool +Reader::parse( std::istream& sin, + Value &root, + bool collectComments ) +{ + //std::istream_iterator begin(sin); + //std::istream_iterator end; + // Those would allow streamed input from a file, if parse() were a + // template function. + + // Since std::string is reference-counted, this at least does not + // create an extra copy. + std::string doc; + std::getline(sin, doc, static_cast(EOF)); + return parse( doc, root, collectComments ); +} + +bool +Reader::parse( const char *beginDoc, const char *endDoc, + Value &root, + bool collectComments ) +{ + if ( !features_.allowComments_ ) + { + collectComments = false; + } + + begin_ = beginDoc; + end_ = endDoc; + collectComments_ = collectComments; + current_ = begin_; + lastValueEnd_ = 0; + lastValue_ = 0; + commentsBefore_ = ""; + errors_.clear(); + while ( !nodes_.empty() ) + nodes_.pop(); + nodes_.push( &root ); + + bool successful = readValue(); + Token token; + skipCommentTokens( token ); + if ( collectComments_ && !commentsBefore_.empty() ) + root.setComment( commentsBefore_, commentAfter ); + if ( features_.strictRoot_ ) + { + if ( !root.isArray() && !root.isObject() ) + { + // Set error location to start of doc, ideally should be first token found in doc + token.type_ = tokenError; + token.start_ = beginDoc; + token.end_ = endDoc; + addError( "A valid JSON document must be either an array or an object value.", + token ); + return false; + } + } + return successful; +} + + +bool +Reader::readValue() +{ + Token token; + skipCommentTokens( token ); + bool successful = true; + + if ( collectComments_ && !commentsBefore_.empty() ) + { + currentValue().setComment( commentsBefore_, commentBefore ); + commentsBefore_ = ""; + } + + + switch ( token.type_ ) + { + case tokenObjectBegin: + successful = readObject( token ); + break; + case tokenArrayBegin: + successful = readArray( token ); + break; + case tokenNumber: + successful = decodeNumber( token ); + break; + case tokenString: + successful = decodeString( token ); + break; + case tokenTrue: + currentValue() = true; + break; + case tokenFalse: + currentValue() = false; + break; + case tokenNull: + currentValue() = Value(); + break; + default: + return addError( "Syntax error: value, object or array expected.", token ); + } + + if ( collectComments_ ) + { + lastValueEnd_ = current_; + lastValue_ = ¤tValue(); + } + + return successful; +} + + +void +Reader::skipCommentTokens( Token &token ) +{ + if ( features_.allowComments_ ) + { + do + { + readToken( token ); + } + while ( token.type_ == tokenComment ); + } + else + { + readToken( token ); + } +} + + +bool +Reader::expectToken( TokenType type, Token &token, const char *message ) +{ + readToken( token ); + if ( token.type_ != type ) + return addError( message, token ); + return true; +} + + +bool +Reader::readToken( Token &token ) +{ + skipSpaces(); + token.start_ = current_; + Char c = getNextChar(); + bool ok = true; + switch ( c ) + { + case '{': + token.type_ = tokenObjectBegin; + break; + case '}': + token.type_ = tokenObjectEnd; + break; + case '[': + token.type_ = tokenArrayBegin; + break; + case ']': + token.type_ = tokenArrayEnd; + break; + case '"': + token.type_ = tokenString; + ok = readString(); + break; + case '/': + token.type_ = tokenComment; + ok = readComment(); + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '-': + token.type_ = tokenNumber; + readNumber(); + break; + case 't': + token.type_ = tokenTrue; + ok = match( "rue", 3 ); + break; + case 'f': + token.type_ = tokenFalse; + ok = match( "alse", 4 ); + break; + case 'n': + token.type_ = tokenNull; + ok = match( "ull", 3 ); + break; + case ',': + token.type_ = tokenArraySeparator; + break; + case ':': + token.type_ = tokenMemberSeparator; + break; + case 0: + token.type_ = tokenEndOfStream; + break; + default: + ok = false; + break; + } + if ( !ok ) + token.type_ = tokenError; + token.end_ = current_; + return true; +} + + +void +Reader::skipSpaces() +{ + while ( current_ != end_ ) + { + Char c = *current_; + if ( c == ' ' || c == '\t' || c == '\r' || c == '\n' ) + ++current_; + else + break; + } +} + + +bool +Reader::match( Location pattern, + int patternLength ) +{ + if ( end_ - current_ < patternLength ) + return false; + int index = patternLength; + while ( index-- ) + if ( current_[index] != pattern[index] ) + return false; + current_ += patternLength; + return true; +} + + +bool +Reader::readComment() +{ + Location commentBegin = current_ - 1; + Char c = getNextChar(); + bool successful = false; + if ( c == '*' ) + successful = readCStyleComment(); + else if ( c == '/' ) + successful = readCppStyleComment(); + if ( !successful ) + return false; + + if ( collectComments_ ) + { + CommentPlacement placement = commentBefore; + if ( lastValueEnd_ && !containsNewLine( lastValueEnd_, commentBegin ) ) + { + if ( c != '*' || !containsNewLine( commentBegin, current_ ) ) + placement = commentAfterOnSameLine; + } + + addComment( commentBegin, current_, placement ); + } + return true; +} + + +void +Reader::addComment( Location begin, + Location end, + CommentPlacement placement ) +{ + assert( collectComments_ ); + if ( placement == commentAfterOnSameLine ) + { + assert( lastValue_ != 0 ); + lastValue_->setComment( std::string( begin, end ), placement ); + } + else + { + if ( !commentsBefore_.empty() ) + commentsBefore_ += "\n"; + commentsBefore_ += std::string( begin, end ); + } +} + + +bool +Reader::readCStyleComment() +{ + while ( current_ != end_ ) + { + Char c = getNextChar(); + if ( c == '*' && *current_ == '/' ) + break; + } + return getNextChar() == '/'; +} + + +bool +Reader::readCppStyleComment() +{ + while ( current_ != end_ ) + { + Char c = getNextChar(); + if ( c == '\r' || c == '\n' ) + break; + } + return true; +} + + +void +Reader::readNumber() +{ + while ( current_ != end_ ) + { + if ( !(*current_ >= '0' && *current_ <= '9') && + !in( *current_, '.', 'e', 'E', '+', '-' ) ) + break; + ++current_; + } +} + +bool +Reader::readString() +{ + Char c = 0; + while ( current_ != end_ ) + { + c = getNextChar(); + if ( c == '\\' ) + getNextChar(); + else if ( c == '"' ) + break; + } + return c == '"'; +} + + +bool +Reader::readObject( Token &/*tokenStart*/ ) +{ + Token tokenName; + std::string name; + currentValue() = Value( objectValue ); + while ( readToken( tokenName ) ) + { + bool initialTokenOk = true; + while ( tokenName.type_ == tokenComment && initialTokenOk ) + initialTokenOk = readToken( tokenName ); + if ( !initialTokenOk ) + break; + if ( tokenName.type_ == tokenObjectEnd && name.empty() ) // empty object + return true; + if ( tokenName.type_ != tokenString ) + break; + + name = ""; + if ( !decodeString( tokenName, name ) ) + return recoverFromError( tokenObjectEnd ); + + Token colon; + if ( !readToken( colon ) || colon.type_ != tokenMemberSeparator ) + { + return addErrorAndRecover( "Missing ':' after object member name", + colon, + tokenObjectEnd ); + } + Value &value = currentValue()[ name ]; + nodes_.push( &value ); + bool ok = readValue(); + nodes_.pop(); + if ( !ok ) // error already set + return recoverFromError( tokenObjectEnd ); + + Token comma; + if ( !readToken( comma ) + || ( comma.type_ != tokenObjectEnd && + comma.type_ != tokenArraySeparator && + comma.type_ != tokenComment ) ) + { + return addErrorAndRecover( "Missing ',' or '}' in object declaration", + comma, + tokenObjectEnd ); + } + bool finalizeTokenOk = true; + while ( comma.type_ == tokenComment && + finalizeTokenOk ) + finalizeTokenOk = readToken( comma ); + if ( comma.type_ == tokenObjectEnd ) + return true; + } + return addErrorAndRecover( "Missing '}' or object member name", + tokenName, + tokenObjectEnd ); +} + + +bool +Reader::readArray( Token &/*tokenStart*/ ) +{ + currentValue() = Value( arrayValue ); + skipSpaces(); + if ( *current_ == ']' ) // empty array + { + Token endArray; + readToken( endArray ); + return true; + } + int index = 0; + for (;;) + { + Value &value = currentValue()[ index++ ]; + nodes_.push( &value ); + bool ok = readValue(); + nodes_.pop(); + if ( !ok ) // error already set + return recoverFromError( tokenArrayEnd ); + + Token token; + // Accept Comment after last item in the array. + ok = readToken( token ); + while ( token.type_ == tokenComment && ok ) + { + ok = readToken( token ); + } + bool badTokenType = ( token.type_ != tokenArraySeparator && + token.type_ != tokenArrayEnd ); + if ( !ok || badTokenType ) + { + return addErrorAndRecover( "Missing ',' or ']' in array declaration", + token, + tokenArrayEnd ); + } + if ( token.type_ == tokenArrayEnd ) + break; + } + return true; +} + + +bool +Reader::decodeNumber( Token &token ) +{ + bool isDouble = false; + for ( Location inspect = token.start_; inspect != token.end_; ++inspect ) + { + isDouble = isDouble + || in( *inspect, '.', 'e', 'E', '+' ) + || ( *inspect == '-' && inspect != token.start_ ); + } + if ( isDouble ) + return decodeDouble( token ); + // Attempts to parse the number as an integer. If the number is + // larger than the maximum supported value of an integer then + // we decode the number as a double. + Location current = token.start_; + bool isNegative = *current == '-'; + if ( isNegative ) + ++current; + Value::LargestUInt maxIntegerValue = isNegative ? Value::LargestUInt(-Value::minLargestInt) + : Value::maxLargestUInt; + Value::LargestUInt threshold = maxIntegerValue / 10; + Value::UInt lastDigitThreshold = Value::UInt( maxIntegerValue % 10 ); + assert(/* lastDigitThreshold >=0 &&*/ lastDigitThreshold <= 9 ); + Value::LargestUInt value = 0; + while ( current < token.end_ ) + { + Char c = *current++; + if ( c < '0' || c > '9' ) + return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token ); + Value::UInt digit(c - '0'); + if ( value >= threshold ) + { + // If the current digit is not the last one, or if it is + // greater than the last digit of the maximum integer value, + // the parse the number as a double. + if ( current != token.end_ || digit > lastDigitThreshold ) + { + return decodeDouble( token ); + } + } + value = value * 10 + digit; + } + if ( isNegative ) + currentValue() = -Value::LargestInt( value ); + else if ( value <= Value::LargestUInt(Value::maxInt) ) + currentValue() = Value::LargestInt( value ); + else + currentValue() = value; + return true; +} + + +bool +Reader::decodeDouble( Token &token ) +{ + double value = 0; + const int bufferSize = 32; + int count; + int length = int(token.end_ - token.start_); + if ( length <= bufferSize ) + { + Char buffer[bufferSize+1]; + memcpy( buffer, token.start_, length ); + buffer[length] = 0; + count = sscanf( buffer, "%lf", &value ); + } + else + { + std::string buffer( token.start_, token.end_ ); + count = sscanf( buffer.c_str(), "%lf", &value ); + } + + if ( count != 1 ) + return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token ); + currentValue() = value; + return true; +} + + +bool +Reader::decodeString( Token &token ) +{ + std::string decoded; + if ( !decodeString( token, decoded ) ) + return false; + currentValue() = decoded; + return true; +} + + +bool +Reader::decodeString( Token &token, std::string &decoded ) +{ + decoded.reserve( token.end_ - token.start_ - 2 ); + Location current = token.start_ + 1; // skip '"' + Location end = token.end_ - 1; // do not include '"' + while ( current != end ) + { + Char c = *current++; + if ( c == '"' ) + break; + else if ( c == '\\' ) + { + if ( current == end ) + return addError( "Empty escape sequence in string", token, current ); + Char escape = *current++; + switch ( escape ) + { + case '"': decoded += '"'; break; + case '/': decoded += '/'; break; + case '\\': decoded += '\\'; break; + case 'b': decoded += '\b'; break; + case 'f': decoded += '\f'; break; + case 'n': decoded += '\n'; break; + case 'r': decoded += '\r'; break; + case 't': decoded += '\t'; break; + case 'u': + { + unsigned int unicode; + if ( !decodeUnicodeCodePoint( token, current, end, unicode ) ) + return false; + decoded += codePointToUTF8(unicode); + } + break; + default: + return addError( "Bad escape sequence in string", token, current ); + } + } + else + { + decoded += c; + } + } + return true; +} + +bool +Reader::decodeUnicodeCodePoint( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ) +{ + + if ( !decodeUnicodeEscapeSequence( token, current, end, unicode ) ) + return false; + if (unicode >= 0xD800 && unicode <= 0xDBFF) + { + // surrogate pairs + if (end - current < 6) + return addError( "additional six characters expected to parse unicode surrogate pair.", token, current ); + unsigned int surrogatePair; + if (*(current++) == '\\' && *(current++)== 'u') + { + if (decodeUnicodeEscapeSequence( token, current, end, surrogatePair )) + { + unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF); + } + else + return false; + } + else + return addError( "expecting another \\u token to begin the second half of a unicode surrogate pair", token, current ); + } + return true; +} + +bool +Reader::decodeUnicodeEscapeSequence( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ) +{ + if ( end - current < 4 ) + return addError( "Bad unicode escape sequence in string: four digits expected.", token, current ); + unicode = 0; + for ( int index =0; index < 4; ++index ) + { + Char c = *current++; + unicode *= 16; + if ( c >= '0' && c <= '9' ) + unicode += c - '0'; + else if ( c >= 'a' && c <= 'f' ) + unicode += c - 'a' + 10; + else if ( c >= 'A' && c <= 'F' ) + unicode += c - 'A' + 10; + else + return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current ); + } + return true; +} + + +bool +Reader::addError( const std::string &message, + Token &token, + Location extra ) +{ + ErrorInfo info; + info.token_ = token; + info.message_ = message; + info.extra_ = extra; + errors_.push_back( info ); + return false; +} + + +bool +Reader::recoverFromError( TokenType skipUntilToken ) +{ + int errorCount = int(errors_.size()); + Token skip; + for (;;) + { + if ( !readToken(skip) ) + errors_.resize( errorCount ); // discard errors caused by recovery + if ( skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream ) + break; + } + errors_.resize( errorCount ); + return false; +} + + +bool +Reader::addErrorAndRecover( const std::string &message, + Token &token, + TokenType skipUntilToken ) +{ + addError( message, token ); + return recoverFromError( skipUntilToken ); +} + + +Value & +Reader::currentValue() +{ + return *(nodes_.top()); +} + + +Reader::Char +Reader::getNextChar() +{ + if ( current_ == end_ ) + return 0; + return *current_++; +} + + +void +Reader::getLocationLineAndColumn( Location location, + int &line, + int &column ) const +{ + Location current = begin_; + Location lastLineStart = current; + line = 0; + while ( current < location && current != end_ ) + { + Char c = *current++; + if ( c == '\r' ) + { + if ( *current == '\n' ) + ++current; + lastLineStart = current; + ++line; + } + else if ( c == '\n' ) + { + lastLineStart = current; + ++line; + } + } + // column & line start at 1 + column = int(location - lastLineStart) + 1; + ++line; +} + + +std::string +Reader::getLocationLineAndColumn( Location location ) const +{ + int line, column; + getLocationLineAndColumn( location, line, column ); + char buffer[18+16+16+1]; + sprintf( buffer, "Line %d, Column %d", line, column ); + return buffer; +} + + +// Deprecated. Preserved for backward compatibility +std::string +Reader::getFormatedErrorMessages() const +{ + return getFormattedErrorMessages(); +} + + +std::string +Reader::getFormattedErrorMessages() const +{ + std::string formattedMessage; + for ( Errors::const_iterator itError = errors_.begin(); + itError != errors_.end(); + ++itError ) + { + const ErrorInfo &error = *itError; + formattedMessage += "* " + getLocationLineAndColumn( error.token_.start_ ) + "\n"; + formattedMessage += " " + error.message_ + "\n"; + if ( error.extra_ ) + formattedMessage += "See " + getLocationLineAndColumn( error.extra_ ) + " for detail.\n"; + } + return formattedMessage; +} + + +std::istream& operator>>( std::istream &sin, Value &root ) +{ + Json::Reader reader; + bool ok = reader.parse(sin, root, true); + //JSON_ASSERT( ok ); + if (!ok) throw std::runtime_error(reader.getFormattedErrorMessages()); + return sin; +} + + +} // namespace Json + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_reader.cpp +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_batchallocator.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSONCPP_BATCHALLOCATOR_H_INCLUDED +# define JSONCPP_BATCHALLOCATOR_H_INCLUDED + +# include +# include + +# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + +namespace Json { + +/* Fast memory allocator. + * + * This memory allocator allocates memory for a batch of object (specified by + * the page size, the number of object in each page). + * + * It does not allow the destruction of a single object. All the allocated objects + * can be destroyed at once. The memory can be either released or reused for future + * allocation. + * + * The in-place new operator must be used to construct the object using the pointer + * returned by allocate. + */ +template +class BatchAllocator +{ +public: + typedef AllocatedType Type; + + BatchAllocator( unsigned int objectsPerPage = 255 ) + : freeHead_( 0 ) + , objectsPerPage_( objectsPerPage ) + { +// printf( "Size: %d => %s\n", sizeof(AllocatedType), typeid(AllocatedType).name() ); + assert( sizeof(AllocatedType) * objectPerAllocation >= sizeof(AllocatedType *) ); // We must be able to store a slist in the object free space. + assert( objectsPerPage >= 16 ); + batches_ = allocateBatch( 0 ); // allocated a dummy page + currentBatch_ = batches_; + } + + ~BatchAllocator() + { + for ( BatchInfo *batch = batches_; batch; ) + { + BatchInfo *nextBatch = batch->next_; + free( batch ); + batch = nextBatch; + } + } + + /// allocate space for an array of objectPerAllocation object. + /// @warning it is the responsability of the caller to call objects constructors. + AllocatedType *allocate() + { + if ( freeHead_ ) // returns node from free list. + { + AllocatedType *object = freeHead_; + freeHead_ = *static_cast(object); + return object; + } + if ( currentBatch_->used_ == currentBatch_->end_ ) + { + currentBatch_ = currentBatch_->next_; + while ( currentBatch_ && currentBatch_->used_ == currentBatch_->end_ ) + currentBatch_ = currentBatch_->next_; + + if ( !currentBatch_ ) // no free batch found, allocate a new one + { + currentBatch_ = allocateBatch( objectsPerPage_ ); + currentBatch_->next_ = batches_; // insert at the head of the list + batches_ = currentBatch_; + } + } + AllocatedType *allocated = currentBatch_->used_; + currentBatch_->used_ += objectPerAllocation; + return allocated; + } + + /// Release the object. + /// @warning it is the responsability of the caller to actually destruct the object. + void release( AllocatedType *object ) + { + assert( object != 0 ); + *static_cast(object) = freeHead_; + freeHead_ = object; + } + +private: + struct BatchInfo + { + BatchInfo *next_; + AllocatedType *used_; + AllocatedType *end_; + AllocatedType buffer_[objectPerAllocation]; + }; + + // disabled copy constructor and assignement operator. + BatchAllocator( const BatchAllocator & ); + void operator =( const BatchAllocator &); + + static BatchInfo *allocateBatch( unsigned int objectsPerPage ) + { + const unsigned int mallocSize = sizeof(BatchInfo) - sizeof(AllocatedType)* objectPerAllocation + + sizeof(AllocatedType) * objectPerAllocation * objectsPerPage; + BatchInfo *batch = static_cast( malloc( mallocSize ) ); + batch->next_ = 0; + batch->used_ = batch->buffer_; + batch->end_ = batch->buffer_ + objectsPerPage; + return batch; + } + + BatchInfo *batches_; + BatchInfo *currentBatch_; + /// Head of a single linked list within the allocated space of freeed object + AllocatedType *freeHead_; + unsigned int objectsPerPage_; +}; + + +} // namespace Json + +# endif // ifndef JSONCPP_DOC_INCLUDE_IMPLEMENTATION + +#endif // JSONCPP_BATCHALLOCATOR_H_INCLUDED + + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_batchallocator.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_valueiterator.inl +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +// included by json_value.cpp + +namespace Json { + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueIteratorBase +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +ValueIteratorBase::ValueIteratorBase() +#ifndef JSON_VALUE_USE_INTERNAL_MAP + : current_() + , isNull_( true ) +{ +} +#else + : isArray_( true ) + , isNull_( true ) +{ + iterator_.array_ = ValueInternalArray::IteratorState(); +} +#endif + + +#ifndef JSON_VALUE_USE_INTERNAL_MAP +ValueIteratorBase::ValueIteratorBase( const Value::ObjectValues::iterator ¤t ) + : current_( current ) + , isNull_( false ) +{ +} +#else +ValueIteratorBase::ValueIteratorBase( const ValueInternalArray::IteratorState &state ) + : isArray_( true ) +{ + iterator_.array_ = state; +} + + +ValueIteratorBase::ValueIteratorBase( const ValueInternalMap::IteratorState &state ) + : isArray_( false ) +{ + iterator_.map_ = state; +} +#endif + +Value & +ValueIteratorBase::deref() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + return current_->second; +#else + if ( isArray_ ) + return ValueInternalArray::dereference( iterator_.array_ ); + return ValueInternalMap::value( iterator_.map_ ); +#endif +} + + +void +ValueIteratorBase::increment() +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + ++current_; +#else + if ( isArray_ ) + ValueInternalArray::increment( iterator_.array_ ); + ValueInternalMap::increment( iterator_.map_ ); +#endif +} + + +void +ValueIteratorBase::decrement() +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + --current_; +#else + if ( isArray_ ) + ValueInternalArray::decrement( iterator_.array_ ); + ValueInternalMap::decrement( iterator_.map_ ); +#endif +} + + +ValueIteratorBase::difference_type +ValueIteratorBase::computeDistance( const SelfType &other ) const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP +# ifdef JSON_USE_CPPTL_SMALLMAP + return current_ - other.current_; +# else + // Iterator for null value are initialized using the default + // constructor, which initialize current_ to the default + // std::map::iterator. As begin() and end() are two instance + // of the default std::map::iterator, they can not be compared. + // To allow this, we handle this comparison specifically. + if ( isNull_ && other.isNull_ ) + { + return 0; + } + + + // Usage of std::distance is not portable (does not compile with Sun Studio 12 RogueWave STL, + // which is the one used by default). + // Using a portable hand-made version for non random iterator instead: + // return difference_type( std::distance( current_, other.current_ ) ); + difference_type myDistance = 0; + for ( Value::ObjectValues::iterator it = current_; it != other.current_; ++it ) + { + ++myDistance; + } + return myDistance; +# endif +#else + if ( isArray_ ) + return ValueInternalArray::distance( iterator_.array_, other.iterator_.array_ ); + return ValueInternalMap::distance( iterator_.map_, other.iterator_.map_ ); +#endif +} + + +bool +ValueIteratorBase::isEqual( const SelfType &other ) const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + if ( isNull_ ) + { + return other.isNull_; + } + return current_ == other.current_; +#else + if ( isArray_ ) + return ValueInternalArray::equals( iterator_.array_, other.iterator_.array_ ); + return ValueInternalMap::equals( iterator_.map_, other.iterator_.map_ ); +#endif +} + + +void +ValueIteratorBase::copy( const SelfType &other ) +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + current_ = other.current_; +#else + if ( isArray_ ) + iterator_.array_ = other.iterator_.array_; + iterator_.map_ = other.iterator_.map_; +#endif +} + + +Value +ValueIteratorBase::key() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + const Value::CZString czstring = (*current_).first; + if ( czstring.c_str() ) + { + if ( czstring.isStaticString() ) + return Value( StaticString( czstring.c_str() ) ); + return Value( czstring.c_str() ); + } + return Value( czstring.index() ); +#else + if ( isArray_ ) + return Value( ValueInternalArray::indexOf( iterator_.array_ ) ); + bool isStatic; + const char *memberName = ValueInternalMap::key( iterator_.map_, isStatic ); + if ( isStatic ) + return Value( StaticString( memberName ) ); + return Value( memberName ); +#endif +} + + +UInt +ValueIteratorBase::index() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + const Value::CZString czstring = (*current_).first; + if ( !czstring.c_str() ) + return czstring.index(); + return Value::UInt( -1 ); +#else + if ( isArray_ ) + return Value::UInt( ValueInternalArray::indexOf( iterator_.array_ ) ); + return Value::UInt( -1 ); +#endif +} + + +const char * +ValueIteratorBase::memberName() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + const char *name = (*current_).first.c_str(); + return name ? name : ""; +#else + if ( !isArray_ ) + return ValueInternalMap::key( iterator_.map_ ); + return ""; +#endif +} + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueConstIterator +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +ValueConstIterator::ValueConstIterator() +{ +} + + +#ifndef JSON_VALUE_USE_INTERNAL_MAP +ValueConstIterator::ValueConstIterator( const Value::ObjectValues::iterator ¤t ) + : ValueIteratorBase( current ) +{ +} +#else +ValueConstIterator::ValueConstIterator( const ValueInternalArray::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} + +ValueConstIterator::ValueConstIterator( const ValueInternalMap::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} +#endif + +ValueConstIterator & +ValueConstIterator::operator =( const ValueIteratorBase &other ) +{ + copy( other ); + return *this; +} + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueIterator +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +ValueIterator::ValueIterator() +{ +} + + +#ifndef JSON_VALUE_USE_INTERNAL_MAP +ValueIterator::ValueIterator( const Value::ObjectValues::iterator ¤t ) + : ValueIteratorBase( current ) +{ +} +#else +ValueIterator::ValueIterator( const ValueInternalArray::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} + +ValueIterator::ValueIterator( const ValueInternalMap::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} +#endif + +ValueIterator::ValueIterator( const ValueConstIterator &other ) + : ValueIteratorBase( other ) +{ +} + +ValueIterator::ValueIterator( const ValueIterator &other ) + : ValueIteratorBase( other ) +{ +} + +ValueIterator & +ValueIterator::operator =( const SelfType &other ) +{ + copy( other ); + return *this; +} + +} // namespace Json + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_valueiterator.inl +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_value.cpp +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#if !defined(JSON_IS_AMALGAMATION) +# include +# include +# ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR +# include "json_batchallocator.h" +# endif // #ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR +#endif // if !defined(JSON_IS_AMALGAMATION) +#include +#include +#include +#include +#include +#ifdef JSON_USE_CPPTL +# include +#endif +#include // size_t + +#define JSON_ASSERT_UNREACHABLE assert( false ) +#define JSON_ASSERT( condition ) assert( condition ); // @todo <= change this into an exception throw +#define JSON_FAIL_MESSAGE( message ) throw std::runtime_error( message ); +#define JSON_ASSERT_MESSAGE( condition, message ) if (!( condition )) JSON_FAIL_MESSAGE( message ) + +namespace Json { + +const Value Value::null; +const Int Value::minInt = Int( ~(UInt(-1)/2) ); +const Int Value::maxInt = Int( UInt(-1)/2 ); +const UInt Value::maxUInt = UInt(-1); +const Int64 Value::minInt64 = Int64( ~(UInt64(-1)/2) ); +const Int64 Value::maxInt64 = Int64( UInt64(-1)/2 ); +const UInt64 Value::maxUInt64 = UInt64(-1); +const LargestInt Value::minLargestInt = LargestInt( ~(LargestUInt(-1)/2) ); +const LargestInt Value::maxLargestInt = LargestInt( LargestUInt(-1)/2 ); +const LargestUInt Value::maxLargestUInt = LargestUInt(-1); + + +/// Unknown size marker +static const unsigned int unknown = -1; + + +/** Duplicates the specified string value. + * @param value Pointer to the string to duplicate. Must be zero-terminated if + * length is "unknown". + * @param length Length of the value. if equals to unknown, then it will be + * computed using strlen(value). + * @return Pointer on the duplicate instance of string. + */ +static inline char * +duplicateStringValue( const char *value, + unsigned int length = unknown ) +{ + if ( length == unknown ) + length = static_cast(strlen(value)); + char *newString = static_cast( malloc( length + 1 ) ); + JSON_ASSERT_MESSAGE( newString != 0, "Failed to allocate string value buffer" ); + memcpy( newString, value, length ); + newString[length] = 0; + return newString; +} + + +/** Free the string duplicated by duplicateStringValue(). + */ +static inline void +releaseStringValue( char *value ) +{ + if ( value ) + free( value ); +} + +} // namespace Json + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ValueInternals... +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +#if !defined(JSON_IS_AMALGAMATION) +# ifdef JSON_VALUE_USE_INTERNAL_MAP +# include "json_internalarray.inl" +# include "json_internalmap.inl" +# endif // JSON_VALUE_USE_INTERNAL_MAP + +# include "json_valueiterator.inl" +#endif // if !defined(JSON_IS_AMALGAMATION) + +namespace Json { + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class Value::CommentInfo +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + + +Value::CommentInfo::CommentInfo() + : comment_( 0 ) +{ +} + +Value::CommentInfo::~CommentInfo() +{ + if ( comment_ ) + releaseStringValue( comment_ ); +} + + +void +Value::CommentInfo::setComment( const char *text ) +{ + if ( comment_ ) + releaseStringValue( comment_ ); + JSON_ASSERT( text != 0 ); + JSON_ASSERT_MESSAGE( text[0]=='\0' || text[0]=='/', "Comments must start with /"); + // It seems that /**/ style comments are acceptable as well. + comment_ = duplicateStringValue( text ); +} + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class Value::CZString +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +# ifndef JSON_VALUE_USE_INTERNAL_MAP + +// Notes: index_ indicates if the string was allocated when +// a string is stored. + +Value::CZString::CZString( ArrayIndex index ) + : cstr_( 0 ) + , index_( index ) +{ +} + +Value::CZString::CZString( const char *cstr, DuplicationPolicy allocate ) + : cstr_( allocate == duplicate ? duplicateStringValue(cstr) + : cstr ) + , index_( allocate ) +{ +} + +Value::CZString::CZString( const CZString &other ) +: cstr_( other.index_ != noDuplication && other.cstr_ != 0 + ? duplicateStringValue( other.cstr_ ) + : other.cstr_ ) + , index_( other.cstr_ ? (other.index_ == noDuplication ? static_cast(noDuplication) : static_cast(duplicate)) + : other.index_ ) +{ +} + +Value::CZString::~CZString() +{ + if ( cstr_ && index_ == duplicate ) + releaseStringValue( const_cast( cstr_ ) ); +} + +void +Value::CZString::swap( CZString &other ) +{ + std::swap( cstr_, other.cstr_ ); + std::swap( index_, other.index_ ); +} + +Value::CZString & +Value::CZString::operator =( const CZString &other ) +{ + CZString temp( other ); + swap( temp ); + return *this; +} + +bool +Value::CZString::operator<( const CZString &other ) const +{ + if ( cstr_ ) + return strcmp( cstr_, other.cstr_ ) < 0; + return index_ < other.index_; +} + +bool +Value::CZString::operator==( const CZString &other ) const +{ + if ( cstr_ ) + return strcmp( cstr_, other.cstr_ ) == 0; + return index_ == other.index_; +} + + +ArrayIndex +Value::CZString::index() const +{ + return index_; +} + + +const char * +Value::CZString::c_str() const +{ + return cstr_; +} + +bool +Value::CZString::isStaticString() const +{ + return index_ == noDuplication; +} + +#endif // ifndef JSON_VALUE_USE_INTERNAL_MAP + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class Value::Value +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +/*! \internal Default constructor initialization must be equivalent to: + * memset( this, 0, sizeof(Value) ) + * This optimization is used in ValueInternalMap fast allocator. + */ +Value::Value( ValueType type ) + : type_( type ) + , allocated_( 0 ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + switch ( type ) + { + case nullValue: + break; + case intValue: + case uintValue: + value_.int_ = 0; + break; + case realValue: + value_.real_ = 0.0; + break; + case stringValue: + value_.string_ = 0; + break; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + value_.map_ = new ObjectValues(); + break; +#else + case arrayValue: + value_.array_ = arrayAllocator()->newArray(); + break; + case objectValue: + value_.map_ = mapAllocator()->newMap(); + break; +#endif + case booleanValue: + value_.bool_ = false; + break; + default: + JSON_ASSERT_UNREACHABLE; + } +} + + +#if defined(JSON_HAS_INT64) +Value::Value( UInt value ) + : type_( uintValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.uint_ = value; +} + +Value::Value( Int value ) + : type_( intValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.int_ = value; +} + +#endif // if defined(JSON_HAS_INT64) + + +Value::Value( Int64 value ) + : type_( intValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.int_ = value; +} + + +Value::Value( UInt64 value ) + : type_( uintValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.uint_ = value; +} + +Value::Value( double value ) + : type_( realValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.real_ = value; +} + +Value::Value( const char *value ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = duplicateStringValue( value ); +} + + +Value::Value( const char *beginValue, + const char *endValue ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = duplicateStringValue( beginValue, + static_cast(endValue - beginValue) ); +} + + +Value::Value( const std::string &value ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = duplicateStringValue( value.c_str(), + static_cast(value.length()) ); + +} + +Value::Value( const StaticString &value ) + : type_( stringValue ) + , allocated_( false ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = const_cast( value.c_str() ); +} + + +# ifdef JSON_USE_CPPTL +Value::Value( const CppTL::ConstString &value ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = duplicateStringValue( value, value.length() ); +} +# endif + +Value::Value( bool value ) + : type_( booleanValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.bool_ = value; +} + + +Value::Value( const Value &other ) + : type_( other.type_ ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + switch ( type_ ) + { + case nullValue: + case intValue: + case uintValue: + case realValue: + case booleanValue: + value_ = other.value_; + break; + case stringValue: + if ( other.value_.string_ ) + { + value_.string_ = duplicateStringValue( other.value_.string_ ); + allocated_ = true; + } + else + value_.string_ = 0; + break; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + value_.map_ = new ObjectValues( *other.value_.map_ ); + break; +#else + case arrayValue: + value_.array_ = arrayAllocator()->newArrayCopy( *other.value_.array_ ); + break; + case objectValue: + value_.map_ = mapAllocator()->newMapCopy( *other.value_.map_ ); + break; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + if ( other.comments_ ) + { + comments_ = new CommentInfo[numberOfCommentPlacement]; + for ( int comment =0; comment < numberOfCommentPlacement; ++comment ) + { + const CommentInfo &otherComment = other.comments_[comment]; + if ( otherComment.comment_ ) + comments_[comment].setComment( otherComment.comment_ ); + } + } +} + + +Value::~Value() +{ + switch ( type_ ) + { + case nullValue: + case intValue: + case uintValue: + case realValue: + case booleanValue: + break; + case stringValue: + if ( allocated_ ) + releaseStringValue( value_.string_ ); + break; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + delete value_.map_; + break; +#else + case arrayValue: + arrayAllocator()->destructArray( value_.array_ ); + break; + case objectValue: + mapAllocator()->destructMap( value_.map_ ); + break; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + + if ( comments_ ) + delete[] comments_; +} + +Value & +Value::operator=( const Value &other ) +{ + Value temp( other ); + swap( temp ); + return *this; +} + +void +Value::swap( Value &other ) +{ + ValueType temp = type_; + type_ = other.type_; + other.type_ = temp; + std::swap( value_, other.value_ ); + int temp2 = allocated_; + allocated_ = other.allocated_; + other.allocated_ = temp2; +} + +ValueType +Value::type() const +{ + return type_; +} + + +int +Value::compare( const Value &other ) const +{ + if ( *this < other ) + return -1; + if ( *this > other ) + return 1; + return 0; +} + + +bool +Value::operator <( const Value &other ) const +{ + int typeDelta = type_ - other.type_; + if ( typeDelta ) + return typeDelta < 0 ? true : false; + switch ( type_ ) + { + case nullValue: + return false; + case intValue: + return value_.int_ < other.value_.int_; + case uintValue: + return value_.uint_ < other.value_.uint_; + case realValue: + return value_.real_ < other.value_.real_; + case booleanValue: + return value_.bool_ < other.value_.bool_; + case stringValue: + return ( value_.string_ == 0 && other.value_.string_ ) + || ( other.value_.string_ + && value_.string_ + && strcmp( value_.string_, other.value_.string_ ) < 0 ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + { + int delta = int( value_.map_->size() - other.value_.map_->size() ); + if ( delta ) + return delta < 0; + return (*value_.map_) < (*other.value_.map_); + } +#else + case arrayValue: + return value_.array_->compare( *(other.value_.array_) ) < 0; + case objectValue: + return value_.map_->compare( *(other.value_.map_) ) < 0; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable +} + +bool +Value::operator <=( const Value &other ) const +{ + return !(other < *this); +} + +bool +Value::operator >=( const Value &other ) const +{ + return !(*this < other); +} + +bool +Value::operator >( const Value &other ) const +{ + return other < *this; +} + +bool +Value::operator ==( const Value &other ) const +{ + //if ( type_ != other.type_ ) + // GCC 2.95.3 says: + // attempt to take address of bit-field structure member `Json::Value::type_' + // Beats me, but a temp solves the problem. + int temp = other.type_; + if ( type_ != temp ) + return false; + switch ( type_ ) + { + case nullValue: + return true; + case intValue: + return value_.int_ == other.value_.int_; + case uintValue: + return value_.uint_ == other.value_.uint_; + case realValue: + return value_.real_ == other.value_.real_; + case booleanValue: + return value_.bool_ == other.value_.bool_; + case stringValue: + return ( value_.string_ == other.value_.string_ ) + || ( other.value_.string_ + && value_.string_ + && strcmp( value_.string_, other.value_.string_ ) == 0 ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + return value_.map_->size() == other.value_.map_->size() + && (*value_.map_) == (*other.value_.map_); +#else + case arrayValue: + return value_.array_->compare( *(other.value_.array_) ) == 0; + case objectValue: + return value_.map_->compare( *(other.value_.map_) ) == 0; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable +} + +bool +Value::operator !=( const Value &other ) const +{ + return !( *this == other ); +} + +const char * +Value::asCString() const +{ + JSON_ASSERT( type_ == stringValue ); + return value_.string_; +} + + +std::string +Value::asString() const +{ + switch ( type_ ) + { + case nullValue: + return ""; + case stringValue: + return value_.string_ ? value_.string_ : ""; + case booleanValue: + return value_.bool_ ? "true" : "false"; + case intValue: + case uintValue: + case realValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to string" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return ""; // unreachable +} + +# ifdef JSON_USE_CPPTL +CppTL::ConstString +Value::asConstString() const +{ + return CppTL::ConstString( asString().c_str() ); +} +# endif + + +Value::Int +Value::asInt() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + JSON_ASSERT_MESSAGE( value_.int_ >= minInt && value_.int_ <= maxInt, "unsigned integer out of signed int range" ); + return Int(value_.int_); + case uintValue: + JSON_ASSERT_MESSAGE( value_.uint_ <= UInt(maxInt), "unsigned integer out of signed int range" ); + return Int(value_.uint_); + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= minInt && value_.real_ <= maxInt, "Real out of signed integer range" ); + return Int( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to int" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + + +Value::UInt +Value::asUInt() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + JSON_ASSERT_MESSAGE( value_.int_ >= 0, "Negative integer can not be converted to unsigned integer" ); + JSON_ASSERT_MESSAGE( value_.int_ <= maxUInt, "signed integer out of UInt range" ); + return UInt(value_.int_); + case uintValue: + JSON_ASSERT_MESSAGE( value_.uint_ <= maxUInt, "unsigned integer out of UInt range" ); + return UInt(value_.uint_); + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= 0 && value_.real_ <= maxUInt, "Real out of unsigned integer range" ); + return UInt( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to uint" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + + +# if defined(JSON_HAS_INT64) + +Value::Int64 +Value::asInt64() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + return value_.int_; + case uintValue: + JSON_ASSERT_MESSAGE( value_.uint_ <= UInt64(maxInt64), "unsigned integer out of Int64 range" ); + return value_.uint_; + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= minInt64 && value_.real_ <= maxInt64, "Real out of Int64 range" ); + return Int( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to Int64" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + + +Value::UInt64 +Value::asUInt64() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + JSON_ASSERT_MESSAGE( value_.int_ >= 0, "Negative integer can not be converted to UInt64" ); + return value_.int_; + case uintValue: + return value_.uint_; + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= 0 && value_.real_ <= maxUInt64, "Real out of UInt64 range" ); + return UInt( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to UInt64" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} +# endif // if defined(JSON_HAS_INT64) + + +LargestInt +Value::asLargestInt() const +{ +#if defined(JSON_NO_INT64) + return asInt(); +#else + return asInt64(); +#endif +} + + +LargestUInt +Value::asLargestUInt() const +{ +#if defined(JSON_NO_INT64) + return asUInt(); +#else + return asUInt64(); +#endif +} + + +double +Value::asDouble() const +{ + switch ( type_ ) + { + case nullValue: + return 0.0; + case intValue: + return static_cast( value_.int_ ); + case uintValue: +#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + return static_cast( value_.uint_ ); +#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + return static_cast( Int(value_.uint_/2) ) * 2 + Int(value_.uint_ & 1); +#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + case realValue: + return value_.real_; + case booleanValue: + return value_.bool_ ? 1.0 : 0.0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to double" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + +float +Value::asFloat() const +{ + switch ( type_ ) + { + case nullValue: + return 0.0f; + case intValue: + return static_cast( value_.int_ ); + case uintValue: +#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + return static_cast( value_.uint_ ); +#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + return static_cast( Int(value_.uint_/2) ) * 2 + Int(value_.uint_ & 1); +#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + case realValue: + return static_cast( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1.0f : 0.0f; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to float" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0.0f; // unreachable; +} + +bool +Value::asBool() const +{ + switch ( type_ ) + { + case nullValue: + return false; + case intValue: + case uintValue: + return value_.int_ != 0; + case realValue: + return value_.real_ != 0.0; + case booleanValue: + return value_.bool_; + case stringValue: + return value_.string_ && value_.string_[0] != 0; + case arrayValue: + case objectValue: + return value_.map_->size() != 0; + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable; +} + + +bool +Value::isConvertibleTo( ValueType other ) const +{ + switch ( type_ ) + { + case nullValue: + return true; + case intValue: + return ( other == nullValue && value_.int_ == 0 ) + || other == intValue + || ( other == uintValue && value_.int_ >= 0 ) + || other == realValue + || other == stringValue + || other == booleanValue; + case uintValue: + return ( other == nullValue && value_.uint_ == 0 ) + || ( other == intValue && value_.uint_ <= static_cast(maxInt) ) + || other == uintValue + || other == realValue + || other == stringValue + || other == booleanValue; + case realValue: + return ( other == nullValue && value_.real_ == 0.0 ) + || ( other == intValue && value_.real_ >= minInt && value_.real_ <= maxInt ) + || ( other == uintValue && value_.real_ >= 0 && value_.real_ <= maxUInt ) + || other == realValue + || other == stringValue + || other == booleanValue; + case booleanValue: + return ( other == nullValue && value_.bool_ == false ) + || other == intValue + || other == uintValue + || other == realValue + || other == stringValue + || other == booleanValue; + case stringValue: + return other == stringValue + || ( other == nullValue && (!value_.string_ || value_.string_[0] == 0) ); + case arrayValue: + return other == arrayValue + || ( other == nullValue && value_.map_->size() == 0 ); + case objectValue: + return other == objectValue + || ( other == nullValue && value_.map_->size() == 0 ); + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable; +} + + +/// Number of values in array or object +ArrayIndex +Value::size() const +{ + switch ( type_ ) + { + case nullValue: + case intValue: + case uintValue: + case realValue: + case booleanValue: + case stringValue: + return 0; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: // size of the array is highest index + 1 + if ( !value_.map_->empty() ) + { + ObjectValues::const_iterator itLast = value_.map_->end(); + --itLast; + return (*itLast).first.index()+1; + } + return 0; + case objectValue: + return ArrayIndex( value_.map_->size() ); +#else + case arrayValue: + return Int( value_.array_->size() ); + case objectValue: + return Int( value_.map_->size() ); +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + + +bool +Value::empty() const +{ + if ( isNull() || isArray() || isObject() ) + return size() == 0u; + else + return false; +} + + +bool +Value::operator!() const +{ + return isNull(); +} + + +void +Value::clear() +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue || type_ == objectValue ); + + switch ( type_ ) + { +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + value_.map_->clear(); + break; +#else + case arrayValue: + value_.array_->clear(); + break; + case objectValue: + value_.map_->clear(); + break; +#endif + default: + break; + } +} + +void +Value::resize( ArrayIndex newSize ) +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); + if ( type_ == nullValue ) + *this = Value( arrayValue ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + ArrayIndex oldSize = size(); + if ( newSize == 0 ) + clear(); + else if ( newSize > oldSize ) + (*this)[ newSize - 1 ]; + else + { + for ( ArrayIndex index = newSize; index < oldSize; ++index ) + { + value_.map_->erase( index ); + } + assert( size() == newSize ); + } +#else + value_.array_->resize( newSize ); +#endif +} + + +Value & +Value::operator[]( ArrayIndex index ) +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); + if ( type_ == nullValue ) + *this = Value( arrayValue ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString key( index ); + ObjectValues::iterator it = value_.map_->lower_bound( key ); + if ( it != value_.map_->end() && (*it).first == key ) + return (*it).second; + + ObjectValues::value_type defaultValue( key, null ); + it = value_.map_->insert( it, defaultValue ); + return (*it).second; +#else + return value_.array_->resolveReference( index ); +#endif +} + + +Value & +Value::operator[]( int index ) +{ + JSON_ASSERT( index >= 0 ); + return (*this)[ ArrayIndex(index) ]; +} + + +const Value & +Value::operator[]( ArrayIndex index ) const +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); + if ( type_ == nullValue ) + return null; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString key( index ); + ObjectValues::const_iterator it = value_.map_->find( key ); + if ( it == value_.map_->end() ) + return null; + return (*it).second; +#else + Value *value = value_.array_->find( index ); + return value ? *value : null; +#endif +} + + +const Value & +Value::operator[]( int index ) const +{ + JSON_ASSERT( index >= 0 ); + return (*this)[ ArrayIndex(index) ]; +} + + +Value & +Value::operator[]( const char *key ) +{ + return resolveReference( key, false ); +} + + +Value & +Value::resolveReference( const char *key, + bool isStatic ) +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + *this = Value( objectValue ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString actualKey( key, isStatic ? CZString::noDuplication + : CZString::duplicateOnCopy ); + ObjectValues::iterator it = value_.map_->lower_bound( actualKey ); + if ( it != value_.map_->end() && (*it).first == actualKey ) + return (*it).second; + + ObjectValues::value_type defaultValue( actualKey, null ); + it = value_.map_->insert( it, defaultValue ); + Value &value = (*it).second; + return value; +#else + return value_.map_->resolveReference( key, isStatic ); +#endif +} + + +Value +Value::get( ArrayIndex index, + const Value &defaultValue ) const +{ + const Value *value = &((*this)[index]); + return value == &null ? defaultValue : *value; +} + + +bool +Value::isValidIndex( ArrayIndex index ) const +{ + return index < size(); +} + + + +const Value & +Value::operator[]( const char *key ) const +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + return null; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString actualKey( key, CZString::noDuplication ); + ObjectValues::const_iterator it = value_.map_->find( actualKey ); + if ( it == value_.map_->end() ) + return null; + return (*it).second; +#else + const Value *value = value_.map_->find( key ); + return value ? *value : null; +#endif +} + + +Value & +Value::operator[]( const std::string &key ) +{ + return (*this)[ key.c_str() ]; +} + + +const Value & +Value::operator[]( const std::string &key ) const +{ + return (*this)[ key.c_str() ]; +} + +Value & +Value::operator[]( const StaticString &key ) +{ + return resolveReference( key, true ); +} + + +# ifdef JSON_USE_CPPTL +Value & +Value::operator[]( const CppTL::ConstString &key ) +{ + return (*this)[ key.c_str() ]; +} + + +const Value & +Value::operator[]( const CppTL::ConstString &key ) const +{ + return (*this)[ key.c_str() ]; +} +# endif + + +Value & +Value::append( const Value &value ) +{ + return (*this)[size()] = value; +} + + +Value +Value::get( const char *key, + const Value &defaultValue ) const +{ + const Value *value = &((*this)[key]); + return value == &null ? defaultValue : *value; +} + + +Value +Value::get( const std::string &key, + const Value &defaultValue ) const +{ + return get( key.c_str(), defaultValue ); +} + +Value +Value::removeMember( const char* key ) +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + return null; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString actualKey( key, CZString::noDuplication ); + ObjectValues::iterator it = value_.map_->find( actualKey ); + if ( it == value_.map_->end() ) + return null; + Value old(it->second); + value_.map_->erase(it); + return old; +#else + Value *value = value_.map_->find( key ); + if (value){ + Value old(*value); + value_.map_.remove( key ); + return old; + } else { + return null; + } +#endif +} + +Value +Value::removeMember( const std::string &key ) +{ + return removeMember( key.c_str() ); +} + +# ifdef JSON_USE_CPPTL +Value +Value::get( const CppTL::ConstString &key, + const Value &defaultValue ) const +{ + return get( key.c_str(), defaultValue ); +} +# endif + +bool +Value::isMember( const char *key ) const +{ + const Value *value = &((*this)[key]); + return value != &null; +} + + +bool +Value::isMember( const std::string &key ) const +{ + return isMember( key.c_str() ); +} + + +# ifdef JSON_USE_CPPTL +bool +Value::isMember( const CppTL::ConstString &key ) const +{ + return isMember( key.c_str() ); +} +#endif + +Value::Members +Value::getMemberNames() const +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + return Value::Members(); + Members members; + members.reserve( value_.map_->size() ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + ObjectValues::const_iterator it = value_.map_->begin(); + ObjectValues::const_iterator itEnd = value_.map_->end(); + for ( ; it != itEnd; ++it ) + members.push_back( std::string( (*it).first.c_str() ) ); +#else + ValueInternalMap::IteratorState it; + ValueInternalMap::IteratorState itEnd; + value_.map_->makeBeginIterator( it ); + value_.map_->makeEndIterator( itEnd ); + for ( ; !ValueInternalMap::equals( it, itEnd ); ValueInternalMap::increment(it) ) + members.push_back( std::string( ValueInternalMap::key( it ) ) ); +#endif + return members; +} +// +//# ifdef JSON_USE_CPPTL +//EnumMemberNames +//Value::enumMemberNames() const +//{ +// if ( type_ == objectValue ) +// { +// return CppTL::Enum::any( CppTL::Enum::transform( +// CppTL::Enum::keys( *(value_.map_), CppTL::Type() ), +// MemberNamesTransform() ) ); +// } +// return EnumMemberNames(); +//} +// +// +//EnumValues +//Value::enumValues() const +//{ +// if ( type_ == objectValue || type_ == arrayValue ) +// return CppTL::Enum::anyValues( *(value_.map_), +// CppTL::Type() ); +// return EnumValues(); +//} +// +//# endif + + +bool +Value::isNull() const +{ + return type_ == nullValue; +} + + +bool +Value::isBool() const +{ + return type_ == booleanValue; +} + + +bool +Value::isInt() const +{ + return type_ == intValue; +} + + +bool +Value::isUInt() const +{ + return type_ == uintValue; +} + + +bool +Value::isIntegral() const +{ + return type_ == intValue + || type_ == uintValue + || type_ == booleanValue; +} + + +bool +Value::isDouble() const +{ + return type_ == realValue; +} + + +bool +Value::isNumeric() const +{ + return isIntegral() || isDouble(); +} + + +bool +Value::isString() const +{ + return type_ == stringValue; +} + + +bool +Value::isArray() const +{ + return type_ == nullValue || type_ == arrayValue; +} + + +bool +Value::isObject() const +{ + return type_ == nullValue || type_ == objectValue; +} + + +void +Value::setComment( const char *comment, + CommentPlacement placement ) +{ + if ( !comments_ ) + comments_ = new CommentInfo[numberOfCommentPlacement]; + comments_[placement].setComment( comment ); +} + + +void +Value::setComment( const std::string &comment, + CommentPlacement placement ) +{ + setComment( comment.c_str(), placement ); +} + + +bool +Value::hasComment( CommentPlacement placement ) const +{ + return comments_ != 0 && comments_[placement].comment_ != 0; +} + +std::string +Value::getComment( CommentPlacement placement ) const +{ + if ( hasComment(placement) ) + return comments_[placement].comment_; + return ""; +} + + +std::string +Value::toStyledString() const +{ + StyledWriter writer; + return writer.write( *this ); +} + + +Value::const_iterator +Value::begin() const +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeBeginIterator( it ); + return const_iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeBeginIterator( it ); + return const_iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return const_iterator( value_.map_->begin() ); + break; +#endif + default: + break; + } + return const_iterator(); +} + +Value::const_iterator +Value::end() const +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeEndIterator( it ); + return const_iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeEndIterator( it ); + return const_iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return const_iterator( value_.map_->end() ); + break; +#endif + default: + break; + } + return const_iterator(); +} + + +Value::iterator +Value::begin() +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeBeginIterator( it ); + return iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeBeginIterator( it ); + return iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return iterator( value_.map_->begin() ); + break; +#endif + default: + break; + } + return iterator(); +} + +Value::iterator +Value::end() +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeEndIterator( it ); + return iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeEndIterator( it ); + return iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return iterator( value_.map_->end() ); + break; +#endif + default: + break; + } + return iterator(); +} + + +// class PathArgument +// ////////////////////////////////////////////////////////////////// + +PathArgument::PathArgument() + : kind_( kindNone ) +{ +} + + +PathArgument::PathArgument( ArrayIndex index ) + : index_( index ) + , kind_( kindIndex ) +{ +} + + +PathArgument::PathArgument( const char *key ) + : key_( key ) + , kind_( kindKey ) +{ +} + + +PathArgument::PathArgument( const std::string &key ) + : key_( key.c_str() ) + , kind_( kindKey ) +{ +} + +// class Path +// ////////////////////////////////////////////////////////////////// + +Path::Path( const std::string &path, + const PathArgument &a1, + const PathArgument &a2, + const PathArgument &a3, + const PathArgument &a4, + const PathArgument &a5 ) +{ + InArgs in; + in.push_back( &a1 ); + in.push_back( &a2 ); + in.push_back( &a3 ); + in.push_back( &a4 ); + in.push_back( &a5 ); + makePath( path, in ); +} + + +void +Path::makePath( const std::string &path, + const InArgs &in ) +{ + const char *current = path.c_str(); + const char *end = current + path.length(); + InArgs::const_iterator itInArg = in.begin(); + while ( current != end ) + { + if ( *current == '[' ) + { + ++current; + if ( *current == '%' ) + addPathInArg( path, in, itInArg, PathArgument::kindIndex ); + else + { + ArrayIndex index = 0; + for ( ; current != end && *current >= '0' && *current <= '9'; ++current ) + index = index * 10 + ArrayIndex(*current - '0'); + args_.push_back( index ); + } + if ( current == end || *current++ != ']' ) + invalidPath( path, int(current - path.c_str()) ); + } + else if ( *current == '%' ) + { + addPathInArg( path, in, itInArg, PathArgument::kindKey ); + ++current; + } + else if ( *current == '.' ) + { + ++current; + } + else + { + const char *beginName = current; + while ( current != end && !strchr( "[.", *current ) ) + ++current; + args_.push_back( std::string( beginName, current ) ); + } + } +} + + +void +Path::addPathInArg( const std::string &/*path*/, + const InArgs &in, + InArgs::const_iterator &itInArg, + PathArgument::Kind kind ) +{ + if ( itInArg == in.end() ) + { + // Error: missing argument %d + } + else if ( (*itInArg)->kind_ != kind ) + { + // Error: bad argument type + } + else + { + args_.push_back( **itInArg ); + } +} + + +void +Path::invalidPath( const std::string &/*path*/, + int /*location*/ ) +{ + // Error: invalid path. +} + + +const Value & +Path::resolve( const Value &root ) const +{ + const Value *node = &root; + for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) + { + const PathArgument &arg = *it; + if ( arg.kind_ == PathArgument::kindIndex ) + { + if ( !node->isArray() || node->isValidIndex( arg.index_ ) ) + { + // Error: unable to resolve path (array value expected at position... + } + node = &((*node)[arg.index_]); + } + else if ( arg.kind_ == PathArgument::kindKey ) + { + if ( !node->isObject() ) + { + // Error: unable to resolve path (object value expected at position...) + } + node = &((*node)[arg.key_]); + if ( node == &Value::null ) + { + // Error: unable to resolve path (object has no member named '' at position...) + } + } + } + return *node; +} + + +Value +Path::resolve( const Value &root, + const Value &defaultValue ) const +{ + const Value *node = &root; + for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) + { + const PathArgument &arg = *it; + if ( arg.kind_ == PathArgument::kindIndex ) + { + if ( !node->isArray() || node->isValidIndex( arg.index_ ) ) + return defaultValue; + node = &((*node)[arg.index_]); + } + else if ( arg.kind_ == PathArgument::kindKey ) + { + if ( !node->isObject() ) + return defaultValue; + node = &((*node)[arg.key_]); + if ( node == &Value::null ) + return defaultValue; + } + } + return *node; +} + + +Value & +Path::make( Value &root ) const +{ + Value *node = &root; + for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) + { + const PathArgument &arg = *it; + if ( arg.kind_ == PathArgument::kindIndex ) + { + if ( !node->isArray() ) + { + // Error: node is not an array at position ... + } + node = &((*node)[arg.index_]); + } + else if ( arg.kind_ == PathArgument::kindKey ) + { + if ( !node->isObject() ) + { + // Error: node is not an object at position... + } + node = &((*node)[arg.key_]); + } + } + return *node; +} + + +} // namespace Json + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_value.cpp +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_writer.cpp +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#if !defined(JSON_IS_AMALGAMATION) +# include +# include "json_tool.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +#include +#include +#include +#include +#include +#include +#include + +#if _MSC_VER >= 1400 // VC++ 8.0 +#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated. +#endif + +namespace Json { + +static bool containsControlCharacter( const char* str ) +{ + while ( *str ) + { + if ( isControlCharacter( *(str++) ) ) + return true; + } + return false; +} + + +std::string valueToString( LargestInt value ) +{ + UIntToStringBuffer buffer; + char *current = buffer + sizeof(buffer); + bool isNegative = value < 0; + if ( isNegative ) + value = -value; + uintToString( LargestUInt(value), current ); + if ( isNegative ) + *--current = '-'; + assert( current >= buffer ); + return current; +} + + +std::string valueToString( LargestUInt value ) +{ + UIntToStringBuffer buffer; + char *current = buffer + sizeof(buffer); + uintToString( value, current ); + assert( current >= buffer ); + return current; +} + +#if defined(JSON_HAS_INT64) + +std::string valueToString( Int value ) +{ + return valueToString( LargestInt(value) ); +} + + +std::string valueToString( UInt value ) +{ + return valueToString( LargestUInt(value) ); +} + +#endif // # if defined(JSON_HAS_INT64) + + +std::string valueToString( double value ) +{ + char buffer[32]; +#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with visual studio 2005 to avoid warning. + sprintf_s(buffer, sizeof(buffer), "%#.16g", value); +#else + sprintf(buffer, "%#.16g", value); +#endif + char* ch = buffer + strlen(buffer) - 1; + if (*ch != '0') return buffer; // nothing to truncate, so save time + while(ch > buffer && *ch == '0'){ + --ch; + } + char* last_nonzero = ch; + while(ch >= buffer){ + switch(*ch){ + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + --ch; + continue; + case '.': + // Truncate zeroes to save bytes in output, but keep one. + *(last_nonzero+2) = '\0'; + return buffer; + default: + return buffer; + } + } + return buffer; +} + + +std::string valueToString( bool value ) +{ + return value ? "true" : "false"; +} + +std::string valueToQuotedString( const char *value ) +{ + // Not sure how to handle unicode... + if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL && !containsControlCharacter( value )) + return std::string("\"") + value + "\""; + // We have to walk value and escape any special characters. + // Appending to std::string is not efficient, but this should be rare. + // (Note: forward slashes are *not* rare, but I am not escaping them.) + std::string::size_type maxsize = strlen(value)*2 + 3; // allescaped+quotes+NULL + std::string result; + result.reserve(maxsize); // to avoid lots of mallocs + result += "\""; + for (const char* c=value; *c != 0; ++c) + { + switch(*c) + { + case '\"': + result += "\\\""; + break; + case '\\': + result += "\\\\"; + break; + case '\b': + result += "\\b"; + break; + case '\f': + result += "\\f"; + break; + case '\n': + result += "\\n"; + break; + case '\r': + result += "\\r"; + break; + case '\t': + result += "\\t"; + break; + //case '/': + // Even though \/ is considered a legal escape in JSON, a bare + // slash is also legal, so I see no reason to escape it. + // (I hope I am not misunderstanding something. + // blep notes: actually escaping \/ may be useful in javascript to avoid (*c); + result += oss.str(); + } + else + { + result += *c; + } + break; + } + } + result += "\""; + return result; +} + +// Class Writer +// ////////////////////////////////////////////////////////////////// +Writer::~Writer() +{ +} + + +// Class FastWriter +// ////////////////////////////////////////////////////////////////// + +FastWriter::FastWriter() + : yamlCompatiblityEnabled_( false ) +{ +} + + +void +FastWriter::enableYAMLCompatibility() +{ + yamlCompatiblityEnabled_ = true; +} + + +std::string +FastWriter::write( const Value &root ) +{ + document_ = ""; + writeValue( root ); + document_ += "\n"; + return document_; +} + + +void +FastWriter::writeValue( const Value &value ) +{ + switch ( value.type() ) + { + case nullValue: + document_ += "null"; + break; + case intValue: + document_ += valueToString( value.asLargestInt() ); + break; + case uintValue: + document_ += valueToString( value.asLargestUInt() ); + break; + case realValue: + document_ += valueToString( value.asDouble() ); + break; + case stringValue: + document_ += valueToQuotedString( value.asCString() ); + break; + case booleanValue: + document_ += valueToString( value.asBool() ); + break; + case arrayValue: + { + document_ += "["; + int size = value.size(); + for ( int index =0; index < size; ++index ) + { + if ( index > 0 ) + document_ += ","; + writeValue( value[index] ); + } + document_ += "]"; + } + break; + case objectValue: + { + Value::Members members( value.getMemberNames() ); + document_ += "{"; + for ( Value::Members::iterator it = members.begin(); + it != members.end(); + ++it ) + { + const std::string &name = *it; + if ( it != members.begin() ) + document_ += ","; + document_ += valueToQuotedString( name.c_str() ); + document_ += yamlCompatiblityEnabled_ ? ": " + : ":"; + writeValue( value[name] ); + } + document_ += "}"; + } + break; + } +} + + +// Class StyledWriter +// ////////////////////////////////////////////////////////////////// + +StyledWriter::StyledWriter() + : rightMargin_( 74 ) + , indentSize_( 3 ) +{ +} + + +std::string +StyledWriter::write( const Value &root ) +{ + document_ = ""; + addChildValues_ = false; + indentString_ = ""; + writeCommentBeforeValue( root ); + writeValue( root ); + writeCommentAfterValueOnSameLine( root ); + document_ += "\n"; + return document_; +} + + +void +StyledWriter::writeValue( const Value &value ) +{ + switch ( value.type() ) + { + case nullValue: + pushValue( "null" ); + break; + case intValue: + pushValue( valueToString( value.asLargestInt() ) ); + break; + case uintValue: + pushValue( valueToString( value.asLargestUInt() ) ); + break; + case realValue: + pushValue( valueToString( value.asDouble() ) ); + break; + case stringValue: + pushValue( valueToQuotedString( value.asCString() ) ); + break; + case booleanValue: + pushValue( valueToString( value.asBool() ) ); + break; + case arrayValue: + writeArrayValue( value); + break; + case objectValue: + { + Value::Members members( value.getMemberNames() ); + if ( members.empty() ) + pushValue( "{}" ); + else + { + writeWithIndent( "{" ); + indent(); + Value::Members::iterator it = members.begin(); + for (;;) + { + const std::string &name = *it; + const Value &childValue = value[name]; + writeCommentBeforeValue( childValue ); + writeWithIndent( valueToQuotedString( name.c_str() ) ); + document_ += " : "; + writeValue( childValue ); + if ( ++it == members.end() ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + document_ += ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "}" ); + } + } + break; + } +} + + +void +StyledWriter::writeArrayValue( const Value &value ) +{ + unsigned size = value.size(); + if ( size == 0 ) + pushValue( "[]" ); + else + { + bool isArrayMultiLine = isMultineArray( value ); + if ( isArrayMultiLine ) + { + writeWithIndent( "[" ); + indent(); + bool hasChildValue = !childValues_.empty(); + unsigned index =0; + for (;;) + { + const Value &childValue = value[index]; + writeCommentBeforeValue( childValue ); + if ( hasChildValue ) + writeWithIndent( childValues_[index] ); + else + { + writeIndent(); + writeValue( childValue ); + } + if ( ++index == size ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + document_ += ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "]" ); + } + else // output on a single line + { + assert( childValues_.size() == size ); + document_ += "[ "; + for ( unsigned index =0; index < size; ++index ) + { + if ( index > 0 ) + document_ += ", "; + document_ += childValues_[index]; + } + document_ += " ]"; + } + } +} + + +bool +StyledWriter::isMultineArray( const Value &value ) +{ + int size = value.size(); + bool isMultiLine = size*3 >= rightMargin_ ; + childValues_.clear(); + for ( int index =0; index < size && !isMultiLine; ++index ) + { + const Value &childValue = value[index]; + isMultiLine = isMultiLine || + ( (childValue.isArray() || childValue.isObject()) && + childValue.size() > 0 ); + } + if ( !isMultiLine ) // check if line length > max line length + { + childValues_.reserve( size ); + addChildValues_ = true; + int lineLength = 4 + (size-1)*2; // '[ ' + ', '*n + ' ]' + for ( int index =0; index < size && !isMultiLine; ++index ) + { + writeValue( value[index] ); + lineLength += int( childValues_[index].length() ); + isMultiLine = isMultiLine && hasCommentForValue( value[index] ); + } + addChildValues_ = false; + isMultiLine = isMultiLine || lineLength >= rightMargin_; + } + return isMultiLine; +} + + +void +StyledWriter::pushValue( const std::string &value ) +{ + if ( addChildValues_ ) + childValues_.push_back( value ); + else + document_ += value; +} + + +void +StyledWriter::writeIndent() +{ + if ( !document_.empty() ) + { + char last = document_[document_.length()-1]; + if ( last == ' ' ) // already indented + return; + if ( last != '\n' ) // Comments may add new-line + document_ += '\n'; + } + document_ += indentString_; +} + + +void +StyledWriter::writeWithIndent( const std::string &value ) +{ + writeIndent(); + document_ += value; +} + + +void +StyledWriter::indent() +{ + indentString_ += std::string( indentSize_, ' ' ); +} + + +void +StyledWriter::unindent() +{ + assert( int(indentString_.size()) >= indentSize_ ); + indentString_.resize( indentString_.size() - indentSize_ ); +} + + +void +StyledWriter::writeCommentBeforeValue( const Value &root ) +{ + if ( !root.hasComment( commentBefore ) ) + return; + document_ += normalizeEOL( root.getComment( commentBefore ) ); + document_ += "\n"; +} + + +void +StyledWriter::writeCommentAfterValueOnSameLine( const Value &root ) +{ + if ( root.hasComment( commentAfterOnSameLine ) ) + document_ += " " + normalizeEOL( root.getComment( commentAfterOnSameLine ) ); + + if ( root.hasComment( commentAfter ) ) + { + document_ += "\n"; + document_ += normalizeEOL( root.getComment( commentAfter ) ); + document_ += "\n"; + } +} + + +bool +StyledWriter::hasCommentForValue( const Value &value ) +{ + return value.hasComment( commentBefore ) + || value.hasComment( commentAfterOnSameLine ) + || value.hasComment( commentAfter ); +} + + +std::string +StyledWriter::normalizeEOL( const std::string &text ) +{ + std::string normalized; + normalized.reserve( text.length() ); + const char *begin = text.c_str(); + const char *end = begin + text.length(); + const char *current = begin; + while ( current != end ) + { + char c = *current++; + if ( c == '\r' ) // mac or dos EOL + { + if ( *current == '\n' ) // convert dos EOL + ++current; + normalized += '\n'; + } + else // handle unix EOL & other char + normalized += c; + } + return normalized; +} + + +// Class StyledStreamWriter +// ////////////////////////////////////////////////////////////////// + +StyledStreamWriter::StyledStreamWriter( std::string indentation ) + : document_(NULL) + , rightMargin_( 74 ) + , indentation_( indentation ) +{ +} + + +void +StyledStreamWriter::write( std::ostream &out, const Value &root ) +{ + document_ = &out; + addChildValues_ = false; + indentString_ = ""; + writeCommentBeforeValue( root ); + writeValue( root ); + writeCommentAfterValueOnSameLine( root ); + *document_ << "\n"; + document_ = NULL; // Forget the stream, for safety. +} + + +void +StyledStreamWriter::writeValue( const Value &value ) +{ + switch ( value.type() ) + { + case nullValue: + pushValue( "null" ); + break; + case intValue: + pushValue( valueToString( value.asLargestInt() ) ); + break; + case uintValue: + pushValue( valueToString( value.asLargestUInt() ) ); + break; + case realValue: + pushValue( valueToString( value.asDouble() ) ); + break; + case stringValue: + pushValue( valueToQuotedString( value.asCString() ) ); + break; + case booleanValue: + pushValue( valueToString( value.asBool() ) ); + break; + case arrayValue: + writeArrayValue( value); + break; + case objectValue: + { + Value::Members members( value.getMemberNames() ); + if ( members.empty() ) + pushValue( "{}" ); + else + { + writeWithIndent( "{" ); + indent(); + Value::Members::iterator it = members.begin(); + for (;;) + { + const std::string &name = *it; + const Value &childValue = value[name]; + writeCommentBeforeValue( childValue ); + writeWithIndent( valueToQuotedString( name.c_str() ) ); + *document_ << " : "; + writeValue( childValue ); + if ( ++it == members.end() ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + *document_ << ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "}" ); + } + } + break; + } +} + + +void +StyledStreamWriter::writeArrayValue( const Value &value ) +{ + unsigned size = value.size(); + if ( size == 0 ) + pushValue( "[]" ); + else + { + bool isArrayMultiLine = isMultineArray( value ); + if ( isArrayMultiLine ) + { + writeWithIndent( "[" ); + indent(); + bool hasChildValue = !childValues_.empty(); + unsigned index =0; + for (;;) + { + const Value &childValue = value[index]; + writeCommentBeforeValue( childValue ); + if ( hasChildValue ) + writeWithIndent( childValues_[index] ); + else + { + writeIndent(); + writeValue( childValue ); + } + if ( ++index == size ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + *document_ << ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "]" ); + } + else // output on a single line + { + assert( childValues_.size() == size ); + *document_ << "[ "; + for ( unsigned index =0; index < size; ++index ) + { + if ( index > 0 ) + *document_ << ", "; + *document_ << childValues_[index]; + } + *document_ << " ]"; + } + } +} + + +bool +StyledStreamWriter::isMultineArray( const Value &value ) +{ + int size = value.size(); + bool isMultiLine = size*3 >= rightMargin_ ; + childValues_.clear(); + for ( int index =0; index < size && !isMultiLine; ++index ) + { + const Value &childValue = value[index]; + isMultiLine = isMultiLine || + ( (childValue.isArray() || childValue.isObject()) && + childValue.size() > 0 ); + } + if ( !isMultiLine ) // check if line length > max line length + { + childValues_.reserve( size ); + addChildValues_ = true; + int lineLength = 4 + (size-1)*2; // '[ ' + ', '*n + ' ]' + for ( int index =0; index < size && !isMultiLine; ++index ) + { + writeValue( value[index] ); + lineLength += int( childValues_[index].length() ); + isMultiLine = isMultiLine && hasCommentForValue( value[index] ); + } + addChildValues_ = false; + isMultiLine = isMultiLine || lineLength >= rightMargin_; + } + return isMultiLine; +} + + +void +StyledStreamWriter::pushValue( const std::string &value ) +{ + if ( addChildValues_ ) + childValues_.push_back( value ); + else + *document_ << value; +} + + +void +StyledStreamWriter::writeIndent() +{ + /* + Some comments in this method would have been nice. ;-) + + if ( !document_.empty() ) + { + char last = document_[document_.length()-1]; + if ( last == ' ' ) // already indented + return; + if ( last != '\n' ) // Comments may add new-line + *document_ << '\n'; + } + */ + *document_ << '\n' << indentString_; +} + + +void +StyledStreamWriter::writeWithIndent( const std::string &value ) +{ + writeIndent(); + *document_ << value; +} + + +void +StyledStreamWriter::indent() +{ + indentString_ += indentation_; +} + + +void +StyledStreamWriter::unindent() +{ + assert( indentString_.size() >= indentation_.size() ); + indentString_.resize( indentString_.size() - indentation_.size() ); +} + + +void +StyledStreamWriter::writeCommentBeforeValue( const Value &root ) +{ + if ( !root.hasComment( commentBefore ) ) + return; + *document_ << normalizeEOL( root.getComment( commentBefore ) ); + *document_ << "\n"; +} + + +void +StyledStreamWriter::writeCommentAfterValueOnSameLine( const Value &root ) +{ + if ( root.hasComment( commentAfterOnSameLine ) ) + *document_ << " " + normalizeEOL( root.getComment( commentAfterOnSameLine ) ); + + if ( root.hasComment( commentAfter ) ) + { + *document_ << "\n"; + *document_ << normalizeEOL( root.getComment( commentAfter ) ); + *document_ << "\n"; + } +} + + +bool +StyledStreamWriter::hasCommentForValue( const Value &value ) +{ + return value.hasComment( commentBefore ) + || value.hasComment( commentAfterOnSameLine ) + || value.hasComment( commentAfter ); +} + + +std::string +StyledStreamWriter::normalizeEOL( const std::string &text ) +{ + std::string normalized; + normalized.reserve( text.length() ); + const char *begin = text.c_str(); + const char *end = begin + text.length(); + const char *current = begin; + while ( current != end ) + { + char c = *current++; + if ( c == '\r' ) // mac or dos EOL + { + if ( *current == '\n' ) // convert dos EOL + ++current; + normalized += '\n'; + } + else // handle unix EOL & other char + normalized += c; + } + return normalized; +} + + +std::ostream& operator<<( std::ostream &sout, const Value &root ) +{ + Json::StyledStreamWriter writer; + writer.write(sout, root); + return sout; +} + + +} // namespace Json + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_writer.cpp +// ////////////////////////////////////////////////////////////////////// diff --git a/src/util/stdint_p.h b/src/util/stdint_p.h new file mode 100644 index 0000000000..242332bac2 --- /dev/null +++ b/src/util/stdint_p.h @@ -0,0 +1,33 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USSTDINT_H +#define USSTDINT_H + +#ifdef HAVE_STDINT +#include +#elif defined(_MSC_VER) +#include "stdint_vc_p.h" +#else +#error The stdint.h header is not available +#endif + +#endif // USSTDINT_H diff --git a/src/util/stdint_vc_p.h b/src/util/stdint_vc_p.h new file mode 100644 index 0000000000..c660849c42 --- /dev/null +++ b/src/util/stdint_vc_p.h @@ -0,0 +1,235 @@ +/* ISO C9x 7.18 Integer types + * Based on ISO/IEC SC22/WG14 9899 Committee draft (SC22 N2794) + * + * THIS SOFTWARE IS NOT COPYRIGHTED + * + * Contributor: Danny Smith + * + * This source code is offered for use in the public domain. You may + * use, modify or distribute it freely. + * + * This code is distributed in the hope that it will be useful but + * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY + * DISCLAIMED. This includes but is not limited to warranties of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * Date: 2000-12-02 + * + * mwb: This was modified in the following ways: + * + * - make it compatible with Visual C++ 6 (which uses + * non-standard keywords and suffixes for 64-bit types) + * - some environments need stddef.h included (for wchar stuff?) + * - handle the fact that Microsoft's limits.h header defines + * SIZE_MAX + * - make corrections for SIZE_MAX, INTPTR_MIN, INTPTR_MAX, UINTPTR_MAX, + * PTRDIFF_MIN, PTRDIFF_MAX, SIG_ATOMIC_MIN, and SIG_ATOMIC_MAX + * to be 64-bit aware. + */ + + +#ifndef _STDINT_H +#define _STDINT_H +#define __need_wint_t +#define __need_wchar_t +#include +#include + +#if _MSC_VER && (_MSC_VER < 1300) +/* using MSVC 6 or earlier - no "long long" type, but might have _int64 type */ +#define __STDINT_LONGLONG __int64 +#define __STDINT_LONGLONG_SUFFIX i64 +#else +#define __STDINT_LONGLONG long long +#define __STDINT_LONGLONG_SUFFIX LL +#endif + +#if !defined( PASTE) +#define PASTE2( x, y) x##y +#define PASTE( x, y) PASTE2( x, y) +#endif /* PASTE */ + + +/* 7.18.1.1 Exact-width integer types */ +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef short int16_t; +typedef unsigned short uint16_t; +typedef int int32_t; +typedef unsigned uint32_t; +typedef __STDINT_LONGLONG int64_t; +typedef unsigned __STDINT_LONGLONG uint64_t; + +/* 7.18.1.2 Minimum-width integer types */ +typedef signed char int_least8_t; +typedef unsigned char uint_least8_t; +typedef short int_least16_t; +typedef unsigned short uint_least16_t; +typedef int int_least32_t; +typedef unsigned uint_least32_t; +typedef __STDINT_LONGLONG int_least64_t; +typedef unsigned __STDINT_LONGLONG uint_least64_t; + +/* 7.18.1.3 Fastest minimum-width integer types + * Not actually guaranteed to be fastest for all purposes + * Here we use the exact-width types for 8 and 16-bit ints. + */ +typedef char int_fast8_t; +typedef unsigned char uint_fast8_t; +typedef short int_fast16_t; +typedef unsigned short uint_fast16_t; +typedef int int_fast32_t; +typedef unsigned int uint_fast32_t; +typedef __STDINT_LONGLONG int_fast64_t; +typedef unsigned __STDINT_LONGLONG uint_fast64_t; + +/* 7.18.1.4 Integer types capable of holding object pointers */ +#ifndef _INTPTR_T_DEFINED +#define _INTPTR_T_DEFINED +#ifdef _WIN64 +typedef __STDINT_LONGLONG intptr_t +#else +typedef int intptr_t; +#endif /* _WIN64 */ +#endif /* _INTPTR_T_DEFINED */ + +#ifndef _UINTPTR_T_DEFINED +#define _UINTPTR_T_DEFINED +#ifdef _WIN64 +typedef unsigned __STDINT_LONGLONG uintptr_t +#else +typedef unsigned int uintptr_t; +#endif /* _WIN64 */ +#endif /* _UINTPTR_T_DEFINED */ + +/* 7.18.1.5 Greatest-width integer types */ +typedef __STDINT_LONGLONG intmax_t; +typedef unsigned __STDINT_LONGLONG uintmax_t; + +/* 7.18.2 Limits of specified-width integer types */ +#if !defined ( __cplusplus) || defined (__STDC_LIMIT_MACROS) + +/* 7.18.2.1 Limits of exact-width integer types */ +#define INT8_MIN (-128) +#define INT16_MIN (-32768) +#define INT32_MIN (-2147483647 - 1) +#define INT64_MIN (PASTE( -9223372036854775807, __STDINT_LONGLONG_SUFFIX) - 1) + +#define INT8_MAX 127 +#define INT16_MAX 32767 +#define INT32_MAX 2147483647 +#define INT64_MAX (PASTE( 9223372036854775807, __STDINT_LONGLONG_SUFFIX)) + +#define UINT8_MAX 0xff /* 255U */ +#define UINT16_MAX 0xffff /* 65535U */ +#define UINT32_MAX 0xffffffff /* 4294967295U */ +#define UINT64_MAX (PASTE( 0xffffffffffffffffU, __STDINT_LONGLONG_SUFFIX)) /* 18446744073709551615ULL */ + +/* 7.18.2.2 Limits of minimum-width integer types */ +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST64_MIN INT64_MIN + +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MAX INT64_MAX + +#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST16_MAX UINT16_MAX +#define UINT_LEAST32_MAX UINT32_MAX +#define UINT_LEAST64_MAX UINT64_MAX + +/* 7.18.2.3 Limits of fastest minimum-width integer types */ +#define INT_FAST8_MIN INT8_MIN +#define INT_FAST16_MIN INT16_MIN +#define INT_FAST32_MIN INT32_MIN +#define INT_FAST64_MIN INT64_MIN + +#define INT_FAST8_MAX INT8_MAX +#define INT_FAST16_MAX INT16_MAX +#define INT_FAST32_MAX INT32_MAX +#define INT_FAST64_MAX INT64_MAX + +#define UINT_FAST8_MAX UINT8_MAX +#define UINT_FAST16_MAX UINT16_MAX +#define UINT_FAST32_MAX UINT32_MAX +#define UINT_FAST64_MAX UINT64_MAX + +/* 7.18.2.4 Limits of integer types capable of holding + object pointers */ +#ifdef _WIN64 +#define INTPTR_MIN INT64_MIN +#define INTPTR_MAX INT64_MAX +#define UINTPTR_MAX UINT64_MAX +#else +#define INTPTR_MIN INT32_MIN +#define INTPTR_MAX INT32_MAX +#define UINTPTR_MAX UINT32_MAX +#endif /* _WIN64 */ + +/* 7.18.2.5 Limits of greatest-width integer types */ +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX + +/* 7.18.3 Limits of other integer types */ +#define PTRDIFF_MIN INTPTR_MIN +#define PTRDIFF_MAX INTPTR_MAX + +#define SIG_ATOMIC_MIN INTPTR_MIN +#define SIG_ATOMIC_MAX INTPTR_MAX + +/* we need to check for SIZE_MAX already defined because MS defines it in limits.h */ +#ifndef SIZE_MAX +#define SIZE_MAX UINTPTR_MAX +#endif + +#ifndef WCHAR_MIN /* also in wchar.h */ +#define WCHAR_MIN 0 +#define WCHAR_MAX ((wchar_t)-1) /* UINT16_MAX */ +#endif + +/* + * wint_t is unsigned short for compatibility with MS runtime + */ +#define WINT_MIN 0 +#define WINT_MAX ((wint_t)-1) /* UINT16_MAX */ + +#endif /* !defined ( __cplusplus) || defined __STDC_LIMIT_MACROS */ + + +/* 7.18.4 Macros for integer constants */ +#if !defined ( __cplusplus) || defined (__STDC_CONSTANT_MACROS) + +/* 7.18.4.1 Macros for minimum-width integer constants + + Accoding to Douglas Gwyn : +"This spec was changed in ISO/IEC 9899:1999 TC1; in ISO/IEC +9899:1999 as initially published, the expansion was required +to be an integer constant of precisely matching type, which +is impossible to accomplish for the shorter types on most +platforms, because C99 provides no standard way to designate +an integer constant with width less than that of type int. +TC1 changed this to require just an integer constant +*expression* with *promoted* type." +*/ + +#define INT8_C(val) ((int8_t) + (val)) +#define UINT8_C(val) ((uint8_t) + (val##U)) +#define INT16_C(val) ((int16_t) + (val)) +#define UINT16_C(val) ((uint16_t) + (val##U)) + +#define INT32_C(val) val##L +#define UINT32_C(val) val##UL +#define INT64_C(val) (PASTE( val, __STDINT_LONGLONG_SUFFIX)) +#define UINT64_C(val)(PASTE( PASTE( val, U), __STDINT_LONGLONG_SUFFIX)) + +/* 7.18.4.2 Macros for greatest-width integer constants */ +#define INTMAX_C(val) INT64_C(val) +#define UINTMAX_C(val) UINT64_C(val) + +#endif /* !defined ( __cplusplus) || defined __STDC_CONSTANT_MACROS */ + +#endif diff --git a/src/util/tinfl.c b/src/util/tinfl.c new file mode 100644 index 0000000000..a17a156b6c --- /dev/null +++ b/src/util/tinfl.c @@ -0,0 +1,592 @@ +/* tinfl.c v1.11 - public domain inflate with zlib header parsing/adler32 checking (inflate-only subset of miniz.c) + See "unlicense" statement at the end of this file. + Rich Geldreich , last updated May 20, 2011 + Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt + + The entire decompressor coroutine is implemented in tinfl_decompress(). The other functions are optional high-level helpers. +*/ +#ifndef TINFL_HEADER_INCLUDED +#define TINFL_HEADER_INCLUDED + +#include + +typedef unsigned char mz_uint8; +typedef signed short mz_int16; +typedef unsigned short mz_uint16; +typedef unsigned int mz_uint32; +typedef unsigned int mz_uint; +typedef unsigned long long mz_uint64; + +#if defined(_M_IX86) || defined(_M_X64) +// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 if integer loads and stores to unaligned addresses are acceptable on the target platform (slightly faster). +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. +#define MINIZ_LITTLE_ENDIAN 1 +#endif + +#if defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) +// Set MINIZ_HAS_64BIT_REGISTERS to 1 if the processor has 64-bit general purpose registers (enables 64-bit bitbuffer in inflator) +#define MINIZ_HAS_64BIT_REGISTERS 1 +#endif + +// Works around MSVC's spammy "warning C4127: conditional expression is constant" message. +#ifdef _MSC_VER + #define MZ_MACRO_END while (0, 0) +#else + #define MZ_MACRO_END while (0) +#endif + +// Decompression flags used by tinfl_decompress(). +// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. +// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. +// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). +// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. +enum +{ + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +// High level decompression functions: +// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. +// On return: +// Function returns a pointer to the decompressed data, or NULL on failure. +// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must free() the returned block when it's no longer needed. +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. +// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. +// Returns 1 on success or 0 on failure. +typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; + +// Max size of LZ dictionary. +#define TINFL_LZ_DICT_SIZE 32768 + +// Return status. +typedef enum +{ + TINFL_STATUS_BAD_PARAM = -3, + TINFL_STATUS_ADLER32_MISMATCH = -2, + TINFL_STATUS_FAILED = -1, + TINFL_STATUS_DONE = 0, + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +// Initializes the decompressor to its initial state. +#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. +// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + +// Internal/private bits follow. +enum +{ + TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +typedef struct +{ + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; +} tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS + #define TINFL_USE_64BIT_BITBUF 1 +#endif + +#if TINFL_USE_64BIT_BITBUF + typedef mz_uint64 tinfl_bit_buf_t; + #define TINFL_BITBUF_SIZE (64) +#else + typedef mz_uint32 tinfl_bit_buf_t; + #define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag +{ + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + +#endif // #ifdef TINFL_HEADER_INCLUDED + +// ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.) + +#ifndef TINFL_HEADER_FILE_ONLY + +#include + +// MZ_MALLOC, etc. are only used by the optional high-level helper functions. +#ifdef MINIZ_NO_MALLOC + #define MZ_MALLOC(x) NULL + #define MZ_FREE(x) x, ((void)0) + #define MZ_REALLOC(p, x) NULL +#else + #define MZ_MALLOC(x) malloc(x) + #define MZ_FREE(x) free(x) + #define MZ_REALLOC(p, x) realloc(p, x) +#endif + +#define MZ_MAX(a,b) (((a)>(b))?(a):(b)) +#define MZ_MIN(a,b) (((a)<(b))?(a):(b)) +#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) + #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#else + #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) + #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#endif + +#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) +#define TINFL_MEMSET(p, c, l) memset(p, c, l) + +#define TINFL_CR_BEGIN switch(r->m_state) { case 0: +#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END +#define TINFL_CR_FINISH } + +// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never +// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. +#define TINFL_GET_BYTE(state_index, c) do { \ + if (pIn_buf_cur >= pIn_buf_end) { \ + for ( ; ; ) { \ + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ + TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ + if (pIn_buf_cur < pIn_buf_end) { \ + c = *pIn_buf_cur++; \ + break; \ + } \ + } else { \ + c = 0; \ + break; \ + } \ + } \ + } else c = *pIn_buf_cur++; } MZ_MACRO_END + +#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END + +// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. +// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a +// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the +// bit buffer contains >=15 bits (deflate's max. Huffman code size). +#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ + do { \ + temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ + } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ + } while (num_bits < 15); + +// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read +// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully +// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. +// The slow path is only executed at the very end of the input buffer. +#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ + int temp; mz_uint code_len, c; \ + if (num_bits < 15) { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) { \ + TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ + } else { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ + } \ + } \ + if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ + code_len = temp >> 9, temp &= 511; \ + else { \ + code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ + } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END + +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) +{ + static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; + static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + static const int s_min_table_sizes[3] = { 257, 1, 4 }; + + tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; + const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; + mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; + size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; + + // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). + if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } + + num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); + if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } + } + + do + { + TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; + if (r->m_type == 0) + { + TINFL_SKIP_BITS(5, num_bits & 7); + for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } + if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } + while ((counter) && (num_bits)) + { + TINFL_GET_BITS(51, dist, 8); + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = (mz_uint8)dist; + counter--; + } + while (counter) + { + size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } + while (pIn_buf_cur >= pIn_buf_end) + { + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) + { + TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); + } + else + { + TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); + } + } + n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); + TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; + } + } + else if (r->m_type == 3) + { + TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); + } + else + { + if (r->m_type == 1) + { + mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; + r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); + for ( i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8; + } + else + { + for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } + MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } + r->m_table_sizes[2] = 19; + } + for ( ; (int)r->m_type >= 0; r->m_type--) + { + int tree_next, tree_cur; tinfl_huff_table *pTable; + mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; + used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } + if ((65536 != total) && (used_syms > 1)) + { + TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); + } + for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) + { + mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; + cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } + if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) + { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; + } + if (r->m_type == 2) + { + for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); ) + { + mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } + if ((dist == 16) && (!counter)) + { + TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); + } + num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; + TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; + } + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) + { + TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); + } + TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); + } + } + for ( ; ; ) + { + mz_uint8 *pSrc; + for ( ; ; ) + { + if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) + { + TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); + if (counter >= 256) + break; + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = (mz_uint8)counter; + } + else + { + int sym2; mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } +#else + if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); + } + counter = sym2; bit_buf >>= code_len; num_bits -= code_len; + if (counter & 256) + break; + +#if !TINFL_USE_64BIT_BITBUF + if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); + } + bit_buf >>= code_len; num_bits -= code_len; + + pOut_buf_cur[0] = (mz_uint8)counter; + if (sym2 & 256) + { + pOut_buf_cur++; + counter = sym2; + break; + } + pOut_buf_cur[1] = (mz_uint8)sym2; + pOut_buf_cur += 2; + } + } + if ((counter &= 511) == 256) break; + + num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; + if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } + + TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); + num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; + if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } + + dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; + if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + { + TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); + } + + pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + + if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) + { + while (counter--) + { + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; + } + continue; + } +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + else if ((counter >= 9) && (counter <= dist)) + { + const mz_uint8 *pSrc_end = pSrc + (counter & ~7); + do + { + ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; + ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; + pOut_buf_cur += 8; + } while ((pSrc += 8) < pSrc_end); + if ((counter &= 7) < 3) + { + if (counter) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + continue; + } + } +#endif + do + { + pOut_buf_cur[0] = pSrc[0]; + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur[2] = pSrc[2]; + pOut_buf_cur += 3; pSrc += 3; + } while ((int)(counter -= 3) > 2); + if ((int)counter > 0) + { + pOut_buf_cur[0] = pSrc[0]; + if ((int)counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + } + } + } while (!(r->m_final & 1)); + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } + } + TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); + TINFL_CR_FINISH + +common_exit: + r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) + { + const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; + } + for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; + } + r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; + } + return status; +} + +// Higher level helper functions. +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; + *pOut_len = 0; + tinfl_init(&decomp); + for ( ; ; ) + { + size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) + { + MZ_FREE(pBuf); *pOut_len = 0; return NULL; + } + src_buf_ofs += src_buf_size; + *pOut_len += dst_buf_size; + if (status == TINFL_STATUS_DONE) break; + new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; + pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); + if (!pNew_buf) + { + MZ_FREE(pBuf); *pOut_len = 0; return NULL; + } + pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; + } + return pBuf; +} + +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); + status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; +} + +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + int result = 0; + tinfl_decompressor decomp; + mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; + if (!pDict) + return TINFL_STATUS_FAILED; + tinfl_init(&decomp); + for ( ; ; ) + { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, + (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + in_buf_ofs += in_buf_size; + if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + break; + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) + { + result = (status == TINFL_STATUS_DONE); + break; + } + dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); + } + MZ_FREE(pDict); + *pIn_buf_size = in_buf_ofs; + return result; +} + +#endif // #ifndef TINFL_HEADER_FILE_ONLY + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + For more information, please refer to +*/ diff --git a/src/util/usAny.cpp b/src/util/usAny.cpp new file mode 100644 index 0000000000..bac8be2580 --- /dev/null +++ b/src/util/usAny.cpp @@ -0,0 +1,78 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usAny.h" + +US_BEGIN_NAMESPACE + +std::ostream& operator<< (std::ostream& os, const Any& any) +{ + return os << any.ToString(); +} + +template +std::string container_to_string(Iterator i1, Iterator i2) +{ + std::stringstream ss; + ss << "("; + const Iterator begin = i1; + for ( ; i1 != i2; ++i1) + { + if (i1 == begin) ss << *i1; + else ss << "," << *i1; + } + ss << ")"; + return ss.str(); +} + +std::string any_value_to_string(const std::vector& val) +{ + return container_to_string(val.begin(), val.end()); +} + +std::string any_value_to_string(const std::list& val) +{ + return container_to_string(val.begin(), val.end()); +} + +std::string any_value_to_string(const std::vector& val) +{ + return container_to_string(val.begin(), val.end()); +} + +std::string any_value_to_string(const std::map& val) +{ + std::stringstream ss; + ss << "["; + typedef std::map::const_iterator Iterator; + Iterator i1 = val.begin(); + const Iterator begin = i1; + const Iterator end = val.end(); + for ( ; i1 != end; ++i1) + { + if (i1 == begin) ss << "\"" << i1->first << "\" => " << i1->second; + else ss << ", " << "\"" << i1->first << "\" => " << i1->second; + } + ss << "]"; + return ss.str(); +} + +US_END_NAMESPACE diff --git a/src/util/usAny.h b/src/util/usAny.h new file mode 100644 index 0000000000..01b69af5d8 --- /dev/null +++ b/src/util/usAny.h @@ -0,0 +1,397 @@ +/*============================================================================= + + Library: CppMicroServices + + +Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved. +Extracted from Boost 1.46.1 and adapted for CppMicroServices. + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +=========================================================================*/ + +#ifndef US_ANY_H +#define US_ANY_H + +#include +#include +#include +#include +#include +#include + +#include + +US_BEGIN_NAMESPACE + +template +std::string any_value_to_string(const T& val); + +US_EXPORT std::string any_value_to_string(const std::vector& val); +US_EXPORT std::string any_value_to_string(const std::list& val); + +/** + * \ingroup MicroServicesUtils + * + * An Any class represents a general type and is capable of storing any type, supporting type-safe extraction + * of the internally stored data. + * + * Code taken from the Boost 1.46.1 library. Original copyright by Kevlin Henney. Modified for CppMicroServices. + */ +class Any +{ +public: + + /** + * Creates an empty any type. + */ + Any(): _content(0) + { } + + /** + * Creates an Any which stores the init parameter inside. + * + * \param value The content of the Any + * + * Example: + * \code + * Any a(13); + * Any a(string("12345")); + * \endcode + */ + template + Any(const ValueType& value) + : _content(new Holder(value)) + { } + + /** + * Copy constructor, works with empty Anys and initialized Any values. + * + * \param other The Any to copy + */ + Any(const Any& other) + : _content(other._content ? other._content->Clone() : 0) + { } + + ~Any() + { + delete _content; + } + + /** + * Swaps the content of the two Anys. + * + * \param rhs The Any to swap this Any with. + */ + Any& Swap(Any& rhs) + { + std::swap(_content, rhs._content); + return *this; + } + + /** + * Assignment operator for all types != Any. + * + * \param rhs The value which should be assigned to this Any. + * + * Example: + * \code + * Any a = 13; + * Any a = string("12345"); + * \endcode + */ + template + Any& operator = (const ValueType& rhs) + { + Any(rhs).Swap(*this); + return *this; + } + + /** + * Assignment operator for Any. + * + * \param rhs The Any which should be assigned to this Any. + */ + Any& operator = (const Any& rhs) + { + Any(rhs).Swap(*this); + return *this; + } + + /** + * returns true if the Any is empty + */ + bool Empty() const + { + return !_content; + } + + /** + * Returns a string representation for the content. + * + * Custom types should either provide a std::ostream& operator<<(std::ostream& os, const CustomType& ct) + * function or specialize the any_value_to_string template function for meaningful output. + */ + std::string ToString() const + { + return _content->ToString(); + } + + /** + * Returns the type information of the stored content. + * If the Any is empty typeid(void) is returned. + * It is suggested to always query an Any for its type info before trying to extract + * data via an any_cast/ref_any_cast. + */ + const std::type_info& Type() const + { + return _content ? _content->Type() : typeid(void); + } + +private: + + class Placeholder + { + public: + virtual ~Placeholder() + { } + + virtual std::string ToString() const = 0; + + virtual const std::type_info& Type() const = 0; + virtual Placeholder* Clone() const = 0; + }; + + template + class Holder: public Placeholder + { + public: + Holder(const ValueType& value) + : _held(value) + { } + + virtual std::string ToString() const + { + return any_value_to_string(_held); + } + + virtual const std::type_info& Type() const + { + return typeid(ValueType); + } + + virtual Placeholder* Clone() const + { + return new Holder(_held); + } + + ValueType _held; + + private: // intentionally left unimplemented + Holder& operator=(const Holder &); + }; + +private: + template + friend ValueType* any_cast(Any*); + + template + friend ValueType* unsafe_any_cast(Any*); + + Placeholder* _content; +}; + +class BadAnyCastException : public std::bad_cast +{ +public: + + BadAnyCastException(const std::string& msg = "") + : std::bad_cast(), _msg(msg) + {} + + ~BadAnyCastException() throw() {} + + virtual const char * what() const throw() + { + if (_msg.empty()) + return "US_PREPEND_NAMESPACE(BadAnyCastException): " + "failed conversion using US_PREPEND_NAMESPACE(any_cast)"; + else + return _msg.c_str(); + } + +private: + + std::string _msg; +}; + +/** + * any_cast operator used to extract the ValueType from an Any*. Will return a pointer + * to the stored value. + * + * Example Usage: + * \code + * MyType* pTmp = any_cast(pAny) + * \endcode + * Will return NULL if the cast fails, i.e. types don't match. + */ +template +ValueType* any_cast(Any* operand) +{ + return operand && operand->Type() == typeid(ValueType) + ? &static_cast*>(operand->_content)->_held + : 0; +} + +/** + * any_cast operator used to extract a const ValueType pointer from an const Any*. Will return a const pointer + * to the stored value. + * + * Example Usage: + * \code + * const MyType* pTmp = any_cast(pAny) + * \endcode + * Will return NULL if the cast fails, i.e. types don't match. + */ +template +const ValueType* any_cast(const Any* operand) +{ + return any_cast(const_cast(operand)); +} + +/** + * any_cast operator used to extract a copy of the ValueType from an const Any&. + * + * Example Usage: + * \code + * MyType tmp = any_cast(anAny) + * \endcode + * Will throw a BadCastException if the cast fails. + * Dont use an any_cast in combination with references, i.e. MyType& tmp = ... or const MyType& = ... + * Some compilers will accept this code although a copy is returned. Use the ref_any_cast in + * these cases. + */ +template +ValueType any_cast(const Any& operand) +{ + ValueType* result = any_cast(const_cast(&operand)); + if (!result) throw BadAnyCastException("Failed to convert between const Any types"); + return *result; +} + +/** + * any_cast operator used to extract a copy of the ValueType from an Any&. + * + * Example Usage: + * \code + * MyType tmp = any_cast(anAny) + * \endcode + * Will throw a BadCastException if the cast fails. + * Dont use an any_cast in combination with references, i.e. MyType& tmp = ... or const MyType& tmp = ... + * Some compilers will accept this code although a copy is returned. Use the ref_any_cast in + * these cases. + */ +template +ValueType any_cast(Any& operand) +{ + ValueType* result = any_cast(&operand); + if (!result) throw BadAnyCastException("Failed to convert between Any types"); + return *result; +} + +/** + * ref_any_cast operator used to return a const reference to the internal data. + * + * Example Usage: + * \code + * const MyType& tmp = ref_any_cast(anAny); + * \endcode + */ +template +const ValueType& ref_any_cast(const Any & operand) +{ + ValueType* result = any_cast(const_cast(&operand)); + if (!result) throw BadAnyCastException("RefAnyCast: Failed to convert between const Any types"); + return *result; +} + +/** + * ref_any_cast operator used to return a reference to the internal data. + * + * Example Usage: + * \code + * MyType& tmp = ref_any_cast(anAny); + * \endcode + */ +template +ValueType& ref_any_cast(Any& operand) +{ + ValueType* result = any_cast(&operand); + if (!result) throw BadAnyCastException("RefAnyCast: Failed to convert between Any types"); + return *result; +} + +/** + * \internal + * + * The "unsafe" versions of any_cast are not part of the + * public interface and may be removed at any time. They are + * required where we know what type is stored in the any and can't + * use typeid() comparison, e.g., when our types may travel across + * different shared libraries. + */ +template +ValueType* unsafe_any_cast(Any* operand) +{ + return &static_cast*>(operand->_content)->_held; +} + +/** + * \internal + * + * The "unsafe" versions of any_cast are not part of the + * public interface and may be removed at any time. They are + * required where we know what type is stored in the any and can't + * use typeid() comparison, e.g., when our types may travel across + * different shared libraries. + */ +template +const ValueType* unsafe_any_cast(const Any* operand) +{ + return any_cast(const_cast(operand)); +} + +US_EXPORT std::string any_value_to_string(const std::vector& val); +US_EXPORT std::string any_value_to_string(const std::map& val); + +template +std::string any_value_to_string(const T& val) +{ + std::stringstream ss; + ss << val; + return ss.str(); +} + +US_END_NAMESPACE + +#endif // US_ANY_H diff --git a/src/util/usAtomicInt_p.h b/src/util/usAtomicInt_p.h new file mode 100644 index 0000000000..4bc954ec02 --- /dev/null +++ b/src/util/usAtomicInt_p.h @@ -0,0 +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_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/src/util/usFunctor_p.h b/src/util/usFunctor_p.h new file mode 100644 index 0000000000..dfdd608d0f --- /dev/null +++ b/src/util/usFunctor_p.h @@ -0,0 +1,139 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USFUNCTOR_H +#define USFUNCTOR_H + +#include + +US_BEGIN_NAMESPACE + +template +class FunctorImpl +{ +public: + + virtual void operator()(Arg) = 0; + virtual FunctorImpl* Clone() const = 0; + + bool operator==(const FunctorImpl& o) const + { return typeid(*this) == typeid(o) && IsEqual(o); } + + virtual ~FunctorImpl() {} + +private: + + virtual bool IsEqual(const FunctorImpl& o) const = 0; +}; + +template +class FunctorHandler : public FunctorImpl +{ +public: + + FunctorHandler(const Fun& fun) : m_Fun(fun) {} + + FunctorHandler* Clone() const + { return new FunctorHandler(*this); } + + void operator()(Arg a) + { m_Fun(a); } + +private: + + bool IsEqual(const FunctorImpl& o) const + { return this->m_Fun == static_cast(o).m_Fun; } + + Fun m_Fun; +}; + +template +class MemFunHandler : public FunctorImpl +{ +public: + + MemFunHandler(const PointerToObj& pObj, PointerToMemFn pMemFn) + : m_pObj(pObj), m_pMemFn(pMemFn) + {} + + MemFunHandler* Clone() const + { return new MemFunHandler(*this); } + + void operator()(Arg a) + { ((*m_pObj).*m_pMemFn)(a); } + +private: + + bool IsEqual(const FunctorImpl& o) const + { return this->m_pObj == static_cast(o).m_pObj && + this->m_pMemFn == static_cast(o).m_pMemFn; } + + PointerToObj m_pObj; + PointerToMemFn m_pMemFn; + +}; + +template +class Functor +{ +public: + + Functor() : m_Impl(0) {} + + template + Functor(const Fun& fun) + : m_Impl(new FunctorHandler(fun)) + {} + + template + Functor(const PtrObj& p, MemFn memFn) + : m_Impl(new MemFunHandler(p, memFn)) + {} + + Functor(const Functor& f) : m_Impl(f.m_Impl->Clone()) {} + + Functor& operator=(const Functor& f) + { + Impl* tmp = f.m_Impl->Clone(); + std::swap(tmp, m_Impl); + delete tmp; + } + + bool operator==(const Functor& f) const + { return (*m_Impl) == (*f.m_Impl); } + + ~Functor() { delete m_Impl; } + + void operator()(Arg a) + { + (*m_Impl)(a); + } + +private: + + typedef FunctorImpl Impl; + Impl* m_Impl; +}; + +US_END_NAMESPACE + +#endif // USFUNCTOR_H diff --git a/src/util/usSharedData.h b/src/util/usSharedData.h new file mode 100644 index 0000000000..f3a6dfc82f --- /dev/null +++ b/src/util/usSharedData.h @@ -0,0 +1,274 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Modified version of qshareddata.h from Qt 4.7.3 for CppMicroServices. +Original copyright (c) Nokia Corporation. Usage covered by the +GNU Lesser General Public License version 2.1 +(http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html) and the Nokia Qt +LGPL Exception version 1.1 (file LGPL_EXCEPTION.txt in Qt 4.7.3 package). + +=========================================================================*/ + +#ifndef USSHAREDDATA_H +#define USSHAREDDATA_H + +#include "usAtomicInt_p.h" + +#include +#include + +US_BEGIN_NAMESPACE + +/** + * \ingroup MicroServicesUtils + */ +class SharedData +{ +public: + mutable AtomicInt ref; + + inline SharedData() : ref(0) { } + inline SharedData(const SharedData&) : ref(0) { } + +private: + // using the assignment operator would lead to corruption in the ref-counting + SharedData& operator=(const SharedData&); +}; + +/** + * \ingroup MicroServicesUtils + */ +template +class SharedDataPointer +{ +public: + typedef T Type; + typedef T* pointer; + + inline void Detach() { if (d && d->ref != 1) Detach_helper(); } + inline T& operator*() { Detach(); return *d; } + inline const T& operator*() const { return *d; } + inline T* operator->() { Detach(); return d; } + inline const T* operator->() const { return d; } + inline operator T*() { Detach(); return d; } + inline operator const T*() const { return d; } + inline T* Data() { Detach(); return d; } + inline const T* Data() const { return d; } + inline const T* ConstData() const { return d; } + + inline bool operator==(const SharedDataPointer& other) const { return d == other.d; } + inline bool operator!=(const SharedDataPointer& other) const { return d != other.d; } + + inline SharedDataPointer() : d(0) { } + inline ~SharedDataPointer() { if (d && !d->ref.Deref()) delete d; } + + explicit SharedDataPointer(T* data); + inline SharedDataPointer(const SharedDataPointer& o) : d(o.d) { if (d) d->ref.Ref(); } + + inline SharedDataPointer & operator=(const SharedDataPointer& o) + { + if (o.d != d) + { + if (o.d) + o.d->ref.Ref(); + T *old = d; + d = o.d; + if (old && !old->ref.Deref()) + delete old; + } + return *this; + } + + inline SharedDataPointer &operator=(T *o) + { + if (o != d) + { + if (o) + o->ref.Ref(); + T *old = d; + d = o; + if (old && !old->ref.Deref()) + delete old; + } + return *this; + } + + inline bool operator!() const { return !d; } + + inline void Swap(SharedDataPointer& other) + { + using std::swap; + swap(d, other.d); + } + +protected: + T* Clone(); + +private: + void Detach_helper(); + + T *d; +}; + +/** + * \ingroup MicroServicesUtils + */ +template class ExplicitlySharedDataPointer +{ +public: + typedef T Type; + typedef T* pointer; + + inline T& operator*() const { return *d; } + inline T* operator->() { return d; } + inline T* operator->() const { return d; } + inline T* Data() const { return d; } + inline const T* ConstData() const { return d; } + + inline void Detach() { if (d && d->ref != 1) Detach_helper(); } + + inline void Reset() + { + if(d && !d->ref.Deref()) + delete d; + + d = 0; + } + + inline operator bool () const { return d != 0; } + + inline bool operator==(const ExplicitlySharedDataPointer& other) const { return d == other.d; } + inline bool operator!=(const ExplicitlySharedDataPointer& other) const { return d != other.d; } + inline bool operator==(const T* ptr) const { return d == ptr; } + inline bool operator!=(const T* ptr) const { return d != ptr; } + + inline ExplicitlySharedDataPointer() { d = 0; } + inline ~ExplicitlySharedDataPointer() { if (d && !d->ref.Deref()) delete d; } + + explicit ExplicitlySharedDataPointer(T* data); + inline ExplicitlySharedDataPointer(const ExplicitlySharedDataPointer &o) + : d(o.d) { if (d) d->ref.Ref(); } + + template + inline ExplicitlySharedDataPointer(const ExplicitlySharedDataPointer& o) + : d(static_cast(o.Data())) + { + if(d) + d->ref.Ref(); + } + + inline ExplicitlySharedDataPointer& operator=(const ExplicitlySharedDataPointer& o) + { + if (o.d != d) + { + if (o.d) + o.d->ref.Ref(); + T *old = d; + d = o.d; + if (old && !old->ref.Deref()) + delete old; + } + return *this; + } + + inline ExplicitlySharedDataPointer& operator=(T* o) + { + if (o != d) + { + if (o) + o->ref.Ref(); + T *old = d; + d = o; + if (old && !old->ref.Deref()) + delete old; + } + return *this; + } + + inline bool operator!() const { return !d; } + + inline void Swap(ExplicitlySharedDataPointer& other) + { + using std::swap; + swap(d, other.d); + } + +protected: + T* Clone(); + +private: + void Detach_helper(); + + T *d; +}; + + +template +SharedDataPointer::SharedDataPointer(T* adata) : d(adata) +{ if (d) d->ref.Ref(); } + +template +T* SharedDataPointer::Clone() +{ + return new T(*d); +} + +template +void SharedDataPointer::Detach_helper() +{ + T *x = Clone(); + x->ref.Ref(); + if (!d->ref.Deref()) + delete d; + d = x; +} + +template +T* ExplicitlySharedDataPointer::Clone() +{ + return new T(*d); +} + +template +void ExplicitlySharedDataPointer::Detach_helper() +{ + T *x = Clone(); + x->ref.Ref(); + if (!d->ref.Deref()) + delete d; + d = x; +} + +template +ExplicitlySharedDataPointer::ExplicitlySharedDataPointer(T* adata) + : d(adata) +{ if (d) d->ref.Ref(); } + +template +void swap(US_PREPEND_NAMESPACE(SharedDataPointer& p1, US_PREPEND_NAMESPACE(SharedDataPointer& p2) +{ p1.Swap(p2); } + +template +void swap(US_PREPEND_NAMESPACE(ExplicitlySharedDataPointer& p1, US_PREPEND_NAMESPACE(ExplicitlySharedDataPointer& p2) +{ p1.Swap(p2); } + +US_END_NAMESPACE + +#endif // USSHAREDDATA_H diff --git a/src/util/usSharedLibrary.cpp b/src/util/usSharedLibrary.cpp new file mode 100644 index 0000000000..5bead2eaed --- /dev/null +++ b/src/util/usSharedLibrary.cpp @@ -0,0 +1,273 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usSharedLibrary.h" + +#include + +#include +#include +#include + + +#if defined(US_PLATFORM_POSIX) + #include +#elif defined(US_PLATFORM_WINDOWS) + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #include +#else + #error Unsupported platform +#endif + + +US_BEGIN_NAMESPACE + +#ifdef US_PLATFORM_POSIX +static const char PATH_SEPARATOR = '/'; +#else +static const char PATH_SEPARATOR = '\\'; +#endif + +class SharedLibraryPrivate : public SharedData +{ +public: + + SharedLibraryPrivate() + : m_Handle(NULL) + #ifdef US_PLATFORM_WINDOWS + , m_Suffix(".dll") + #elif defined(US_PLATFORM_APPLE) + , m_Suffix(".dylib") + , m_Prefix("lib") + #else + , m_Suffix(".so") + , m_Prefix("lib") + #endif + {} + + void* m_Handle; + + std::string m_Name; + std::string m_Path; + std::string m_FilePath; + std::string m_Suffix; + std::string m_Prefix; + +}; + +SharedLibrary::SharedLibrary() + : d(new SharedLibraryPrivate) +{ +} + +SharedLibrary::SharedLibrary(const SharedLibrary& other) + : d(other.d) +{ +} + +SharedLibrary::SharedLibrary(const std::string& libPath, const std::string& name) + : d(new SharedLibraryPrivate) +{ + d->m_Name = name; + d->m_Path = libPath; +} + +SharedLibrary::SharedLibrary(const std::string& absoluteFilePath) + : d(new SharedLibraryPrivate) +{ + d->m_FilePath = absoluteFilePath; + SetFilePath(absoluteFilePath); +} + +SharedLibrary::~SharedLibrary() +{ +} + +SharedLibrary& SharedLibrary::operator =(const SharedLibrary& other) +{ + d = other.d; + return *this; +} + +void SharedLibrary::Load(int flags) +{ + if (d->m_Handle) throw std::logic_error(std::string("Library already loaded: ") + GetFilePath()); + std::string libPath = GetFilePath(); +#ifdef US_PLATFORM_POSIX + d->m_Handle = dlopen(libPath.c_str(), flags); + if (!d->m_Handle) + { + const char* err = dlerror(); + throw std::runtime_error(err ? std::string(err) : (std::string("Error loading ") + libPath)); + } +#else + d->m_Handle = LoadLibrary(libPath.c_str()); + if (!d->m_Handle) + { + std::string errMsg = "Loading "; + errMsg.append(libPath).append("failed with error: ").append(GetLastErrorStr()); + + throw std::runtime_error(errMsg); + } +#endif +} + +void SharedLibrary::Load() +{ +#ifdef US_PLATFORM_POSIX +#ifdef US_GCC_RTTI_WORKAROUND_NEEDED + Load(RTLD_LAZY | RTLD_GLOBAL); +#else + Load(RTLD_LAZY | RTLD_LOCAL); +#endif +#else + Load(0); +#endif +} + +void SharedLibrary::Unload() +{ + if (d->m_Handle) + { +#ifdef US_PLATFORM_POSIX + if (dlclose(d->m_Handle)) + { + const char* err = dlerror(); + throw std::runtime_error(err ? std::string(err) : (std::string("Error unloading ") + GetLibraryPath())); + } +#else + if (!FreeLibrary((HMODULE)d->m_Handle)) + { + std::string errMsg = "Unloading "; + errMsg.append(GetLibraryPath()).append("failed with error: ").append(GetLastErrorStr()); + + throw std::runtime_error(errMsg); + } +#endif + d->m_Handle = 0; + } +} + +void SharedLibrary::SetName(const std::string& name) +{ + if (IsLoaded() || !d->m_FilePath.empty()) return; + d.Detach(); + d->m_Name = name; +} + +std::string SharedLibrary::GetName() const +{ + return d->m_Name; +} + +std::string SharedLibrary::GetFilePath(const std::string& name) const +{ + if (!d->m_FilePath.empty()) return d->m_FilePath; + return GetLibraryPath() + PATH_SEPARATOR + GetPrefix() + name + GetSuffix(); +} + +void SharedLibrary::SetFilePath(const std::string& absoluteFilePath) +{ + if (IsLoaded()) return; + + d.Detach(); + d->m_FilePath = absoluteFilePath; + + std::string name = d->m_FilePath; + std::size_t pos = d->m_FilePath.find_last_of(PATH_SEPARATOR); + if (pos != std::string::npos) + { + d->m_Path = d->m_FilePath.substr(0, pos); + name = d->m_FilePath.substr(pos+1); + } + else + { + d->m_Path.clear(); + } + + if (name.size() >= d->m_Prefix.size() && + name.compare(0, d->m_Prefix.size(), d->m_Prefix) == 0) + { + name = name.substr(d->m_Prefix.size()); + } + if (name.size() >= d->m_Suffix.size() && + name.compare(name.size()-d->m_Suffix.size(), d->m_Suffix.size(), d->m_Suffix) == 0) + { + name = name.substr(0, name.size()-d->m_Suffix.size()); + } + d->m_Name = name; +} + +std::string SharedLibrary::GetFilePath() const +{ + return GetFilePath(d->m_Name); +} + +void SharedLibrary::SetLibraryPath(const std::string& path) +{ + if (IsLoaded() || !d->m_FilePath.empty()) return; + d.Detach(); + d->m_Path = path; +} + +std::string SharedLibrary::GetLibraryPath() const +{ + return d->m_Path; +} + +void SharedLibrary::SetSuffix(const std::string& suffix) +{ + if (IsLoaded() || !d->m_FilePath.empty()) return; + d.Detach(); + d->m_Suffix = suffix; +} + +std::string SharedLibrary::GetSuffix() const +{ + return d->m_Suffix; +} + +void SharedLibrary::SetPrefix(const std::string& prefix) +{ + if (IsLoaded() || !d->m_FilePath.empty()) return; + d.Detach(); + d->m_Prefix = prefix; +} + +std::string SharedLibrary::GetPrefix() const +{ + return d->m_Prefix; +} + +void* SharedLibrary::GetHandle() const +{ + return d->m_Handle; +} + +bool SharedLibrary::IsLoaded() const +{ + return d->m_Handle != NULL; +} + +US_END_NAMESPACE diff --git a/src/util/usSharedLibrary.h b/src/util/usSharedLibrary.h new file mode 100644 index 0000000000..5bcd9308db --- /dev/null +++ b/src/util/usSharedLibrary.h @@ -0,0 +1,223 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USSHAREDLIBRARY_H +#define USSHAREDLIBRARY_H + +#include "usConfig.h" +#include "usSharedData.h" + +#include + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4251) +#endif + +US_BEGIN_NAMESPACE + +class SharedLibraryPrivate; + +/** + * \ingroup MicroServicesUtils + * + * The SharedLibrary class loads shared libraries at runtime. + */ +class US_EXPORT SharedLibrary +{ +public: + + SharedLibrary(); + SharedLibrary(const SharedLibrary& other); + + /** + * Construct a SharedLibrary object using a library search path and + * a library base name. + * + * @param libPath An absolute path containing the shared library + * @param name The base name of the shared library, without prefix + * and suffix. + */ + SharedLibrary(const std::string& libPath, const std::string& name); + + /** + * Construct a SharedLibrary object using an absolute file path to + * the shared library. Using this constructor effectively disables + * all setters except SetFilePath(). + * + * @param absoluteFilePath The absolute path to the shared library. + */ + SharedLibrary(const std::string& absoluteFilePath); + + /** + * Destroys this object but does not unload the shared library. + */ + ~SharedLibrary(); + + SharedLibrary& operator=(const SharedLibrary& other); + + /** + * Loads the shared library pointed to by this SharedLibrary object. + * On POSIX systems dlopen() is called with the RTLD_LAZY and + * RTLD_LOCAL flags unless the compiler is gcc 4.4.x or older. Then + * the RTLD_LAZY and RTLD_GLOBAL flags are used to load the shared library + * to work around RTTI problems across shared library boundaries. + * + * @throws std::logic_error If the library is already loaded. + * @throws std::runtime_error If loading the library failed. + */ + void Load(); + + /** + * Loads the shared library pointed to by this SharedLibrary object, + * using the specified flags on POSIX systems. + * + * @throws std::logic_error If the library is already loaded. + * @throws std::runtime_error If loading the library failed. + */ + void Load(int flags); + + /** + * Un-loads the shared library pointed to by this SharedLibrary object. + * + * @throws std::runtime_error If an error occurred while un-loading the + * shared library. + */ + void Unload(); + + /** + * Sets the base name of the shared library. Does nothing if the shared + * library is already loaded or the SharedLibrary(const std::string&) + * constructor was used. + * + * @param name The base name of the shared library, without prefix and + * suffix. + */ + void SetName(const std::string& name); + + /** + * Gets the base name of the shared library. + * @return The shared libraries base name. + */ + std::string GetName() const; + + /** + * Gets the absolute file path for the shared library with base name + * \c name, using the search path returned by GetLibraryPath(). + * + * @param name The shared library base name. + * @return The absolute file path of the shared library. + */ + std::string GetFilePath(const std::string& name) const; + + /** + * Sets the absolute file path of this SharedLibrary object. + * Using this methods with a non-empty \c absoluteFilePath argument + * effectively disables all other setters. + * + * @param absoluteFilePath The new absolute file path of this SharedLibrary + * object. + */ + void SetFilePath(const std::string& absoluteFilePath); + + /** + * Gets the absolute file path of this SharedLibrary object. + * + * @return The absolute file path of the shared library. + */ + std::string GetFilePath() const; + + /** + * Sets a new library search path. Does nothing if the shared + * library is already loaded or the SharedLibrary(const std::string&) + * constructor was used. + * + * @param path The new shared library search path. + */ + void SetLibraryPath(const std::string& path); + + /** + * Gets the library search path of this SharedLibrary object. + * + * @return The library search path. + */ + std::string GetLibraryPath() const; + + /** + * Sets the suffix for shared library names (e.g. lib). Does nothing if the shared + * library is already loaded or the SharedLibrary(const std::string&) + * constructor was used. + * + * @param suffix The shared library name suffix. + */ + void SetSuffix(const std::string& suffix); + + /** + * Gets the file name suffix of this SharedLibrary object. + * + * @return The file name suffix of the shared library. + */ + std::string GetSuffix() const; + + /** + * Sets the file name prefix for shared library names (e.g. .dll or .so). + * Does nothing if the shared library is already loaded or the + * SharedLibrary(const std::string&) constructor was used. + * + * @param prefix The shared library name prefix. + */ + void SetPrefix(const std::string& prefix); + + /** + * Gets the file name prefix of this SharedLibrary object. + * + * @return The file name prefix of the shared library. + */ + std::string GetPrefix() const; + + /** + * Gets the internal handle of this SharedLibrary object. + * + * @return \c NULL if the shared library is not loaded, the operating + * system specific handle otherwise. + */ + void* GetHandle() const; + + /** + * Gets the loaded/unloaded stated of this SharedLibrary object. + * + * @return \c true if the shared library is loaded, \c false otherwise. + */ + bool IsLoaded() const; + +private: + + ExplicitlySharedDataPointer d; + +}; + +US_END_NAMESPACE + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif // USTESTUTILSHAREDLIBRARY_H diff --git a/src/util/usStaticInit_p.h b/src/util/usStaticInit_p.h new file mode 100644 index 0000000000..b69d45c61d --- /dev/null +++ b/src/util/usStaticInit_p.h @@ -0,0 +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_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/src/util/usThreads.cpp b/src/util/usThreads.cpp new file mode 100644 index 0000000000..4464c9038e --- /dev/null +++ b/src/util/usThreads.cpp @@ -0,0 +1,254 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usThreads_p.h" + +#include "usUtils_p.h" + +#ifdef US_PLATFORM_POSIX +#include +#include +#endif + +US_BEGIN_NAMESPACE + +WaitCondition::WaitCondition() +{ +#ifdef US_ENABLE_THREADING_SUPPORT + #ifdef US_PLATFORM_POSIX + pthread_cond_init(&m_WaitCondition, 0); + #else + m_NumberOfWaiters = 0; + m_WasNotifyAll = 0; + m_Semaphore = CreateSemaphore(0, // no security + 0, // initial value + 0x7fffffff, // max count + 0); // unnamed + InitializeCriticalSection(&m_NumberOfWaitersLock); + m_WaitersAreDone = CreateEvent(0, // no security + FALSE, // auto-reset + FALSE, // non-signaled initially + 0 ); // unnamed + #endif +#endif +} + +WaitCondition::~WaitCondition() +{ +#ifdef US_ENABLE_THREADING_SUPPORT + #ifdef US_PLATFORM_POSIX + pthread_cond_destroy(&m_WaitCondition); + #else + CloseHandle(m_Semaphore); + CloseHandle(m_WaitersAreDone); + DeleteCriticalSection(&m_NumberOfWaitersLock); + #endif +#endif +} + +void WaitCondition::Notify() +{ +#ifdef US_ENABLE_THREADING_SUPPORT + #ifdef US_PLATFORM_POSIX + pthread_cond_signal(&m_WaitCondition); + #else + EnterCriticalSection(&m_NumberOfWaitersLock); + int haveWaiters = m_NumberOfWaiters > 0; + LeaveCriticalSection(&m_NumberOfWaitersLock); + + // if there were not any waiters, then this is a no-op + if (haveWaiters) + { + ReleaseSemaphore(m_Semaphore, 1, 0); + } + #endif +#endif +} + +void WaitCondition::NotifyAll() +{ +#ifdef US_ENABLE_THREADING_SUPPORT + #ifdef US_PLATFORM_POSIX + pthread_cond_broadcast(&m_WaitCondition); + #else + // This is needed to ensure that m_NumberOfWaiters and m_WasNotifyAll are + // consistent + EnterCriticalSection(&m_NumberOfWaitersLock); + int haveWaiters = 0; + + if (m_NumberOfWaiters > 0) + { + // We are broadcasting, even if there is just one waiter... + // Record that we are broadcasting, which helps optimize Notify() + // for the non-broadcast case + m_WasNotifyAll = 1; + haveWaiters = 1; + } + + if (haveWaiters) + { + // Wake up all waiters atomically + ReleaseSemaphore(m_Semaphore, m_NumberOfWaiters, 0); + + LeaveCriticalSection(&m_NumberOfWaitersLock); + + // Wait for all the awakened threads to acquire the counting + // semaphore + WaitForSingleObject(m_WaitersAreDone, INFINITE); + // This assignment is ok, even without the m_NumberOfWaitersLock held + // because no other waiter threads can wake up to access it. + m_WasNotifyAll = 0; + } + else + { + LeaveCriticalSection(&m_NumberOfWaitersLock); + } + #endif +#endif +} + +bool WaitCondition::Wait(MutexType* mutex, unsigned long timeoutMillis) +{ + return Wait(*mutex, timeoutMillis); +} + +#ifdef US_ENABLE_THREADING_SUPPORT +bool WaitCondition::Wait(MutexType& mutex, unsigned long timeoutMillis) +{ + #ifdef US_PLATFORM_POSIX + struct timespec ts, * pts = 0; + if (timeoutMillis) + { + pts = &ts; + struct timeval tv; + int error = gettimeofday(&tv, NULL); + if (error) + { + US_ERROR << "gettimeofday error: " << GetLastErrorStr(); + return false; + } + ts.tv_sec = tv.tv_sec; + ts.tv_nsec = tv.tv_usec * 1000; + ts.tv_sec += timeoutMillis / 1000; + ts.tv_nsec += (timeoutMillis % 1000) * 1000000; + ts.tv_sec += ts.tv_nsec / 1000000000; + ts.tv_nsec = ts.tv_nsec % 1000000000; + } + + if (pts) + { + int error = pthread_cond_timedwait(&m_WaitCondition, &mutex.m_Mtx, pts); + if (error == 0) + { + return true; + } + else + { + if (error != ETIMEDOUT) + { + US_ERROR << "pthread_cond_timedwait error: " << GetLastErrorStr(); + } + return false; + } + } + else + { + int error = pthread_cond_wait(&m_WaitCondition, &mutex.m_Mtx); + if (error) + { + US_ERROR << "pthread_cond_wait error: " << GetLastErrorStr(); + return false; + } + return true; + } + + #else + + // Avoid race conditions + EnterCriticalSection(&m_NumberOfWaitersLock); + m_NumberOfWaiters++; + LeaveCriticalSection(&m_NumberOfWaitersLock); + + DWORD dw; + bool result = true; + + // This call atomically releases the mutex and waits on the + // semaphore until signaled + dw = SignalObjectAndWait(mutex.m_Mtx, m_Semaphore, timeoutMillis ? timeoutMillis : INFINITE, FALSE); + if (dw == WAIT_TIMEOUT) + { + result = false; + } + else if (dw == WAIT_FAILED) + { + result = false; + US_ERROR << "SignalObjectAndWait failed: " << GetLastErrorStr(); + } + + // Reacquire lock to avoid race conditions + EnterCriticalSection(&m_NumberOfWaitersLock); + + // We're no longer waiting.... + m_NumberOfWaiters--; + + // Check to see if we're the last waiter after the broadcast + int lastWaiter = m_WasNotifyAll && m_NumberOfWaiters == 0; + + LeaveCriticalSection(&m_NumberOfWaitersLock); + + // If we're the last waiter thread during this particular broadcast + // then let the other threads proceed + if (lastWaiter) + { + // This call atomically signals the m_WaitersAreDone event and waits + // until it can acquire the external mutex. This is required to + // ensure fairness + dw = SignalObjectAndWait(m_WaitersAreDone, mutex.m_Mtx, + INFINITE, FALSE); + if (result && dw == WAIT_FAILED) + { + result = false; + US_ERROR << "SignalObjectAndWait failed: " << GetLastErrorStr(); + } + } + else + { + // Always regain the external mutex since that's the guarentee we + // give to our callers + dw = WaitForSingleObject(mutex.m_Mtx, INFINITE); + if (result && dw == WAIT_FAILED) + { + result = false; + US_ERROR << "SignalObjectAndWait failed: " << GetLastErrorStr(); + } + } + + return result; + #endif +} +#else +bool WaitCondition::Wait(MutexType&, unsigned long) +{ + return true; +} +#endif + +US_END_NAMESPACE diff --git a/src/util/usThreads_p.h b/src/util/usThreads_p.h new file mode 100644 index 0000000000..8c77a24781 --- /dev/null +++ b/src/util/usThreads_p.h @@ -0,0 +1,430 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USTHREADINGMODEL_H +#define USTHREADINGMODEL_H + +#include + +#ifdef US_ENABLE_THREADING_SUPPORT + + // Atomic compiler intrinsics + + #if defined(US_PLATFORM_APPLE) + // OSAtomic.h optimizations only used in 10.5 and later + #include + #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 + #include + #define US_ATOMIC_OPTIMIZATION_APPLE + #endif + + #elif defined(__GLIBCPP__) || defined(__GLIBCXX__) + + #if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) + # include + #else + # include + #endif + #define US_ATOMIC_OPTIMIZATION_GNUC + + #endif + + // Mutex support + + #ifdef US_PLATFORM_WINDOWS + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include + + #define US_THREADS_MUTEX(x) HANDLE (x); + #define US_THREADS_MUTEX_INIT(x) + #define US_THREADS_MUTEX_CTOR(x) : x(::CreateMutex(NULL, FALSE, NULL)) + #define US_THREADS_MUTEX_DELETE(x) ::CloseHandle (x) + #define US_THREADS_MUTEX_LOCK(x) ::WaitForSingleObject (x, INFINITE) + #define US_THREADS_MUTEX_UNLOCK(x) ::ReleaseMutex (x) + #define US_THREADS_LONG LONG + + #define US_ATOMIC_OPTIMIZATION + #define US_ATOMIC_INCREMENT(x) IntType n = InterlockedIncrement(x) + #define US_ATOMIC_DECREMENT(x) IntType n = InterlockedDecrement(x) + #define US_ATOMIC_ASSIGN(l, r) InterlockedExchange(l, r) + + #elif defined(US_PLATFORM_POSIX) + + #include + + #define US_THREADS_MUTEX(x) pthread_mutex_t (x); + #define US_THREADS_MUTEX_INIT(x) ::pthread_mutex_init(&x, 0) + #define US_THREADS_MUTEX_CTOR(x) : x() + #define US_THREADS_MUTEX_DELETE(x) ::pthread_mutex_destroy (&x) + #define US_THREADS_MUTEX_LOCK(x) ::pthread_mutex_lock (&x) + #define US_THREADS_MUTEX_UNLOCK(x) ::pthread_mutex_unlock (&x) + + #define US_ATOMIC_OPTIMIZATION + #if defined(US_ATOMIC_OPTIMIZATION_APPLE) + #if defined (__LP64__) && __LP64__ + #define US_THREADS_LONG volatile int64_t + #define US_ATOMIC_INCREMENT(x) IntType n = OSAtomicIncrement64Barrier(x) + #define US_ATOMIC_DECREMENT(x) IntType n = OSAtomicDecrement64Barrier(x) + #define US_ATOMIC_ASSIGN(l, v) OSAtomicCompareAndSwap64Barrier(*l, v, l) + #else + #define US_THREADS_LONG volatile int32_t + #define US_ATOMIC_INCREMENT(x) IntType n = OSAtomicIncrement32Barrier(x) + #define US_ATOMIC_DECREMENT(x) IntType n = OSAtomicDecrement32Barrier(x) + #define US_ATOMIC_ASSIGN(l, v) OSAtomicCompareAndSwap32Barrier(*l, v, l) + #endif + #elif defined(US_ATOMIC_OPTIMIZATION_GNUC) + #define US_THREADS_LONG _Atomic_word + #define US_ATOMIC_INCREMENT(x) IntType n = __sync_add_and_fetch(x, 1) + #define US_ATOMIC_DECREMENT(x) IntType n = __sync_add_and_fetch(x, -1) + #define US_ATOMIC_ASSIGN(l, v) __sync_val_compare_and_swap(l, *l, v) + #else + #define US_THREADS_LONG long + #undef US_ATOMIC_OPTIMIZATION + #define US_ATOMIC_INCREMENT(x) m_AtomicMtx.Lock(); \ + IntType n = ++(*x); \ + m_AtomicMtx.Unlock() + #define US_ATOMIC_DECREMENT(x) m_AtomicMtx.Lock(); \ + IntType n = --(*x); \ + m_AtomicMtx.Unlock() + #define US_ATOMIC_ASSIGN(l, v) m_AtomicMtx.Lock(); \ + *l = v; \ + m_AtomicMtx.Unlock() + #endif + + #endif + +#else + + // single threaded + #define US_THREADS_MUTEX(x) + #define US_THREADS_MUTEX_INIT(x) + #define US_THREADS_MUTEX_CTOR(x) + #define US_THREADS_MUTEX_DELETE(x) + #define US_THREADS_MUTEX_LOCK(x) + #define US_THREADS_MUTEX_UNLOCK(x) + #define US_THREADS_LONG + +#endif + +#ifndef US_DEFAULT_MUTEX + #define US_DEFAULT_MUTEX US_PREPEND_NAMESPACE(Mutex) +#endif + + +US_BEGIN_NAMESPACE + +class Mutex +{ +public: + + Mutex() US_THREADS_MUTEX_CTOR(m_Mtx) + { + US_THREADS_MUTEX_INIT(m_Mtx); + } + + ~Mutex() + { + US_THREADS_MUTEX_DELETE(m_Mtx); + } + + void Lock() + { + US_THREADS_MUTEX_LOCK(m_Mtx); + } + void Unlock() + { + US_THREADS_MUTEX_UNLOCK(m_Mtx); + } + +private: + + friend class WaitCondition; + + // Copy-constructor not implemented. + Mutex(const Mutex &); + // Copy-assignement operator not implemented. + Mutex & operator = (const Mutex &); + + US_THREADS_MUTEX(m_Mtx) +}; + +template +class MutexLock +{ +public: + typedef MutexPolicy MutexType; + + MutexLock(MutexType& mtx) : m_Mtx(&mtx) { m_Mtx->Lock(); } + ~MutexLock() { m_Mtx->Unlock(); } + +private: + MutexType* m_Mtx; + + // purposely not implemented + MutexLock(const MutexLock&); + MutexLock& operator=(const MutexLock&); +}; + +typedef MutexLock<> DefaultMutexLock; + + +/** + * \brief A thread synchronization object used to suspend execution until some + * condition on shared data is met. + * + * A thread calls Wait() to suspend its execution until the condition is + * met. Each call to Notify() from an executing thread will then cause a single + * waiting thread to be released. A call to Notify() means, "signal + * that the condition is true." NotifyAll() releases all threads waiting on + * the condition variable. + * + * The WaitCondition implementation is consistent with the standard + * definition and use of condition variables in pthreads and other common + * thread libraries. + * + * IMPORTANT: A condition variable always requires an associated mutex + * object. The mutex object is used to avoid a dangerous race condition when + * Wait() and Notify() are called simultaneously from two different + * threads. + * + * On systems using pthreads, this implementation abstracts the + * standard calls to the pthread condition variable. On Win32 + * systems, there is no system provided condition variable. This + * class implements a condition variable using a critical section, a + * semphore, an event and a number of counters. The implementation is + * almost an extract translation of the implementation presented by + * Douglas C Schmidt and Irfan Pyarali in "Strategies for Implementing + * POSIX Condition Variables on Win32". This article can be found at + * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html + * + */ +class US_EXPORT WaitCondition +{ +public: + + typedef US_DEFAULT_MUTEX MutexType; + + WaitCondition(); + ~WaitCondition(); + + /** Suspend execution of this thread until the condition is signaled. The + * argument is a SimpleMutex object that must be locked prior to calling + * this method. */ + bool Wait(MutexType& mutex, unsigned long time = 0); + + bool Wait(MutexType* mutex, unsigned long time = 0); + + /** Notify that the condition is true and release one waiting thread */ + void Notify(); + + /** Notify that the condition is true and release all waiting threads */ + void NotifyAll(); + +private: + + // purposely not implemented + WaitCondition(const WaitCondition& other); + const WaitCondition& operator=(const WaitCondition&); + +#ifdef US_ENABLE_THREADING_SUPPORT + #ifdef US_PLATFORM_POSIX + pthread_cond_t m_WaitCondition; + #else + + int m_NumberOfWaiters; // number of waiting threads + CRITICAL_SECTION m_NumberOfWaitersLock; // Serialize access to + // m_NumberOfWaiters + + HANDLE m_Semaphore; // Semaphore to queue threads + HANDLE m_WaitersAreDone; // Auto-reset event used by the + // broadcast/signal thread to + // wait for all the waiting + // threads to wake up and + // release the semaphore + + std::size_t m_WasNotifyAll; // Keeps track of whether we + // were broadcasting or signaling + #endif + +#endif +}; + +US_END_NAMESPACE + +#ifdef US_ENABLE_THREADING_SUPPORT + +US_BEGIN_NAMESPACE + +template +class MultiThreaded +{ + mutable MutexPolicy m_Mtx; + WaitCondition m_Cond; + + #if !defined(US_ATOMIC_OPTIMIZATION) + mutable MutexPolicy m_AtomicMtx; + #endif + +public: + + MultiThreaded() : m_Mtx(), m_Cond() {} + MultiThreaded(const MultiThreaded&) : m_Mtx(), m_Cond() {} + virtual ~MultiThreaded() {} + + class Lock; + friend class Lock; + + class Lock + { + public: + + // Lock object + explicit Lock(const MultiThreaded& host) : m_Host(host) + { + m_Host.m_Mtx.Lock(); + } + + // Lock object + explicit Lock(const MultiThreaded* host) : m_Host(*host) + { + m_Host.m_Mtx.Lock(); + } + + // Unlock object + ~Lock() + { + m_Host.m_Mtx.Unlock(); + } + + private: + + // private by design + Lock(); + Lock(const Lock&); + Lock& operator=(const Lock&); + const MultiThreaded& m_Host; + + }; + + typedef volatile Host VolatileType; + typedef US_THREADS_LONG IntType; + + bool Wait(unsigned long timeoutMillis = 0) + { + return m_Cond.Wait(m_Mtx, timeoutMillis); + } + + void Notify() + { + m_Cond.Notify(); + } + + void NotifyAll() + { + m_Cond.NotifyAll(); + } + + IntType AtomicIncrement(volatile IntType& lval) const + { + US_ATOMIC_INCREMENT(&lval); + return n; + } + + IntType AtomicDecrement(volatile IntType& lval) const + { + US_ATOMIC_DECREMENT(&lval); + return n; + } + + void AtomicAssign(volatile IntType& lval, const IntType val) const + { + US_ATOMIC_ASSIGN(&lval, val); + } + +}; + +US_END_NAMESPACE + +#endif + + +US_BEGIN_NAMESPACE + +template +class SingleThreaded +{ +public: + + virtual ~SingleThreaded() {} + + // Dummy Lock class + struct Lock + { + Lock() {} + explicit Lock(const SingleThreaded&) {} + explicit Lock(const SingleThreaded*) {} + }; + + typedef Host VolatileType; + typedef int IntType; + + bool Wait(unsigned long = 0) + { return false; } + + void Notify() {} + + void NotifyAll() {} + + static IntType AtomicAdd(volatile IntType& lval, const IntType val) + { return lval += val; } + + static IntType AtomicSubtract(volatile IntType& lval, const IntType val) + { return lval -= val; } + + static IntType AtomicMultiply(volatile IntType& lval, const IntType val) + { return lval *= val; } + + static IntType AtomicDivide(volatile IntType& lval, const IntType val) + { return lval /= val; } + + static IntType AtomicIncrement(volatile IntType& lval) + { return ++lval; } + + static IntType AtomicDecrement(volatile IntType& lval) + { return --lval; } + + static void AtomicAssign(volatile IntType & lval, const IntType val) + { lval = val; } + + static void AtomicAssign(IntType & lval, volatile IntType & val) + { lval = val; } + +}; + +US_END_NAMESPACE + +#endif // USTHREADINGMODEL_H diff --git a/src/util/usUncompressResourceData.c b/src/util/usUncompressResourceData.c new file mode 100644 index 0000000000..310491ed82 --- /dev/null +++ b/src/util/usUncompressResourceData.c @@ -0,0 +1,59 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#include "tinfl.c" + +#include + +static char us_uncompress_error_msg[256]; + +const char* us_uncompress_resource_error() +{ + return us_uncompress_error_msg; +} + +void us_uncompress_resource_data(const unsigned char* data, size_t size, + unsigned char* uncompressedData, size_t uncompressedSize) +{ + size_t bytesWritten = 0; + + memset(us_uncompress_error_msg, 0, sizeof(us_uncompress_error_msg)); + + if (data == NULL) + { + return; + } + + if (uncompressedData == NULL) + { + sprintf(us_uncompress_error_msg, "us_uncompress_resource_data: Buffer for uncomcpressing data is NULL"); + return; + } + + bytesWritten = tinfl_decompress_mem_to_mem(uncompressedData, uncompressedSize, + data, size, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if (bytesWritten != uncompressedSize) + { + sprintf(us_uncompress_error_msg, "us_uncompress_resource_data: tinfl_decompress_mem_to_mem failed"); + } +} diff --git a/src/util/usUncompressResourceData.cpp b/src/util/usUncompressResourceData.cpp new file mode 100644 index 0000000000..dbc383145d --- /dev/null +++ b/src/util/usUncompressResourceData.cpp @@ -0,0 +1,86 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usUncompressResourceData.h" + +#ifdef US_ENABLE_RESOURCE_COMPRESSION +#include "usUtils_p.h" + +extern "C" { +const char* us_uncompress_resource_error(); +void us_uncompress_resource_data(const unsigned char*, size_t, unsigned char*, size_t); +} + +US_BEGIN_NAMESPACE + +unsigned char* UncompressResourceData(const unsigned char* data, std::size_t size, + std::size_t* uncompressedSize) +{ + if (size <= 4) + { + if (size < 4 || (data[0] != 0 || data[1] != 0 || data[2] != 0 || data[3] != 0)) + { + US_WARN << "UncompressResourceData: Input data is corrupted"; + return NULL; + } + } + std::size_t expectedSize = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; + try + { + unsigned char* uncompressedData = new unsigned char[expectedSize]; + us_uncompress_resource_data(data+4, size-4, uncompressedData, expectedSize); + if (us_uncompress_resource_error()[0] != 0) + { + US_WARN << us_uncompress_resource_error(); + delete[] uncompressedData; + return NULL; + } + + if (uncompressedSize != NULL) + { + *uncompressedSize = expectedSize; + } + + return uncompressedData; + } + catch (const std::bad_alloc&) + { + US_WARN << "UncompressResourceData: Could not allocate enough memory for uncompressing resource data"; + return NULL; + } + + return NULL; +} + +US_END_NAMESPACE + +#else + +US_BEGIN_NAMESPACE + +unsigned char* UncompressResourceData(const unsigned char*, std::size_t, std::size_t*) +{ + return 0; +} + +US_END_NAMESPACE + +#endif // US_ENABLE_RESOURCE_COMPRESSION diff --git a/src/util/usUncompressResourceData.h b/src/util/usUncompressResourceData.h new file mode 100644 index 0000000000..a3e82f3679 --- /dev/null +++ b/src/util/usUncompressResourceData.h @@ -0,0 +1,33 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USUNCOMPRESSRESOURCEDATA_H +#define USUNCOMPRESSRESOURCEDATA_H + +#include "usConfig.h" + +US_BEGIN_NAMESPACE + +US_EXPORT unsigned char* UncompressResourceData(const unsigned char* data, std::size_t size, std::size_t* uncompressedSize); + +US_END_NAMESPACE + +#endif // USUNCOMPRESSRESOURCEDATA_H diff --git a/src/util/usUtils.cpp b/src/util/usUtils.cpp new file mode 100644 index 0000000000..5cfb254075 --- /dev/null +++ b/src/util/usUtils.cpp @@ -0,0 +1,270 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usUtils_p.h" + +#include "usModuleInfo.h" +#include "usModuleSettings.h" + +#include + +#ifdef US_PLATFORM_POSIX + #include + #include + #include + #include +#else + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #include + #include "dirent_win32_p.h" +#endif + +//------------------------------------------------------------------- +// Module auto-loading +//------------------------------------------------------------------- + +namespace { + +#if !defined(US_PLATFORM_LINUX) +std::string library_suffix() +{ +#ifdef US_PLATFORM_WINDOWS + return ".dll"; +#elif defined(US_PLATFORM_APPLE) + return ".dylib"; +#else + return ".so"; +#endif +} +#endif + +#ifdef US_PLATFORM_POSIX + +const char DIR_SEP = '/'; + +bool load_impl(const std::string& modulePath) +{ + void* handle = dlopen(modulePath.c_str(), RTLD_NOW | RTLD_LOCAL); + return (handle != NULL); +} + +#elif defined(US_PLATFORM_WINDOWS) + +const char DIR_SEP = '\\'; + +bool load_impl(const std::string& modulePath) +{ + void* handle = LoadLibrary(modulePath.c_str()); + return (handle != NULL); +} + +#else + + #ifdef US_ENABLE_AUTOLOADING_SUPPORT + #error "Missing load_impl implementation for this platform." + #else +bool load_impl(const std::string&) { return false; } + #endif + +#endif + +} + +US_BEGIN_NAMESPACE + +void AutoLoadModulesFromPath(const std::string& absoluteBasePath, const std::string& subDir) +{ + std::string loadPath = absoluteBasePath + DIR_SEP + subDir; + + DIR* dir = opendir(loadPath.c_str()); +#ifdef CMAKE_INTDIR + // Try intermediate output directories + if (dir == NULL) + { + std::size_t indexOfLastSeparator = absoluteBasePath.find_last_of(DIR_SEP); + if (indexOfLastSeparator != -1) + { + if (absoluteBasePath.substr(indexOfLastSeparator+1) == CMAKE_INTDIR) + { + loadPath = absoluteBasePath.substr(0, indexOfLastSeparator+1) + subDir + DIR_SEP + CMAKE_INTDIR; + dir = opendir(loadPath.c_str()); + } + } + } +#endif + + if (dir != NULL) + { + struct dirent *ent = NULL; + while ((ent = readdir(dir)) != NULL) + { + bool loadFile = true; +#ifdef _DIRENT_HAVE_D_TYPE + if (ent->d_type != DT_UNKNOWN && ent->d_type != DT_REG) + { + loadFile = false; + } +#endif + + std::string entryFileName(ent->d_name); + + // On Linux, library file names can have version numbers appended. On other platforms, we + // check the file ending. This could be refined for Linux in the future. +#if !defined(US_PLATFORM_LINUX) + if (entryFileName.rfind(library_suffix()) != (entryFileName.size() - library_suffix().size())) + { + loadFile = false; + } +#endif + if (!loadFile) continue; + + std::string libPath = loadPath; + if (!libPath.empty() && libPath.find_last_of(DIR_SEP) != libPath.size() -1) + { + libPath += DIR_SEP; + } + libPath += entryFileName; + US_INFO << "Auto-loading module " << libPath; + + if (!load_impl(libPath)) + { + US_WARN << "Auto-loading of module " << libPath << " failed: " << GetLastErrorStr(); + } + } + closedir(dir); + } +} + +void AutoLoadModules(const ModuleInfo& moduleInfo) +{ + if (moduleInfo.autoLoadDir.empty()) + { + return; + } + + ModuleSettings::PathList autoLoadPaths = ModuleSettings::GetAutoLoadPaths(); + + std::size_t indexOfLastSeparator = moduleInfo.location.find_last_of(DIR_SEP); + std::string moduleBasePath = moduleInfo.location.substr(0, indexOfLastSeparator); + + for (ModuleSettings::PathList::iterator i = autoLoadPaths.begin(); + i != autoLoadPaths.end(); ++i) + { + if (*i == ModuleSettings::CURRENT_MODULE_PATH()) + { + // Load all modules from a directory located relative to this modules location + // and named after this modules library name. + *i = moduleBasePath; + } + } + + // We could have introduced a duplicate above, so remove it. + std::sort(autoLoadPaths.begin(), autoLoadPaths.end()); + autoLoadPaths.erase(std::unique(autoLoadPaths.begin(), autoLoadPaths.end()), autoLoadPaths.end()); + for (ModuleSettings::PathList::iterator i = autoLoadPaths.begin(); + i != autoLoadPaths.end(); ++i) + { + if (i->empty()) continue; + AutoLoadModulesFromPath(*i, moduleInfo.autoLoadDir); + } +} + +US_END_NAMESPACE + +//------------------------------------------------------------------- +// Error handling +//------------------------------------------------------------------- + +US_BEGIN_NAMESPACE + +std::string GetLastErrorStr() +{ +#ifdef US_PLATFORM_POSIX + return std::string(strerror(errno)); +#else + // Retrieve the system error message for the last-error code + LPVOID lpMsgBuf; + DWORD dw = GetLastError(); + + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + dw, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) &lpMsgBuf, + 0, NULL ); + + std::string errMsg((LPCTSTR)lpMsgBuf); + + LocalFree(lpMsgBuf); + + return errMsg; +#endif +} + +static MsgHandler handler = 0; + +MsgHandler installMsgHandler(MsgHandler h) +{ + MsgHandler old = handler; + handler = h; + return old; +} + +void message_output(MsgType msgType, const char *buf) +{ + if (handler) + { + (*handler)(msgType, buf); + } + else + { + fprintf(stderr, "%s\n", buf); + fflush(stderr); + } + + if (msgType == ErrorMsg) + { + #if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) + // get the current report mode + int reportMode = _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW); + _CrtSetReportMode(_CRT_ERROR, reportMode); + int ret = _CrtDbgReport(_CRT_ERROR, __FILE__, __LINE__, CppMicroServices_VERSION_STR, buf); + if (ret == 0 && reportMode & _CRTDBG_MODE_WNDW) + return; // ignore + else if (ret == 1) + _CrtDbgBreak(); + #endif + + #ifdef US_PLATFORM_POSIX + abort(); // trap; generates core dump + #else + exit(1); // goodbye cruel world + #endif + } +} + +US_END_NAMESPACE diff --git a/src/util/usUtils_p.h b/src/util/usUtils_p.h new file mode 100644 index 0000000000..32c88713e2 --- /dev/null +++ b/src/util/usUtils_p.h @@ -0,0 +1,225 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USUTILS_H +#define USUTILS_H + +#include + +#include +#include +#include + + +//------------------------------------------------------------------- +// Logging +//------------------------------------------------------------------- + +US_BEGIN_NAMESPACE + +US_EXPORT void message_output(MsgType, const char* buf); + +struct LogMsg { + + LogMsg(int t, const char* file, int ln, const char* func) + : type(static_cast(t)), enabled(true), buffer() + { buffer << "In " << func << " at " << file << ":" << ln << " : "; } + + ~LogMsg() { if(enabled) message_output(type, buffer.str().c_str()); } + + template + LogMsg& operator<<(T t) + { + if (enabled) buffer << t; + return *this; + } + + LogMsg& operator()(bool flag) + { + this->enabled = flag; + return *this; + } + +private: + + MsgType type; + bool enabled; + std::stringstream buffer; +}; + +struct NoLogMsg { + + template + NoLogMsg& operator<<(T) + { + return *this; + } + + NoLogMsg& operator()(bool) + { + return *this; + } + +}; + +US_END_NAMESPACE + +#if defined(US_ENABLE_DEBUG_OUTPUT) + #define US_DEBUG US_PREPEND_NAMESPACE(LogMsg)(0, __FILE__, __LINE__, __FUNCTION__) +#else + #define US_DEBUG true ? US_PREPEND_NAMESPACE(NoLogMsg)() : US_PREPEND_NAMESPACE(NoLogMsg)() +#endif + +#if !defined(US_NO_INFO_OUTPUT) + #define US_INFO US_PREPEND_NAMESPACE(LogMsg)(1, __FILE__, __LINE__, __FUNCTION__) +#else + #define US_INFO true ? US_PREPEND_NAMESPACE(NoLogMsg)() : US_PREPEND_NAMESPACE(NoLogMsg)() +#endif + +#if !defined(US_NO_WARNING_OUTPUT) + #define US_WARN US_PREPEND_NAMESPACE(LogMsg)(2, __FILE__, __LINE__, __FUNCTION__) +#else + #define US_WARN true ? US_PREPEND_NAMESPACE(LogMsg)() : US_PREPEND_NAMESPACE(LogMsg)() +#endif + +#define US_ERROR US_PREPEND_NAMESPACE(LogMsg)(3, __FILE__, __LINE__, __FUNCTION__) + +//------------------------------------------------------------------- +// Module auto-loading +//------------------------------------------------------------------- + +US_BEGIN_NAMESPACE + +struct ModuleInfo; + +void AutoLoadModules(const ModuleInfo& moduleInfo); + +US_END_NAMESPACE + +//------------------------------------------------------------------- +// Error handling +//------------------------------------------------------------------- + +US_BEGIN_NAMESPACE + +US_EXPORT std::string GetLastErrorStr(); + +US_END_NAMESPACE + + +//------------------------------------------------------------------- +// Functors +//------------------------------------------------------------------- + +#include +#include + +#if defined(US_USE_CXX11) || defined(__GNUC__) + + #ifdef US_USE_CXX11 + #include + #define US_MODULE_LISTENER_FUNCTOR std::function + #define US_SERVICE_LISTENER_FUNCTOR std::function + #else + #include + #define US_MODULE_LISTENER_FUNCTOR std::tr1::function + #define US_SERVICE_LISTENER_FUNCTOR std::tr1::function + #endif + + US_BEGIN_NAMESPACE + template + US_MODULE_LISTENER_FUNCTOR ModuleListenerMemberFunctor(X* x, void (X::*memFn)(const US_PREPEND_NAMESPACE(ModuleEvent))) + { return std::bind1st(std::mem_fun(memFn), x); } + US_END_NAMESPACE + + US_BEGIN_NAMESPACE + struct ModuleListenerCompare : std::binary_function, + std::pair, bool> + { + bool operator()(const std::pair& p1, + const std::pair& p2) const + { + return p1.second == p2.second && + p1.first.target() == p2.first.target(); + } + }; + US_END_NAMESPACE + + US_BEGIN_NAMESPACE + template + US_SERVICE_LISTENER_FUNCTOR ServiceListenerMemberFunctor(X* x, void (X::*memFn)(const US_PREPEND_NAMESPACE(ServiceEvent))) + { return std::bind1st(std::mem_fun(memFn), x); } + US_END_NAMESPACE + + US_BEGIN_NAMESPACE + struct ServiceListenerCompare : std::binary_function + { + bool operator()(const US_SERVICE_LISTENER_FUNCTOR& f1, + const US_SERVICE_LISTENER_FUNCTOR& f2) const + { + return f1.target() == f2.target(); + } + }; + US_END_NAMESPACE + +#else + + #include + + #define US_MODULE_LISTENER_FUNCTOR US_PREPEND_NAMESPACE(Functor) + + US_BEGIN_NAMESPACE + template + US_MODULE_LISTENER_FUNCTOR ModuleListenerMemberFunctor(X* x, MemFn memFn) + { return Functor(x, memFn); } + US_END_NAMESPACE + + US_BEGIN_NAMESPACE + struct ModuleListenerCompare : std::binary_function, + std::pair, bool> + { + bool operator()(const std::pair& p1, + const std::pair& p2) const + { return p1.second == p2.second && p1.first == p2.first; } + }; + US_END_NAMESPACE + + #define US_SERVICE_LISTENER_FUNCTOR US_PREPEND_NAMESPACE(Functor) + + US_BEGIN_NAMESPACE + template + US_SERVICE_LISTENER_FUNCTOR ServiceListenerMemberFunctor(X* x, MemFn memFn) + { return Functor(x, memFn); } + US_END_NAMESPACE + + US_BEGIN_NAMESPACE + struct ServiceListenerCompare : std::binary_function + { + bool operator()(const US_SERVICE_LISTENER_FUNCTOR& f1, + const US_SERVICE_LISTENER_FUNCTOR& f2) const + { return f1 == f2; } + }; + US_END_NAMESPACE + +#endif + +#endif // USUTILS_H diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt new file mode 100644 index 0000000000..c4bb27b578 --- /dev/null +++ b/test/CMakeLists.txt @@ -0,0 +1,87 @@ + +#----------------------------------------------------------------------------- +# Configure files, include dirs, etc. +#----------------------------------------------------------------------------- + +configure_file("${CMAKE_CURRENT_SOURCE_DIR}/usTestingConfig.h.in" "${PROJECT_BINARY_DIR}/include/usTestingConfig.h") + +include_directories(${US_INCLUDE_DIRS} ${CMAKE_CURRENT_SOURCE_DIR}) + +#----------------------------------------------------------------------------- +# Create test modules +#----------------------------------------------------------------------------- + +include(usFunctionCreateTestModule) + +set(_us_test_module_libs "" CACHE INTERNAL "" FORCE) +add_subdirectory(modules) + +#----------------------------------------------------------------------------- +# Add unit tests +#----------------------------------------------------------------------------- + +set(_tests + usDebugOutputTest + usLDAPFilterTest + usModuleTest + usModuleResourceTest + usServiceFactoryTest + usServiceRegistryPerformanceTest + usServiceRegistryTest + usServiceTemplateTest + usServiceTrackerTest + usStaticModuleResourceTest + usStaticModuleTest +) + +if(US_BUILD_SHARED_LIBS) + list(APPEND _tests usServiceListenerTest usModuleManifestTest usSharedLibraryTest) + if(US_ENABLE_AUTOLOADING_SUPPORT) + list(APPEND _tests usModuleAutoLoadTest) + endif() +endif() + +set(_additional_srcs + usTestManager.cpp + usTestUtilModuleListener.cpp +) + +set(_test_driver ${PROJECT_NAME}TestDriver) +set(_test_sourcelist_extra_args ) +create_test_sourcelist(_srcs ${_test_driver}.cpp ${_tests} ${_test_sourcelist_extra_args}) + +usFunctionEmbedResources(_srcs EXECUTABLE_NAME ${_test_driver} FILES usTestResource.txt manifest.json) + +# Generate a custom "module init" file for the test driver executable +if(US_BUILD_SHARED_LIBS) + usFunctionGenerateExecutableInit(_srcs IDENTIFIER ${_test_driver}) +endif() + +add_executable(${_test_driver} ${_srcs} ${_additional_srcs}) +if(NOT US_BUILD_SHARED_LIBS) + target_link_libraries(${_test_driver} ${_us_test_module_libs}) +endif() +target_link_libraries(${_test_driver} ${US_LIBRARY_TARGET}) + +if(UNIX AND NOT APPLE) + target_link_libraries(${_test_driver} rt) +endif() + +# Register tests +foreach(_test ${_tests}) + add_test(NAME ${_test} COMMAND ${_test_driver} ${_test}) +endforeach() + +if(US_TEST_LABELS) + set_tests_properties(${_tests} PROPERTIES LABELS "${US_TEST_LABELS}") +endif() + +#----------------------------------------------------------------------------- +# Add dependencies for shared libraries +#----------------------------------------------------------------------------- + +if(US_BUILD_SHARED_LIBS) + foreach(_test_module ${_us_test_module_libs}) + add_dependencies(${_test_driver} ${_test_module}) + endforeach() +endif() diff --git a/test/manifest.json b/test/manifest.json new file mode 100644 index 0000000000..fb898a5477 --- /dev/null +++ b/test/manifest.json @@ -0,0 +1,3 @@ +{ + "module.version" : "0.1.0" +} diff --git a/test/modules/CMakeLists.txt b/test/modules/CMakeLists.txt new file mode 100644 index 0000000000..f303ee9753 --- /dev/null +++ b/test/modules/CMakeLists.txt @@ -0,0 +1,13 @@ +add_subdirectory(libA) +add_subdirectory(libA2) +add_subdirectory(libAL) +add_subdirectory(libAL2) +add_subdirectory(libBWithStatic) +add_subdirectory(libH) +add_subdirectory(libM) +add_subdirectory(libS) +add_subdirectory(libSL1) +add_subdirectory(libSL3) +add_subdirectory(libSL4) + +add_subdirectory(libRWithResources) diff --git a/test/modules/libA/CMakeLists.txt b/test/modules/libA/CMakeLists.txt new file mode 100644 index 0000000000..48211b0c66 --- /dev/null +++ b/test/modules/libA/CMakeLists.txt @@ -0,0 +1,2 @@ + +usFunctionCreateTestModule(TestModuleA usTestModuleA.cpp) diff --git a/test/modules/libA/usTestModuleA.cpp b/test/modules/libA/usTestModuleA.cpp new file mode 100644 index 0000000000..a654901ef2 --- /dev/null +++ b/test/modules/libA/usTestModuleA.cpp @@ -0,0 +1,77 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usTestModuleAService.h" + +#include +#include +#include + +US_BEGIN_NAMESPACE + +struct TestModuleA : public TestModuleAService +{ + + TestModuleA(ModuleContext* mc) + { + US_INFO << "Registering TestModuleAService"; + sr = mc->RegisterService(this); + } + + void Unregister() + { + if (sr) + { + sr.Unregister(); + sr = 0; + } + } + +private: + + ServiceRegistration sr; + +}; + +class TestModuleAActivator : public ModuleActivator +{ +public: + + TestModuleAActivator() : s(0) {} + ~TestModuleAActivator() { delete s; } + + void Load(ModuleContext* context) + { + s = new TestModuleA(context); + } + + void Unload(ModuleContext*) + { + } + +private: + + TestModuleA* s; +}; + +US_END_NAMESPACE + +US_EXPORT_MODULE_ACTIVATOR(TestModuleA, US_PREPEND_NAMESPACE(TestModuleAActivator)) diff --git a/test/modules/libA/usTestModuleAService.h b/test/modules/libA/usTestModuleAService.h new file mode 100644 index 0000000000..9ff99bb92e --- /dev/null +++ b/test/modules/libA/usTestModuleAService.h @@ -0,0 +1,40 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USTESTMODULEASERVICE_H +#define USTESTMODULEASERVICE_H + +#include +#include + +US_BEGIN_NAMESPACE + +struct TestModuleAService +{ + virtual ~TestModuleAService() {} +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleAService), "org.cppmicroservices.TestModuleAService") + +#endif // USTESTMODULEASERVICE_H diff --git a/test/modules/libA2/CMakeLists.txt b/test/modules/libA2/CMakeLists.txt new file mode 100644 index 0000000000..21968cba8c --- /dev/null +++ b/test/modules/libA2/CMakeLists.txt @@ -0,0 +1,2 @@ + +usFunctionCreateTestModule(TestModuleA2 usTestModuleA2.cpp) diff --git a/test/modules/libA2/usTestModuleA2.cpp b/test/modules/libA2/usTestModuleA2.cpp new file mode 100644 index 0000000000..d2d03adeeb --- /dev/null +++ b/test/modules/libA2/usTestModuleA2.cpp @@ -0,0 +1,76 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usTestModuleA2Service.h" + +#include +#include + +US_BEGIN_NAMESPACE + +struct TestModuleA2 : public TestModuleA2Service +{ + + TestModuleA2(ModuleContext* mc) + { + US_INFO << "Registering TestModuleA2Service"; + sr = mc->RegisterService(this); + } + + void Unregister() + { + if (sr) + { + sr.Unregister(); + } + } + +private: + + ServiceRegistration sr; +}; + +class TestModuleA2Activator : public ModuleActivator +{ +public: + + TestModuleA2Activator() : s(0) {} + + ~TestModuleA2Activator() { delete s; } + + void Load(ModuleContext* context) + { + s = new TestModuleA2(context); + } + + void Unload(ModuleContext* /*context*/) + { + s->Unregister(); + } + +private: + + TestModuleA2* s; +}; + +US_END_NAMESPACE + +US_EXPORT_MODULE_ACTIVATOR(TestModuleA2, US_PREPEND_NAMESPACE(TestModuleA2Activator)) diff --git a/test/modules/libA2/usTestModuleA2Service.h b/test/modules/libA2/usTestModuleA2Service.h new file mode 100644 index 0000000000..ce6c51a506 --- /dev/null +++ b/test/modules/libA2/usTestModuleA2Service.h @@ -0,0 +1,40 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USTESTMODULEA2SERVICE_H +#define USTESTMODULEA2SERVICE_H + +#include +#include + +US_BEGIN_NAMESPACE + +struct TestModuleA2Service +{ + virtual ~TestModuleA2Service() {} +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleA2Service), "org.us.TestModuleA2Service") + +#endif // USTESTMODULEA2SERVICE_H diff --git a/test/modules/libAL/CMakeLists.txt b/test/modules/libAL/CMakeLists.txt new file mode 100644 index 0000000000..224c6f09cb --- /dev/null +++ b/test/modules/libAL/CMakeLists.txt @@ -0,0 +1,4 @@ + +usFunctionCreateTestModule(TestModuleAL usTestModuleAL.cpp) + +add_subdirectory(libAL_1) diff --git a/test/modules/libAL/libAL_1/CMakeLists.txt b/test/modules/libAL/libAL_1/CMakeLists.txt new file mode 100644 index 0000000000..5db0e45894 --- /dev/null +++ b/test/modules/libAL/libAL_1/CMakeLists.txt @@ -0,0 +1,6 @@ + +foreach(_type ARCHIVE LIBRARY RUNTIME) + set(CMAKE_${_type}_OUTPUT_DIRECTORY ${CMAKE_${_type}_OUTPUT_DIRECTORY}/TestModuleAL) +endforeach() + +usFunctionCreateTestModule(TestModuleAL_1 usTestModuleAL_1.cpp) diff --git a/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp b/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp new file mode 100644 index 0000000000..dd15f10b16 --- /dev/null +++ b/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp @@ -0,0 +1,30 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +US_BEGIN_NAMESPACE + +struct US_ABI_EXPORT TestModuleAL_1_Dummy +{ +}; + +US_END_NAMESPACE diff --git a/test/modules/libAL/usTestModuleAL.cpp b/test/modules/libAL/usTestModuleAL.cpp new file mode 100644 index 0000000000..aaee431545 --- /dev/null +++ b/test/modules/libAL/usTestModuleAL.cpp @@ -0,0 +1,30 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +US_BEGIN_NAMESPACE + +struct TestModuleAL_Dummy +{ +}; + +US_END_NAMESPACE diff --git a/test/modules/libAL2/CMakeLists.txt b/test/modules/libAL2/CMakeLists.txt new file mode 100644 index 0000000000..8fefb1736d --- /dev/null +++ b/test/modules/libAL2/CMakeLists.txt @@ -0,0 +1,4 @@ + +usFunctionCreateTestModuleWithResources(TestModuleAL2 SOURCES usTestModuleAL2.cpp RESOURCES manifest.json) + +add_subdirectory(libAL2_1) diff --git a/test/modules/libAL2/libAL2_1/CMakeLists.txt b/test/modules/libAL2/libAL2_1/CMakeLists.txt new file mode 100644 index 0000000000..7c65e41ee5 --- /dev/null +++ b/test/modules/libAL2/libAL2_1/CMakeLists.txt @@ -0,0 +1,6 @@ + +foreach(_type ARCHIVE LIBRARY RUNTIME) + set(CMAKE_${_type}_OUTPUT_DIRECTORY ${CMAKE_${_type}_OUTPUT_DIRECTORY}/autoload_al2) +endforeach() + +usFunctionCreateTestModule(TestModuleAL2_1 usTestModuleAL2_1.cpp) diff --git a/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp b/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp new file mode 100644 index 0000000000..b81eb15a35 --- /dev/null +++ b/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp @@ -0,0 +1,30 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +US_BEGIN_NAMESPACE + +struct US_ABI_EXPORT TestModuleAL2_1_Dummy +{ +}; + +US_END_NAMESPACE diff --git a/test/modules/libAL2/resources/manifest.json b/test/modules/libAL2/resources/manifest.json new file mode 100644 index 0000000000..4772f1f57c --- /dev/null +++ b/test/modules/libAL2/resources/manifest.json @@ -0,0 +1,3 @@ +{ + "module.autoload_dir" : "autoload_al2" +} diff --git a/test/modules/libAL2/usTestModuleAL2.cpp b/test/modules/libAL2/usTestModuleAL2.cpp new file mode 100644 index 0000000000..0388565838 --- /dev/null +++ b/test/modules/libAL2/usTestModuleAL2.cpp @@ -0,0 +1,30 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +US_BEGIN_NAMESPACE + +struct TestModuleAL2_Dummy +{ +}; + +US_END_NAMESPACE diff --git a/test/modules/libBWithStatic/CMakeLists.txt b/test/modules/libBWithStatic/CMakeLists.txt new file mode 100644 index 0000000000..30b9cf7be6 --- /dev/null +++ b/test/modules/libBWithStatic/CMakeLists.txt @@ -0,0 +1,12 @@ + +usFunctionCreateTestModuleWithResources(TestModuleB + SOURCES usTestModuleB.cpp + RESOURCES dynamic.txt res.txt) + +set(BUILD_SHARED_LIBS 0) +usFunctionCreateTestModuleWithResources(TestModuleImportedByB + SOURCES usTestModuleImportedByB.cpp + RESOURCES static.txt res.txt + RESOURCES_ROOT resources_static) + +target_link_libraries(TestModuleB TestModuleImportedByB) diff --git a/test/modules/libBWithStatic/resources/dynamic.txt b/test/modules/libBWithStatic/resources/dynamic.txt new file mode 100644 index 0000000000..380a834a99 --- /dev/null +++ b/test/modules/libBWithStatic/resources/dynamic.txt @@ -0,0 +1 @@ +dynamic diff --git a/test/modules/libBWithStatic/resources/res.txt b/test/modules/libBWithStatic/resources/res.txt new file mode 100644 index 0000000000..21f035c230 --- /dev/null +++ b/test/modules/libBWithStatic/resources/res.txt @@ -0,0 +1 @@ +dynamic resource diff --git a/test/modules/libBWithStatic/resources_static/res.txt b/test/modules/libBWithStatic/resources_static/res.txt new file mode 100644 index 0000000000..68f9caa9f2 --- /dev/null +++ b/test/modules/libBWithStatic/resources_static/res.txt @@ -0,0 +1 @@ +static resource diff --git a/test/modules/libBWithStatic/resources_static/static.txt b/test/modules/libBWithStatic/resources_static/static.txt new file mode 100644 index 0000000000..7b4d4ba2e6 --- /dev/null +++ b/test/modules/libBWithStatic/resources_static/static.txt @@ -0,0 +1 @@ +static diff --git a/test/modules/libBWithStatic/usTestModuleB.cpp b/test/modules/libBWithStatic/usTestModuleB.cpp new file mode 100644 index 0000000000..7111c3164a --- /dev/null +++ b/test/modules/libBWithStatic/usTestModuleB.cpp @@ -0,0 +1,71 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usTestModuleBService.h" + +#include +#include +#include +#include + +US_BEGIN_NAMESPACE + +struct TestModuleB : public TestModuleBService +{ + + TestModuleB(ModuleContext* mc) + { + US_INFO << "Registering TestModuleBService"; + mc->RegisterService(this); + } + +}; + +class TestModuleBActivator : public ModuleActivator +{ +public: + + TestModuleBActivator() : s(0) {} + ~TestModuleBActivator() { delete s; } + + void Load(ModuleContext* context) + { + s = new TestModuleB(context); + } + + void Unload(ModuleContext*) + { + } + +private: + + TestModuleB* s; +}; + +US_END_NAMESPACE + +US_EXPORT_MODULE_ACTIVATOR(TestModuleB, US_PREPEND_NAMESPACE(TestModuleBActivator)) + + +US_IMPORT_MODULE(TestModuleImportedByB) +US_IMPORT_MODULE_RESOURCES(TestModuleImportedByB) + +US_LOAD_IMPORTED_MODULES(TestModuleB, TestModuleImportedByB) diff --git a/test/modules/libBWithStatic/usTestModuleBService.h b/test/modules/libBWithStatic/usTestModuleBService.h new file mode 100644 index 0000000000..ababe97398 --- /dev/null +++ b/test/modules/libBWithStatic/usTestModuleBService.h @@ -0,0 +1,40 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USTESTMODULEBSERVICE_H +#define USTESTMODULEBSERVICE_H + +#include +#include + +US_BEGIN_NAMESPACE + +struct TestModuleBService +{ + virtual ~TestModuleBService() {} +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleBService), "org.cppmicroservices.TestModuleBService") + +#endif // USTESTMODULEASERVICE_H diff --git a/test/modules/libBWithStatic/usTestModuleImportedByB.cpp b/test/modules/libBWithStatic/usTestModuleImportedByB.cpp new file mode 100644 index 0000000000..8c6008e506 --- /dev/null +++ b/test/modules/libBWithStatic/usTestModuleImportedByB.cpp @@ -0,0 +1,65 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usTestModuleBService.h" + +#include +#include +#include + + +US_BEGIN_NAMESPACE + +struct TestModuleImportedByB : public TestModuleBService +{ + + TestModuleImportedByB(ModuleContext* mc) + { + US_INFO << "Registering TestModuleImportedByB"; + mc->RegisterService(this); + } + +}; + +class TestModuleImportedByBActivator : public ModuleActivator +{ +public: + + TestModuleImportedByBActivator() : s(0) {} + ~TestModuleImportedByBActivator() { delete s; } + + void Load(ModuleContext* context) + { + s = new TestModuleImportedByB(context); + } + + void Unload(ModuleContext*) + { + } + +private: + + TestModuleImportedByB* s; +}; + +US_END_NAMESPACE + +US_EXPORT_MODULE_ACTIVATOR(TestModuleImportedByB, US_PREPEND_NAMESPACE(TestModuleImportedByBActivator)) diff --git a/test/modules/libH/CMakeLists.txt b/test/modules/libH/CMakeLists.txt new file mode 100644 index 0000000000..0aa0176b5d --- /dev/null +++ b/test/modules/libH/CMakeLists.txt @@ -0,0 +1,2 @@ + +usFunctionCreateTestModule(TestModuleH usTestModuleH.cpp) diff --git a/test/modules/libH/usTestModuleH.cpp b/test/modules/libH/usTestModuleH.cpp new file mode 100644 index 0000000000..2352c039a4 --- /dev/null +++ b/test/modules/libH/usTestModuleH.cpp @@ -0,0 +1,147 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#include +#include +#include +#include +#include +#include + +#include + +US_BEGIN_NAMESPACE + +struct TestModuleH +{ + virtual ~TestModuleH() {} +}; + +struct TestModuleH2 +{ + virtual ~TestModuleH2() {} +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleH), "org.cppmicroservices.TestModuleH") +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleH2), "org.cppmicroservices.TestModuleH2") + +US_BEGIN_NAMESPACE + +class TestProduct : public TestModuleH +{ + Module* caller; + +public: + + TestProduct(Module* caller) + : caller(caller) + {} + +}; + +class TestProduct2 : public TestProduct, public TestModuleH2 +{ +public: + + TestProduct2(Module* caller) + : TestProduct(caller) + {} + +}; + +class TestModuleHPrototypeServiceFactory : public PrototypeServiceFactory +{ + std::map > fcbind; // Map calling module with implementation + +public: + + InterfaceMap GetService(Module* caller, const ServiceRegistrationBase& /*sReg*/) + { + std::cout << "GetService (prototype) in H" << std::endl; + TestProduct2* product = new TestProduct2(caller); + fcbind[caller->GetModuleId()].push_back(product); + return MakeInterfaceMap(product); + } + + void UngetService(Module* caller, const ServiceRegistrationBase& /*sReg*/, const InterfaceMap& service) + { + TestProduct2* product = dynamic_cast(ExtractInterface(service)); + delete product; + fcbind[caller->GetModuleId()].remove(product); + } + +}; + + +class TestModuleHActivator : public ModuleActivator, public ServiceFactory +{ + std::string thisServiceName; + ServiceRegistration factoryService; + ServiceRegistration prototypeFactoryService; + ModuleContext* mc; + + std::map fcbind; // Map calling module with implementation + TestModuleHPrototypeServiceFactory prototypeFactory; + +public: + + TestModuleHActivator() + : thisServiceName(us_service_interface_iid()) + , mc(NULL) + {} + + void Load(ModuleContext* mc) + { + std::cout << "start in H" << std::endl; + this->mc = mc; + factoryService = mc->RegisterService(this); + prototypeFactoryService = mc->RegisterService(static_cast(&prototypeFactory)); + } + + void Unload(ModuleContext* /*mc*/) + { + factoryService.Unregister(); + } + + InterfaceMap GetService(Module* caller, const ServiceRegistrationBase& /*sReg*/) + { + std::cout << "GetService in H" << std::endl; + TestProduct* product = new TestProduct(caller); + fcbind.insert(std::make_pair(caller->GetModuleId(), product)); + return MakeInterfaceMap(product); + } + + void UngetService(Module* caller, const ServiceRegistrationBase& /*sReg*/, const InterfaceMap& service) + { + TestModuleH* product = ExtractInterface(service); + delete product; + fcbind.erase(caller->GetModuleId()); + } + +}; + + +US_END_NAMESPACE + +US_EXPORT_MODULE_ACTIVATOR(TestModuleH, us::TestModuleHActivator) diff --git a/test/modules/libM/CMakeLists.txt b/test/modules/libM/CMakeLists.txt new file mode 100644 index 0000000000..c96b103203 --- /dev/null +++ b/test/modules/libM/CMakeLists.txt @@ -0,0 +1,8 @@ + +set(resource_files + manifest.json +) + +usFunctionCreateTestModuleWithResources(TestModuleM + SOURCES usTestModuleM.cpp + RESOURCES ${resource_files}) diff --git a/test/modules/libM/resources/manifest.json b/test/modules/libM/resources/manifest.json new file mode 100644 index 0000000000..c2b05e4708 --- /dev/null +++ b/test/modules/libM/resources/manifest.json @@ -0,0 +1,16 @@ +{ + "module.name": "TestModuleM Module", + "module.description": "My Module description", + "module.version": "1.0.0", + "number": 5, + "vector": [ + "first", + 2, + "third" + ], + "map": { + "string": "hi", + "number": 4, + "list": [ "a", "b" ] + } +} diff --git a/test/modules/libM/usTestModuleM.cpp b/test/modules/libM/usTestModuleM.cpp new file mode 100644 index 0000000000..934056c84b --- /dev/null +++ b/test/modules/libM/usTestModuleM.cpp @@ -0,0 +1,43 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#include + +US_BEGIN_NAMESPACE + +class TestModuleMActivator : public ModuleActivator +{ +public: + + void Load(ModuleContext*) + { + } + + void Unload(ModuleContext*) + { + } + +}; + +US_END_NAMESPACE + +US_EXPORT_MODULE_ACTIVATOR(TestModuleM, US_PREPEND_NAMESPACE(TestModuleMActivator)) diff --git a/test/modules/libRWithResources/CMakeLists.txt b/test/modules/libRWithResources/CMakeLists.txt new file mode 100644 index 0000000000..e5ff2c8109 --- /dev/null +++ b/test/modules/libRWithResources/CMakeLists.txt @@ -0,0 +1,13 @@ + +set(resource_files + icons/compressable.bmp + icons/cppmicroservices.png + icons/readme.txt + foo.txt + special_chars.dummy.txt + test.xml +) + +usFunctionCreateTestModuleWithResources(TestModuleR + SOURCES usTestModuleR.cpp + RESOURCES ${resource_files}) diff --git a/test/modules/libRWithResources/resources/foo.txt b/test/modules/libRWithResources/resources/foo.txt new file mode 100644 index 0000000000..f004091c6b --- /dev/null +++ b/test/modules/libRWithResources/resources/foo.txt @@ -0,0 +1,3 @@ +foo and +bar + diff --git a/test/modules/libRWithResources/resources/icons/compressable.bmp b/test/modules/libRWithResources/resources/icons/compressable.bmp new file mode 100644 index 0000000000..96c6caba90 Binary files /dev/null and b/test/modules/libRWithResources/resources/icons/compressable.bmp differ diff --git a/test/modules/libRWithResources/resources/icons/cppmicroservices.png b/test/modules/libRWithResources/resources/icons/cppmicroservices.png new file mode 100644 index 0000000000..e115492256 Binary files /dev/null and b/test/modules/libRWithResources/resources/icons/cppmicroservices.png differ diff --git a/test/modules/libRWithResources/resources/icons/readme.txt b/test/modules/libRWithResources/resources/icons/readme.txt new file mode 100644 index 0000000000..30af5fe09c --- /dev/null +++ b/test/modules/libRWithResources/resources/icons/readme.txt @@ -0,0 +1 @@ +icons diff --git a/test/modules/libRWithResources/resources/special_chars.dummy.txt b/test/modules/libRWithResources/resources/special_chars.dummy.txt new file mode 100644 index 0000000000..47bfa90dd0 --- /dev/null +++ b/test/modules/libRWithResources/resources/special_chars.dummy.txt @@ -0,0 +1,2 @@ +German Füße (feet) +French garçon de café (waiter) diff --git a/test/modules/libRWithResources/resources/test.xml b/test/modules/libRWithResources/resources/test.xml new file mode 100644 index 0000000000..bc90bc6ca9 --- /dev/null +++ b/test/modules/libRWithResources/resources/test.xml @@ -0,0 +1,3 @@ + + +hi diff --git a/test/modules/libRWithResources/usTestModuleR.cpp b/test/modules/libRWithResources/usTestModuleR.cpp new file mode 100644 index 0000000000..be8c0291ca --- /dev/null +++ b/test/modules/libRWithResources/usTestModuleR.cpp @@ -0,0 +1,43 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#include + +US_BEGIN_NAMESPACE + +class TestModuleRActivator : public ModuleActivator +{ +public: + + void Load(ModuleContext*) + { + } + + void Unload(ModuleContext*) + { + } + +}; + +US_END_NAMESPACE + +US_EXPORT_MODULE_ACTIVATOR(TestModuleR, US_PREPEND_NAMESPACE(TestModuleRActivator)) diff --git a/test/modules/libS/CMakeLists.txt b/test/modules/libS/CMakeLists.txt new file mode 100644 index 0000000000..cb4ef91bb3 --- /dev/null +++ b/test/modules/libS/CMakeLists.txt @@ -0,0 +1,2 @@ + +usFunctionCreateTestModule(TestModuleS usTestModuleS.cpp) diff --git a/test/modules/libS/usTestModuleS.cpp b/test/modules/libS/usTestModuleS.cpp new file mode 100644 index 0000000000..b25ead2668 --- /dev/null +++ b/test/modules/libS/usTestModuleS.cpp @@ -0,0 +1,143 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "../../usServiceControlInterface.h" + +#include "usTestModuleSService0.h" +#include "usTestModuleSService1.h" +#include "usTestModuleSService2.h" +#include "usTestModuleSService3.h" + +#include +#include +#include +#include + + +US_BEGIN_NAMESPACE + +class TestModuleS : public ServiceControlInterface, + public TestModuleSService0, + public TestModuleSService1, + public TestModuleSService2, + public TestModuleSService3 +{ + +public: + + TestModuleS(ModuleContext* mc) + : mc(mc) + { + for(int i = 0; i <= 3; ++i) + { + servregs.push_back(ServiceRegistrationU()); + } + sreg = mc->RegisterService(this); + sciReg = mc->RegisterService(this); + } + + virtual const char* GetNameOfClass() const + { + return "TestModuleS"; + } + + void ServiceControl(int offset, const std::string& operation, int ranking) + { + if (0 <= offset && offset <= 3) + { + if (operation == "register") + { + if (!servregs[offset]) + { + std::stringstream servicename; + servicename << SERVICE << offset; + InterfaceMap ifm; + ifm.insert(std::make_pair(servicename.str(), static_cast(this))); + ServiceProperties props; + props.insert(std::make_pair(ServiceConstants::SERVICE_RANKING(), Any(ranking))); + servregs[offset] = mc->RegisterService(ifm, props); + } + } + if (operation == "unregister") + { + if (servregs[offset]) + { + ServiceRegistrationU sr1 = servregs[offset]; + sr1.Unregister(); + servregs[offset] = 0; + } + } + } + } + + void Unregister() + { + if (sreg) + { + sreg.Unregister(); + } + if (sciReg) + { + sciReg.Unregister(); + } + } + +private: + + static const std::string SERVICE; // = "org.cppmicroservices.TestModuleSService" + + ModuleContext* mc; + std::vector servregs; + ServiceRegistration sreg; + ServiceRegistration sciReg; +}; + +const std::string TestModuleS::SERVICE = "org.cppmicroservices.TestModuleSService"; + +class TestModuleSActivator : public ModuleActivator +{ + +public: + + TestModuleSActivator() : s(0) {} + ~TestModuleSActivator() { delete s; } + + void Load(ModuleContext* context) + { + s = new TestModuleS(context); + } + + void Unload(ModuleContext* /*context*/) + { + #ifndef US_BUILD_SHARED_LIBS + s->Unregister(); + #endif + } + +private: + + TestModuleS* s; + +}; + +US_END_NAMESPACE + +US_EXPORT_MODULE_ACTIVATOR(TestModuleS, US_PREPEND_NAMESPACE(TestModuleSActivator)) diff --git a/test/modules/libS/usTestModuleSService0.h b/test/modules/libS/usTestModuleSService0.h new file mode 100644 index 0000000000..5208c16775 --- /dev/null +++ b/test/modules/libS/usTestModuleSService0.h @@ -0,0 +1,39 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USTESTMODULESSERVICE0_H +#define USTESTMODULESSERVICE0_H + +#include + +US_BEGIN_NAMESPACE + +struct TestModuleSService0 +{ + virtual ~TestModuleSService0() {} +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleSService0), "org.cppmicroservices.TestModuleSService0") + +#endif // USTESTMODULESSERVICE0_H diff --git a/test/modules/libS/usTestModuleSService1.h b/test/modules/libS/usTestModuleSService1.h new file mode 100644 index 0000000000..2fadbe121c --- /dev/null +++ b/test/modules/libS/usTestModuleSService1.h @@ -0,0 +1,39 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USTESTMODULESSERVICE1_H +#define USTESTMODULESSERVICE1_H + +#include + +US_BEGIN_NAMESPACE + +struct TestModuleSService1 +{ + virtual ~TestModuleSService1() {} +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleSService1), "org.cppmicroservices.TestModuleSService1") + +#endif // USTESTMODULESSERVICE1_H diff --git a/test/modules/libS/usTestModuleSService2.h b/test/modules/libS/usTestModuleSService2.h new file mode 100644 index 0000000000..901bd463a0 --- /dev/null +++ b/test/modules/libS/usTestModuleSService2.h @@ -0,0 +1,39 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USTESTMODULESSERVICE2_H +#define USTESTMODULESSERVICE2_H + +#include + +US_BEGIN_NAMESPACE + +struct TestModuleSService2 +{ + virtual ~TestModuleSService2() {} +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleSService2), "org.cppmicroservices.TestModuleSService2") + +#endif // USTESTMODULESSERVICE0_H diff --git a/test/modules/libS/usTestModuleSService3.h b/test/modules/libS/usTestModuleSService3.h new file mode 100644 index 0000000000..57b0230e05 --- /dev/null +++ b/test/modules/libS/usTestModuleSService3.h @@ -0,0 +1,39 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USTESTMODULESSERVICE3_H +#define USTESTMODULESSERVICE3_H + +#include + +US_BEGIN_NAMESPACE + +struct TestModuleSService3 +{ + virtual ~TestModuleSService3() {} +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleSService3), "org.cppmicroservices.TestModuleSService3") + +#endif // USTESTMODULESSERVICE0_H diff --git a/test/modules/libSL1/CMakeLists.txt b/test/modules/libSL1/CMakeLists.txt new file mode 100644 index 0000000000..29d6d614c3 --- /dev/null +++ b/test/modules/libSL1/CMakeLists.txt @@ -0,0 +1,2 @@ + +usFunctionCreateTestModule(TestModuleSL1 usActivatorSL1.cpp) diff --git a/test/modules/libSL1/usActivatorSL1.cpp b/test/modules/libSL1/usActivatorSL1.cpp new file mode 100644 index 0000000000..f7070ce255 --- /dev/null +++ b/test/modules/libSL1/usActivatorSL1.cpp @@ -0,0 +1,106 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#include +#include + +#include +#include + +#include "usFooService.h" + +US_BEGIN_NAMESPACE + +class ActivatorSL1 : + public ModuleActivator, public ModulePropsInterface, + public ServiceTrackerCustomizer +{ + +public: + + ActivatorSL1() + : tracker(0), context(0) + { + + } + + ~ActivatorSL1() + { + delete tracker; + } + + void Load(ModuleContext* context) + { + this->context = context; + + InterfaceMap im = MakeInterfaceMap(this); + im.insert(std::make_pair(std::string("ActivatorSL1"), this)); + sr = context->RegisterService(im); + + delete tracker; + tracker = new FooTracker(context, this); + tracker->Open(); + } + + void Unload(ModuleContext* /*context*/) + { + tracker->Close(); + } + + const Properties& GetProperties() const + { + return props; + } + + FooService* AddingService(const ServiceReferenceT& reference) + { + props["serviceAdded"] = true; + + FooService* fooService = context->GetService(reference); + fooService->foo(); + return fooService; + } + + void ModifiedService(const ServiceReferenceT& /*reference*/, FooService* /*service*/) + {} + + void RemovedService(const ServiceReferenceT& /*reference*/, FooService* /*service*/) + { + props["serviceRemoved"] = true; + } + +private: + + ModulePropsInterface::Properties props; + + ServiceRegistrationU sr; + + typedef ServiceTracker FooTracker; + + FooTracker* tracker; + ModuleContext* context; + +}; // ActivatorSL1 + +US_END_NAMESPACE + +US_EXPORT_MODULE_ACTIVATOR(TestModuleSL1, US_PREPEND_NAMESPACE(ActivatorSL1)) diff --git a/test/modules/libSL1/usFooService.h b/test/modules/libSL1/usFooService.h new file mode 100644 index 0000000000..461cf12af0 --- /dev/null +++ b/test/modules/libSL1/usFooService.h @@ -0,0 +1,40 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USFOOSERVICE_H +#define USFOOSERVICE_H + +#include + +US_BEGIN_NAMESPACE + +struct FooService +{ + virtual ~FooService() {} + virtual void foo() = 0; +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(FooService), "org.us.testing.FooService") + +#endif // USFOOSERVICE_H diff --git a/test/modules/libSL3/CMakeLists.txt b/test/modules/libSL3/CMakeLists.txt new file mode 100644 index 0000000000..a342806dd6 --- /dev/null +++ b/test/modules/libSL3/CMakeLists.txt @@ -0,0 +1,4 @@ + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../libSL1) + +usFunctionCreateTestModule(TestModuleSL3 usActivatorSL3.cpp) diff --git a/test/modules/libSL3/usActivatorSL3.cpp b/test/modules/libSL3/usActivatorSL3.cpp new file mode 100644 index 0000000000..ea5e9a8706 --- /dev/null +++ b/test/modules/libSL3/usActivatorSL3.cpp @@ -0,0 +1,100 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include +#include +#include + +US_BEGIN_NAMESPACE + +class ActivatorSL3 : + public ModuleActivator, public ModulePropsInterface, + public ServiceTrackerCustomizer +{ + +public: + + ActivatorSL3() : tracker(0), context(0) {} + + ~ActivatorSL3() + { delete tracker; } + + void Load(ModuleContext* context) + { + this->context = context; + + InterfaceMap im = MakeInterfaceMap(this); + im.insert(std::make_pair(std::string("ActivatorSL3"), this)); + sr = context->RegisterService(im); + delete tracker; + tracker = new FooTracker(context, this); + tracker->Open(); + } + + void Unload(ModuleContext* /*context*/) + { + tracker->Close(); + } + + const ModulePropsInterface::Properties& GetProperties() const + { + return props; + } + + FooService* AddingService(const ServiceReferenceT& reference) + { + props["serviceAdded"] = true; + US_INFO << "SL3: Adding reference =" << reference; + + FooService* fooService = context->GetService(reference); + fooService->foo(); + return fooService; + } + + void ModifiedService(const ServiceReferenceT& /*reference*/, FooService* /*service*/) + { + + } + + void RemovedService(const ServiceReferenceT& reference, FooService* /*service*/) + { + props["serviceRemoved"] = true; + US_INFO << "SL3: Removing reference =" << reference; + } + +private: + + typedef ServiceTracker FooTracker; + FooTracker* tracker; + ModuleContext* context; + + ServiceRegistrationU sr; + + ModulePropsInterface::Properties props; + +}; + +US_END_NAMESPACE + +US_EXPORT_MODULE_ACTIVATOR(TestModuleSL3, US_PREPEND_NAMESPACE(ActivatorSL3)) diff --git a/test/modules/libSL4/CMakeLists.txt b/test/modules/libSL4/CMakeLists.txt new file mode 100644 index 0000000000..e81e7e6428 --- /dev/null +++ b/test/modules/libSL4/CMakeLists.txt @@ -0,0 +1,4 @@ + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../libSL1) + +usFunctionCreateTestModule(TestModuleSL4 usActivatorSL4.cpp) diff --git a/test/modules/libSL4/usActivatorSL4.cpp b/test/modules/libSL4/usActivatorSL4.cpp new file mode 100644 index 0000000000..4f0aebb814 --- /dev/null +++ b/test/modules/libSL4/usActivatorSL4.cpp @@ -0,0 +1,65 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#include +#include +#include +#include + +#include + +US_BEGIN_NAMESPACE + +class ActivatorSL4 : + public ModuleActivator, public FooService +{ + +public: + + ~ActivatorSL4() + { + + } + + void foo() + { + US_INFO << "TestModuleSL4: Doing foo"; + } + + void Load(ModuleContext* context) + { + sr = context->RegisterService(this); + US_INFO << "TestModuleSL4: Registered " << sr; + } + + void Unload(ModuleContext* /*context*/) + { + } + +private: + + ServiceRegistration sr; +}; + +US_END_NAMESPACE + +US_EXPORT_MODULE_ACTIVATOR(TestModuleSL4, US_PREPEND_NAMESPACE(ActivatorSL4)) diff --git a/test/usDebugOutputTest.cpp b/test/usDebugOutputTest.cpp new file mode 100644 index 0000000000..3fcc643854 --- /dev/null +++ b/test/usDebugOutputTest.cpp @@ -0,0 +1,99 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +#include "usTestingMacros.h" + +US_USE_NAMESPACE + +static int lastMsgType = -1; +static std::string lastMsg; + +void handleMessages(MsgType type, const char* msg) +{ + lastMsgType = type; + lastMsg.assign(msg); +} + +void resetLastMsg() +{ + lastMsgType = -1; + lastMsg.clear(); +} + +int usDebugOutputTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("DebugOutputTest"); + + // Use the default message handler + { + US_DEBUG << "Msg"; + US_DEBUG(false) << "Msg"; + US_INFO << "Msg"; + US_INFO(false) << "Msg"; + US_WARN << "Msg"; + US_WARN(false) << "Msg"; + } + US_TEST_CONDITION(lastMsg.empty(), "Testing default message handler"); + + resetLastMsg(); + + installMsgHandler(handleMessages); + { + US_DEBUG << "Msg"; + } +#if !defined(US_ENABLE_DEBUG_OUTPUT) + US_TEST_CONDITION(lastMsgType == -1 && lastMsg.empty(), "Testing suppressed debug message") +#else + US_TEST_CONDITION(lastMsgType == 0 && lastMsg.find("Msg") != std::string::npos, "Testing debug message") +#endif + resetLastMsg(); + + { + US_DEBUG(false) << "No msg"; + } + US_TEST_CONDITION(lastMsgType == -1 && lastMsg.empty(), "Testing disabled debug message") + resetLastMsg(); + + { + US_INFO << "Info msg"; + } + US_TEST_CONDITION(lastMsgType == 1 && lastMsg.find("Info msg") != std::string::npos, "Testing informational message") + resetLastMsg(); + + { + US_WARN << "Warn msg"; + } + US_TEST_CONDITION(lastMsgType == 2 && lastMsg.find("Warn msg") != std::string::npos, "Testing warning message") + resetLastMsg(); + + // We cannot test US_ERROR since it will call abort(). + + installMsgHandler(0); + + { + US_INFO << "Info msg"; + } + US_TEST_CONDITION(lastMsgType == -1 && lastMsg.empty(), "Testing message handler reset") + + US_TEST_END() +} diff --git a/test/usLDAPFilterTest.cpp b/test/usLDAPFilterTest.cpp new file mode 100644 index 0000000000..f81a4f3bc7 --- /dev/null +++ b/test/usLDAPFilterTest.cpp @@ -0,0 +1,149 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +#include "usTestingMacros.h" + +#include + +US_USE_NAMESPACE + +int TestParsing() +{ + // WELL FORMED Expr + try + { + US_TEST_OUTPUT(<< "Parsing (cn=Babs Jensen)") + LDAPFilter ldap( "(cn=Babs Jensen)" ); + US_TEST_OUTPUT(<< "Parsing (!(cn=Tim Howes))") + ldap = LDAPFilter( "(!(cn=Tim Howes))" ); + US_TEST_OUTPUT(<< "Parsing " << std::string("(&(") + ServiceConstants::OBJECTCLASS() + "=Person)(|(sn=Jensen)(cn=Babs J*)))") + ldap = LDAPFilter( std::string("(&(") + ServiceConstants::OBJECTCLASS() + "=Person)(|(sn=Jensen)(cn=Babs J*)))" ); + US_TEST_OUTPUT(<< "Parsing (o=univ*of*mich*)") + ldap = LDAPFilter( "(o=univ*of*mich*)" ); + } + catch (const std::invalid_argument& e) + { + US_TEST_OUTPUT(<< e.what()); + return EXIT_FAILURE; + } + + + // MALFORMED Expr + try + { + US_TEST_OUTPUT( << "Parsing malformed expr: cn=Babs Jensen)") + LDAPFilter ldap( "cn=Babs Jensen)" ); + return EXIT_FAILURE; + } + catch (const std::invalid_argument&) + { + } + + return EXIT_SUCCESS; +} + + +int TestEvaluate() +{ + // EVALUATE + try + { + LDAPFilter ldap( "(Cn=Babs Jensen)" ); + ServiceProperties props; + bool eval = false; + + // Several values + props["cn"] = std::string("Babs Jensen"); + props["unused"] = std::string("Jansen"); + US_TEST_OUTPUT(<< "Evaluating expr: " << ldap.ToString()) + eval = ldap.Match(props); + if (!eval) + { + return EXIT_FAILURE; + } + + // WILDCARD + ldap = LDAPFilter( "(cn=Babs *)" ); + props.clear(); + props["cn"] = std::string("Babs Jensen"); + US_TEST_OUTPUT(<< "Evaluating wildcard expr: " << ldap.ToString()) + eval = ldap.Match(props); + if ( !eval ) + { + return EXIT_FAILURE; + } + + // NOT FOUND + ldap = LDAPFilter( "(cn=Babs *)" ); + props.clear(); + props["unused"] = std::string("New"); + US_TEST_OUTPUT(<< "Expr not found test: " << ldap.ToString()) + eval = ldap.Match(props); + if ( eval ) + { + return EXIT_FAILURE; + } + + // std::vector with integer values + ldap = LDAPFilter( " ( |(cn=Babs *)(sn=1) )" ); + props.clear(); + std::vector list; + list.push_back(std::string("Babs Jensen")); + list.push_back(std::string("1")); + props["sn"] = list; + US_TEST_OUTPUT(<< "Evaluating vector expr: " << ldap.ToString()) + eval = ldap.Match(props); + if (!eval) + { + return EXIT_FAILURE; + } + + // wrong case + ldap = LDAPFilter( "(cN=Babs *)" ); + props.clear(); + props["cn"] = std::string("Babs Jensen"); + US_TEST_OUTPUT(<< "Evaluating case sensitive expr: " << ldap.ToString()) + eval = ldap.MatchCase(props); + if (eval) + { + return EXIT_FAILURE; + } + } + catch (const std::invalid_argument& e) + { + US_TEST_OUTPUT( << e.what() ) + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} + +int usLDAPFilterTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("LDAPFilterTest"); + + US_TEST_CONDITION(TestParsing() == EXIT_SUCCESS, "Parsing LDAP expressions: ") + US_TEST_CONDITION(TestEvaluate() == EXIT_SUCCESS, "Evaluating LDAP expressions: ") + + US_TEST_END() +} diff --git a/test/usModuleAutoLoadTest.cpp b/test/usModuleAutoLoadTest.cpp new file mode 100644 index 0000000000..db5dae1a76 --- /dev/null +++ b/test/usModuleAutoLoadTest.cpp @@ -0,0 +1,176 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "usTestUtilModuleListener.h" +#include "usTestingMacros.h" + +#include + +US_USE_NAMESPACE + +namespace { + +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + +void testDefaultAutoLoadPath(bool autoLoadEnabled) +{ + ModuleContext* mc = GetModuleContext(); + assert(mc); + TestModuleListener listener; + + try + { + mc->AddModuleListener(&listener, &TestModuleListener::ModuleChanged); + } + catch (const std::logic_error& ise) + { + US_TEST_OUTPUT( << "module listener registration failed " << ise.what() ); + throw; + } + + SharedLibrary libAL(LIB_PATH, "TestModuleAL"); + + try + { + libAL.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) + } + + Module* moduleAL = ModuleRegistry::GetModule("TestModuleAL Module"); + US_TEST_CONDITION_REQUIRED(moduleAL != NULL, "Test for existing module TestModuleAL") + + US_TEST_CONDITION(moduleAL->GetName() == "TestModuleAL Module", "Test module name") + + // check the listeners for events + std::vector pEvts; + pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleAL)); + + Module* moduleAL_1 = ModuleRegistry::GetModule("TestModuleAL_1 Module"); + if (autoLoadEnabled) + { + US_TEST_CONDITION_REQUIRED(moduleAL_1 != NULL, "Test for existing auto-loaded module TestModuleAL_1") + US_TEST_CONDITION(moduleAL_1->GetName() == "TestModuleAL_1 Module", "Test module name") + + pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleAL_1)); + pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleAL_1)); + } + else + { + US_TEST_CONDITION_REQUIRED(moduleAL_1 == NULL, "Test for non-existing auto-loaded module TestModuleAL_1") + } + + pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleAL)); + + US_TEST_CONDITION(listener.CheckListenerEvents(pEvts), "Test for unexpected events"); + + mc->RemoveModuleListener(&listener, &TestModuleListener::ModuleChanged); + + libAL.Unload(); +} + +void testCustomAutoLoadPath() +{ + ModuleContext* mc = GetModuleContext(); + assert(mc); + TestModuleListener listener; + + try + { + mc->AddModuleListener(&listener, &TestModuleListener::ModuleChanged); + } + catch (const std::logic_error& ise) + { + US_TEST_OUTPUT( << "module listener registration failed " << ise.what() ); + throw; + } + + SharedLibrary libAL2(LIB_PATH, "TestModuleAL2"); + + try + { + libAL2.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) + } + + Module* moduleAL2 = ModuleRegistry::GetModule("TestModuleAL2 Module"); + US_TEST_CONDITION_REQUIRED(moduleAL2 != NULL, "Test for existing module TestModuleAL2") + + US_TEST_CONDITION(moduleAL2->GetName() == "TestModuleAL2 Module", "Test module name") + + // check the listeners for events + std::vector pEvts; + pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleAL2)); + + Module* moduleAL2_1 = ModuleRegistry::GetModule("TestModuleAL2_1 Module"); +#ifdef US_ENABLE_AUTOLOADING_SUPPORT + US_TEST_CONDITION_REQUIRED(moduleAL2_1 != NULL, "Test for existing auto-loaded module TestModuleAL2_1") + US_TEST_CONDITION(moduleAL2_1->GetName() == "TestModuleAL2_1 Module", "Test module name") + + pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleAL2_1)); + pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleAL2_1)); +#else + US_TEST_CONDITION_REQUIRED(moduleAL2_1 == NULL, "Test for non-existing aut-loaded module TestModuleAL2_1") +#endif + + pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleAL2)); + + US_TEST_CONDITION(listener.CheckListenerEvents(pEvts), "Test for unexpected events"); + + mc->RemoveModuleListener(&listener, &TestModuleListener::ModuleChanged); +} + +} // end unnamed namespace + + +int usModuleAutoLoadTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ModuleLoaderTest"); + + ModuleSettings::SetAutoLoadingEnabled(false); + testDefaultAutoLoadPath(false); + ModuleSettings::SetAutoLoadingEnabled(true); + + testDefaultAutoLoadPath(true); + + testCustomAutoLoadPath(); + + US_TEST_END() +} diff --git a/test/usModuleManifestTest.cpp b/test/usModuleManifestTest.cpp new file mode 100644 index 0000000000..757a38da59 --- /dev/null +++ b/test/usModuleManifestTest.cpp @@ -0,0 +1,96 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "usTestingMacros.h" +#include "usTestingConfig.h" + +US_USE_NAMESPACE + +namespace { + +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + +} // end unnamed namespace + +int usModuleManifestTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ModuleManifestTest"); + + SharedLibrary target(LIB_PATH, "TestModuleM"); + + // Start the test target + try + { + target.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG( << "Failed to load module, got exception: " + << e.what() << " + in frameSL02a:FAIL" ); + } + + Module* moduleM = ModuleRegistry::GetModule("TestModuleM Module"); + US_TEST_CONDITION_REQUIRED(moduleM != 0, "Test for existing module TestModuleM") + + US_TEST_CONDITION(moduleM->GetProperty(Module::PROP_NAME()).ToString() == "TestModuleM Module", "Module name") + US_TEST_CONDITION(moduleM->GetName() == "TestModuleM Module", "Module name 2") + US_TEST_CONDITION(moduleM->GetProperty(Module::PROP_DESCRIPTION()).ToString() == "My Module description", "Module description") + US_TEST_CONDITION(moduleM->GetLocation() == moduleM->GetProperty(Module::PROP_LOCATION()).ToString(), "Module location") + US_TEST_CONDITION(moduleM->GetProperty(Module::PROP_VERSION()).ToString() == "1.0.0", "Module version") + US_TEST_CONDITION(moduleM->GetVersion() == ModuleVersion(1,0,0), "Module version 2") + + Any anyVector = moduleM->GetProperty("vector"); + US_TEST_CONDITION_REQUIRED(anyVector.Type() == typeid(std::vector), "vector type") + std::vector& vec = ref_any_cast >(anyVector); + US_TEST_CONDITION_REQUIRED(vec.size() == 3, "vector size") + US_TEST_CONDITION_REQUIRED(vec[0].Type() == typeid(std::string), "vector 0 type") + US_TEST_CONDITION_REQUIRED(vec[0].ToString() == "first", "vector 0 value") + US_TEST_CONDITION_REQUIRED(vec[1].Type() == typeid(int), "vector 1 type") + US_TEST_CONDITION_REQUIRED(any_cast(vec[1]) == 2, "vector 1 value") + + Any anyMap = moduleM->GetProperty("map"); + US_TEST_CONDITION_REQUIRED(anyMap.Type() == typeid(std::map), "map type") + std::map& m = ref_any_cast >(anyMap); + US_TEST_CONDITION_REQUIRED(m.size() == 3, "map size") + US_TEST_CONDITION_REQUIRED(m["string"].Type() == typeid(std::string), "map 0 type") + US_TEST_CONDITION_REQUIRED(m["string"].ToString() == "hi", "map 0 value") + US_TEST_CONDITION_REQUIRED(m["number"].Type() == typeid(int), "map 1 type") + US_TEST_CONDITION_REQUIRED(any_cast(m["number"]) == 4, "map 1 value") + US_TEST_CONDITION_REQUIRED(m["list"].Type() == typeid(std::vector), "map 2 type") + US_TEST_CONDITION_REQUIRED(any_cast >(m["list"]).size() == 2, "map 2 value size") + + target.Unload(); + + US_TEST_END() +} diff --git a/test/usModulePropsInterface.h b/test/usModulePropsInterface.h new file mode 100644 index 0000000000..27bd6e7568 --- /dev/null +++ b/test/usModulePropsInterface.h @@ -0,0 +1,44 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USMODULEPROPSINTERFACE_H +#define USMODULEPROPSINTERFACE_H + +#include +#include + +US_BEGIN_NAMESPACE + +struct ModulePropsInterface +{ + typedef ServiceProperties Properties; + + virtual ~ModulePropsInterface() {} + + virtual const Properties& GetProperties() const = 0; +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(ModulePropsInterface), "org.us.testing.ModulePropsInterface") + +#endif // USMODULEPROPSINTERFACE_H diff --git a/test/usModuleResourceTest.cpp b/test/usModuleResourceTest.cpp new file mode 100644 index 0000000000..ac4fc25cda --- /dev/null +++ b/test/usModuleResourceTest.cpp @@ -0,0 +1,542 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "usTestingMacros.h" + +#include + +#include + +US_USE_NAMESPACE + +namespace { + +void checkResourceInfo(const ModuleResource& res, const std::string& path, + const std::string& baseName, + const std::string& completeBaseName, const std::string& suffix, + const std::string& completeSuffix, + int size, bool children = false, bool compressed = false) +{ + US_TEST_CONDITION_REQUIRED(res.IsValid(), "Valid resource") + US_TEST_CONDITION(res.GetBaseName() == baseName, "GetBaseName()") + US_TEST_CONDITION(res.GetChildren().empty() == !children, "No children") + US_TEST_CONDITION(res.GetCompleteBaseName() == completeBaseName, "GetCompleteBaseName()") + US_TEST_CONDITION(res.GetName() == completeBaseName + "." + suffix, "GetName()") + US_TEST_CONDITION(res.GetResourcePath() == path + completeBaseName + "." + suffix, "GetResourcePath()") + US_TEST_CONDITION(res.GetPath() == path, "GetPath()") + US_TEST_CONDITION(res.GetSize() == size, "Data size") + US_TEST_CONDITION(res.GetSuffix() == suffix, "Suffix") + US_TEST_CONDITION(res.GetCompleteSuffix() == completeSuffix, "Complete suffix") + US_TEST_CONDITION(res.IsCompressed() == compressed, "Compression flag") +} + +void testTextResource(Module* module) +{ + ModuleResource res = module->GetResource("foo.txt"); +#ifdef US_PLATFORM_WINDOWS + checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 16, false); + const std::streampos ssize(13); + const std::string fileData = "foo and\nbar\n\n"; +#else + checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 13, false); + const std::streampos ssize(12); + const std::string fileData = "foo and\nbar\n"; +#endif + + ModuleResourceStream rs(res); + + rs.seekg(0, std::ios::end); + US_TEST_CONDITION(rs.tellg() == ssize, "Stream content length"); + rs.seekg(0, std::ios::beg); + + std::string content; + content.reserve(res.GetSize()); + char buffer[1024]; + while (rs.read(buffer, sizeof(buffer))) + { + content.append(buffer, sizeof(buffer)); + } + content.append(buffer, static_cast(rs.gcount())); + + US_TEST_CONDITION(rs.eof(), "EOF check"); + US_TEST_CONDITION(content == fileData, "Resource content"); + + rs.clear(); + rs.seekg(0); + + US_TEST_CONDITION_REQUIRED(rs.tellg() == std::streampos(0), "Move to start") + US_TEST_CONDITION_REQUIRED(rs.good(), "Start re-reading"); + + std::vector lines; + std::string line; + while (std::getline(rs, line)) + { + lines.push_back(line); + } + US_TEST_CONDITION_REQUIRED(lines.size() > 1, "Number of lines") + US_TEST_CONDITION(lines[0] == "foo and", "Check first line") + US_TEST_CONDITION(lines[1] == "bar", "Check second line") +} + +void testTextResourceAsBinary(Module* module) +{ + ModuleResource res = module->GetResource("foo.txt"); + +#ifdef US_PLATFORM_WINDOWS + checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 16, false); + const std::streampos ssize(16); + const std::string fileData = "foo and\r\nbar\r\n\r\n"; +#else + checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 13, false); + const std::streampos ssize(13); + const std::string fileData = "foo and\nbar\n\n"; +#endif + + + ModuleResourceStream rs(res, std::ios_base::binary); + + rs.seekg(0, std::ios::end); + US_TEST_CONDITION(rs.tellg() == ssize, "Stream content length"); + rs.seekg(0, std::ios::beg); + + std::string content; + content.reserve(res.GetSize()); + char buffer[1024]; + while (rs.read(buffer, sizeof(buffer))) + { + content.append(buffer, sizeof(buffer)); + } + content.append(buffer, static_cast(rs.gcount())); + + US_TEST_CONDITION(rs.eof(), "EOF check"); + US_TEST_CONDITION(content == fileData, "Resource content"); +} + +#ifdef US_BUILD_SHARED_LIBS +void testInvalidResource(Module* module) +{ + ModuleResource res = module->GetResource("invalid"); + US_TEST_CONDITION_REQUIRED(res.IsValid() == false, "Check invalid resource") + US_TEST_CONDITION(res.GetName().empty(), "Check empty name") + US_TEST_CONDITION(res.GetPath().empty(), "Check empty path") + US_TEST_CONDITION(res.GetResourcePath().empty(), "Check empty resource path") + US_TEST_CONDITION(res.GetBaseName().empty(), "Check empty base name") + US_TEST_CONDITION(res.GetCompleteBaseName().empty(), "Check empty complete base name") + US_TEST_CONDITION(res.GetSuffix().empty(), "Check empty suffix") + + US_TEST_CONDITION(res.GetChildren().empty(), "Check empty children") + US_TEST_CONDITION(res.GetSize() == 0, "Check zero size") + US_TEST_CONDITION(res.GetData() == NULL, "Check NULL data") + + ModuleResourceStream rs(res); + US_TEST_CONDITION(rs.good() == true, "Check invalid resource stream") + rs.ignore(); + US_TEST_CONDITION(rs.good() == false, "Check invalid resource stream") + US_TEST_CONDITION(rs.eof() == true, "Check invalid resource stream") +} +#endif + +void testSpecialCharacters(Module* module) +{ + ModuleResource res = module->GetResource("special_chars.dummy.txt"); +#ifdef US_PLATFORM_WINDOWS + checkResourceInfo(res, "/", "special_chars", "special_chars.dummy", "txt", "dummy.txt", 56, false); + const std::streampos ssize(54); + const std::string fileData = "German Füße (feet)\nFrench garçon de café (waiter)\n"; +#else + checkResourceInfo(res, "/", "special_chars", "special_chars.dummy", "txt", "dummy.txt", 54, false); + const std::streampos ssize(53); + const std::string fileData = "German Füße (feet)\nFrench garçon de café (waiter)"; +#endif + + ModuleResourceStream rs(res); + + rs.seekg(0, std::ios_base::end); + US_TEST_CONDITION(rs.tellg() == ssize, "Stream content length"); + rs.seekg(0, std::ios_base::beg); + + std::string content; + content.reserve(res.GetSize()); + char buffer[1024]; + while (rs.read(buffer, sizeof(buffer))) + { + content.append(buffer, sizeof(buffer)); + } + content.append(buffer, static_cast(rs.gcount())); + + US_TEST_CONDITION(rs.eof(), "EOF check"); + US_TEST_CONDITION(content == fileData, "Resource content"); +} + +void testBinaryResource(Module* module) +{ + ModuleResource res = module->GetResource("/icons/cppmicroservices.png"); + checkResourceInfo(res, "/icons/", "cppmicroservices", "cppmicroservices", "png", "png", 2424, false); + + ModuleResourceStream rs(res, std::ios_base::binary); + rs.seekg(0, std::ios_base::end); + std::streampos resLength = rs.tellg(); + rs.seekg(0); + + std::ifstream png(CppMicroServices_SOURCE_DIR "/test/modules/libRWithResources/resources/icons/cppmicroservices.png", + std::ifstream::in | std::ifstream::binary); + + US_TEST_CONDITION_REQUIRED(png.is_open(), "Open reference file") + + png.seekg(0, std::ios_base::end); + std::streampos pngLength = png.tellg(); + png.seekg(0); + US_TEST_CONDITION(res.GetSize() == resLength, "Check resource size") + US_TEST_CONDITION_REQUIRED(resLength == pngLength, "Compare sizes") + + char c1 = 0; + char c2 = 0; + bool isEqual = true; + int count = 0; + while (png.get(c1) && rs.get(c2)) + { + ++count; + if (c1 != c2) + { + isEqual = false; + break; + } + } + + US_TEST_CONDITION_REQUIRED(count == pngLength, "Check if everything was read"); + US_TEST_CONDITION_REQUIRED(isEqual, "Equal binary contents"); + US_TEST_CONDITION(png.eof(), "EOF check"); +} + +#ifdef US_ENABLE_RESOURCE_COMPRESSION +void testCompressedResource(Module* module) +{ + ModuleResource res = module->GetResource("/icons/compressable.bmp"); + checkResourceInfo(res, "/icons/", "compressable", "compressable", "bmp", "bmp", 411, false, true); + + ModuleResourceStream rs(res, std::ios_base::binary); + rs.seekg(0, std::ios_base::end); + std::streampos resLength = rs.tellg(); + rs.seekg(0); + + std::ifstream bmp(CppMicroServices_SOURCE_DIR "/test/modules/libRWithResources/resources/icons/compressable.bmp", + std::ifstream::in | std::ifstream::binary); + + US_TEST_CONDITION_REQUIRED(bmp.is_open(), "Open reference file") + + bmp.seekg(0, std::ios_base::end); + std::streampos bmpLength = bmp.tellg(); + bmp.seekg(0); + US_TEST_CONDITION(300122 == resLength, "Check resource size") + US_TEST_CONDITION_REQUIRED(resLength == bmpLength, "Compare sizes") + + char c1 = 0; + char c2 = 0; + bool isEqual = true; + int count = 0; + while (bmp.get(c1) && rs.get(c2)) + { + ++count; + if (c1 != c2) + { + isEqual = false; + break; + } + } + + US_TEST_CONDITION_REQUIRED(count == bmpLength, "Check if everything was read"); + US_TEST_CONDITION_REQUIRED(isEqual, "Equal binary contents"); + US_TEST_CONDITION(bmp.eof(), "EOF check"); +} +#endif + +struct ResourceComparator { + bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const + { + return mr1 < mr2; + } +}; + +#ifdef US_BUILD_SHARED_LIBS +void testResourceTree(Module* module) +{ + ModuleResource res = module->GetResource(""); + US_TEST_CONDITION(res.GetResourcePath() == "/", "Check root file path") + US_TEST_CONDITION(res.IsDir() == true, "Check type") + + std::vector children = res.GetChildren(); + std::sort(children.begin(), children.end()); + US_TEST_CONDITION_REQUIRED(children.size() == 4, "Check child count") + US_TEST_CONDITION(children[0] == "foo.txt", "Check child name") + US_TEST_CONDITION(children[1] == "icons", "Check child name") + US_TEST_CONDITION(children[2] == "special_chars.dummy.txt", "Check child name") + US_TEST_CONDITION(children[3] == "test.xml", "Check child name") + + + ModuleResource readme = module->GetResource("/icons/readme.txt"); + US_TEST_CONDITION(readme.IsFile() && readme.GetChildren().empty(), "Check file resource") + + ModuleResource icons = module->GetResource("icons"); + US_TEST_CONDITION(icons.IsDir() && !icons.IsFile() && !icons.GetChildren().empty(), "Check directory resource") + + children = icons.GetChildren(); + US_TEST_CONDITION_REQUIRED(children.size() == 3, "Check icons child count") + std::sort(children.begin(), children.end()); + US_TEST_CONDITION(children[0] == "compressable.bmp", "Check child name") + US_TEST_CONDITION(children[1] == "cppmicroservices.png", "Check child name") + US_TEST_CONDITION(children[2] == "readme.txt", "Check child name") + + ResourceComparator resourceComparator; + + // find all .txt files + std::vector nodes = module->FindResources("", "*.txt", false); + std::sort(nodes.begin(), nodes.end(), resourceComparator); + US_TEST_CONDITION_REQUIRED(nodes.size() == 2, "Found child count") + US_TEST_CONDITION(nodes[0].GetResourcePath() == "/foo.txt", "Check child name") + US_TEST_CONDITION(nodes[1].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") + + nodes = module->FindResources("", "*.txt", true); + std::sort(nodes.begin(), nodes.end(), resourceComparator); + US_TEST_CONDITION_REQUIRED(nodes.size() == 3, "Found child count") + US_TEST_CONDITION(nodes[0].GetResourcePath() == "/foo.txt", "Check child name") + US_TEST_CONDITION(nodes[1].GetResourcePath() == "/icons/readme.txt", "Check child name") + US_TEST_CONDITION(nodes[2].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") + + // find all resources + nodes = module->FindResources("", "", true); + US_TEST_CONDITION(nodes.size() == 6, "Total resource number") + nodes = module->FindResources("", "**", true); + US_TEST_CONDITION(nodes.size() == 6, "Total resource number") + + + // test pattern matching + nodes.clear(); + nodes = module->FindResources("/icons", "*micro*.png", false); + US_TEST_CONDITION(nodes.size() == 1 && nodes[0].GetResourcePath() == "/icons/cppmicroservices.png", "Check file pattern matches") + + nodes.clear(); + nodes = module->FindResources("", "*.txt", true); + US_TEST_CONDITION(nodes.size() == 3, "Check recursive pattern matches") +} + +#else + +void testResourceTree(Module* module) +{ + ModuleResource res = module->GetResource(""); + US_TEST_CONDITION(res.GetResourcePath() == "/", "Check root file path") + US_TEST_CONDITION(res.IsDir() == true, "Check type") + + std::vector children = res.GetChildren(); + std::sort(children.begin(), children.end()); + US_TEST_CONDITION_REQUIRED(children.size() == 10, "Check child count") + US_TEST_CONDITION(children[0] == "dynamic.txt", "Check dynamic.txt child name") + US_TEST_CONDITION(children[1] == "foo.txt", "Check foo.txt child name") + US_TEST_CONDITION(children[2] == "icons", "Check icons child name") + US_TEST_CONDITION(children[3] == "manifest.json", "Check manifest.json child name") + US_TEST_CONDITION(children[4] == "manifest.json", "Check manifest.json child name") + US_TEST_CONDITION(children[5] == "res.txt", "Check res.txt child name") + US_TEST_CONDITION(children[6] == "res.txt", "Check res.txt child name") + US_TEST_CONDITION(children[7] == "special_chars.dummy.txt", "Check special_chars.dummy.txt child name") + US_TEST_CONDITION(children[8] == "static.txt", "Check static.txt child name") + US_TEST_CONDITION(children[9] == "test.xml", "Check test.xml child name") + + + ModuleResource readme = module->GetResource("/icons/readme.txt"); + US_TEST_CONDITION(readme.IsFile() && readme.GetChildren().empty(), "Check file resource") + + ModuleResource icons = module->GetResource("icons"); + US_TEST_CONDITION(icons.IsDir() && !icons.IsFile() && !icons.GetChildren().empty(), "Check directory resource") + + children = icons.GetChildren(); + US_TEST_CONDITION_REQUIRED(children.size() == 3, "Check icons child count") + std::sort(children.begin(), children.end()); + US_TEST_CONDITION(children[0] == "compressable.bmp", "Check child name") + US_TEST_CONDITION(children[1] == "cppmicroservices.png", "Check child name") + US_TEST_CONDITION(children[2] == "readme.txt", "Check child name") + + ResourceComparator resourceComparator; + + // find all .txt files + std::vector nodes = module->FindResources("", "*.txt", false); + std::sort(nodes.begin(), nodes.end(), resourceComparator); + US_TEST_CONDITION_REQUIRED(nodes.size() == 6, "Found child count") + US_TEST_CONDITION(nodes[0].GetResourcePath() == "/dynamic.txt", "Check dynamic.txt child name") + US_TEST_CONDITION(nodes[1].GetResourcePath() == "/foo.txt", "Check child name") + US_TEST_CONDITION(nodes[2].GetResourcePath() == "/res.txt", "Check res.txt child name") + US_TEST_CONDITION(nodes[3].GetResourcePath() == "/res.txt", "Check res.txt child name") + US_TEST_CONDITION(nodes[4].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") + US_TEST_CONDITION(nodes[5].GetResourcePath() == "/static.txt", "Check static.txt child name") + + nodes = module->FindResources("", "*.txt", true); + std::sort(nodes.begin(), nodes.end(), resourceComparator); + US_TEST_CONDITION_REQUIRED(nodes.size() == 7, "Found child count") + US_TEST_CONDITION(nodes[0].GetResourcePath() == "/dynamic.txt", "Check dynamic.txt child name") + US_TEST_CONDITION(nodes[1].GetResourcePath() == "/foo.txt", "Check child name") + US_TEST_CONDITION(nodes[2].GetResourcePath() == "/icons/readme.txt", "Check child name") + US_TEST_CONDITION(nodes[3].GetResourcePath() == "/res.txt", "Check res.txt child name") + US_TEST_CONDITION(nodes[4].GetResourcePath() == "/res.txt", "Check res.txt child name") + US_TEST_CONDITION(nodes[5].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") + US_TEST_CONDITION(nodes[6].GetResourcePath() == "/static.txt", "Check static.txt child name") + + // find all resources + nodes = module->FindResources("", "", true); + US_TEST_CONDITION(nodes.size() == 12, "Total resource number") + nodes = module->FindResources("", "**", true); + US_TEST_CONDITION(nodes.size() == 12, "Total resource number") + + + // test pattern matching + nodes.clear(); + nodes = module->FindResources("/icons", "*micro*.png", false); + US_TEST_CONDITION(nodes.size() == 1 && nodes[0].GetResourcePath() == "/icons/cppmicroservices.png", "Check file pattern matches") + + nodes.clear(); + nodes = module->FindResources("", "*.txt", true); + US_TEST_CONDITION(nodes.size() == 7, "Check recursive pattern matches") +} + +#endif + +void testResourceOperators(Module* module) +{ + ModuleResource invalid = module->GetResource("invalid"); + ModuleResource foo = module->GetResource("foo.txt"); + US_TEST_CONDITION_REQUIRED(foo.IsValid() && foo, "Check valid resource") + ModuleResource foo2(foo); + US_TEST_CONDITION(foo == foo, "Check equality operator") + US_TEST_CONDITION(foo == foo2, "Check copy constructor and equality operator") + US_TEST_CONDITION(foo != invalid, "Check inequality with invalid resource") + + ModuleResource xml = module->GetResource("/test.xml"); + US_TEST_CONDITION_REQUIRED(xml.IsValid() && xml, "Check valid resource") + US_TEST_CONDITION(foo != xml, "Check inequality") + US_TEST_CONDITION(foo < xml, "Check operator<") + + // check operator< by using a set + std::set resources; + resources.insert(foo); + resources.insert(foo); + resources.insert(xml); + US_TEST_CONDITION(resources.size() == 2, "Check operator< with set") + + // check hash function specialization + US_UNORDERED_SET_TYPE resources2; + resources2.insert(foo); + resources2.insert(foo); + resources2.insert(xml); + US_TEST_CONDITION(resources2.size() == 2, "Check operator< with unordered set") + + // check operator<< + std::ostringstream oss; + oss << foo; + US_TEST_CONDITION(oss.str() == foo.GetResourcePath(), "Check operator<<") +} + +#ifdef US_BUILD_SHARED_LIBS +void testResourceFromExecutable(Module* module) +{ + ModuleResource resource = module->GetResource("usTestResource.txt"); + US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid executable resource") + + std::string line; + ModuleResourceStream rs(resource); + std::getline(rs, line); + US_TEST_CONDITION(line == "meant to be compiled into the test driver", "Check executable resource content") +} +#endif + +} // end unnamed namespace + + +int usModuleResourceTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ModuleResourceTest"); + + ModuleContext* mc = GetModuleContext(); + assert(mc); + +#ifdef US_BUILD_SHARED_LIBS + +#ifdef US_PLATFORM_WINDOWS + const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + SharedLibrary libR(LIB_PATH, "TestModuleR"); + + try + { + libR.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) + } + + Module* moduleR = ModuleRegistry::GetModule("TestModuleR Module"); + US_TEST_CONDITION_REQUIRED(moduleR != NULL, "Test for existing module TestModuleR") + + US_TEST_CONDITION(moduleR->GetName() == "TestModuleR Module", "Test module name") + + testInvalidResource(moduleR); + testResourceFromExecutable(mc->GetModule()); +#else + Module* moduleR = mc->GetModule(); + US_TEST_CONDITION_REQUIRED(moduleR != NULL, "Test for existing module 0") + + US_TEST_CONDITION(moduleR->GetName() == "CppMicroServices", "Test module name") +#endif + + testResourceTree(moduleR); + + testResourceOperators(moduleR); + + testTextResource(moduleR); + testTextResourceAsBinary(moduleR); + testSpecialCharacters(moduleR); + + testBinaryResource(moduleR); + +#ifdef US_ENABLE_RESOURCE_COMPRESSION + testCompressedResource(moduleR); +#endif + +#ifdef US_BUILD_SHARED_LIBS + ModuleResource foo = moduleR->GetResource("foo.txt"); + US_TEST_CONDITION(foo.IsValid() == true, "Valid resource") + libR.Unload(); + US_TEST_CONDITION(foo.IsValid() == false, "Invalidated resource") + US_TEST_CONDITION(foo.GetData() == NULL, "NULL data") +#endif + + US_TEST_END() +} diff --git a/test/usModuleTest.cpp b/test/usModuleTest.cpp new file mode 100644 index 0000000000..43ff75ee8d --- /dev/null +++ b/test/usModuleTest.cpp @@ -0,0 +1,325 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "usTestUtilModuleListener.h" +#include "usTestingMacros.h" +#include "usTestingConfig.h" + +US_USE_NAMESPACE + +namespace { + +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + +// Verify that the same member function pointers registered as listeners +// with different receivers works. +void frame02a() +{ + ModuleContext* mc = GetModuleContext(); + + TestModuleListener listener1; + TestModuleListener listener2; + + try + { + mc->RemoveModuleListener(&listener1, &TestModuleListener::ModuleChanged); + mc->AddModuleListener(&listener1, &TestModuleListener::ModuleChanged); + mc->RemoveModuleListener(&listener2, &TestModuleListener::ModuleChanged); + mc->AddModuleListener(&listener2, &TestModuleListener::ModuleChanged); + } + catch (const std::logic_error& ise) + { + US_TEST_FAILED_MSG( << "module listener registration failed " << ise.what() + << " : frameSL02a:FAIL" ); + } + + SharedLibrary target(LIB_PATH, "TestModuleA"); + +#ifdef US_BUILD_SHARED_LIBS + // Start the test target + try + { + target.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG( << "Failed to load module, got exception: " + << e.what() << " + in frameSL02a:FAIL" ); + } + + Module* moduleA = ModuleRegistry::GetModule("TestModuleA Module"); + US_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for existing module TestModuleA") +#endif + + std::vector pEvts; +#ifdef US_BUILD_SHARED_LIBS + pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleA)); + pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleA)); +#endif + + std::vector seEvts; + + US_TEST_CONDITION(listener1.CheckListenerEvents(pEvts, seEvts), "Check first module listener") + US_TEST_CONDITION(listener2.CheckListenerEvents(pEvts, seEvts), "Check second module listener") + + mc->RemoveModuleListener(&listener1, &TestModuleListener::ModuleChanged); + mc->RemoveModuleListener(&listener2, &TestModuleListener::ModuleChanged); + + target.Unload(); +} + +// Verify information from the ModuleInfo struct +void frame005a(ModuleContext* mc) +{ + Module* m = mc->GetModule(); + + // check expected headers + +#ifdef US_BUILD_SHARED_LIBS + US_TEST_CONDITION("CppMicroServicesTestDriver" == m->GetName(), "Test module name"); + US_TEST_CONDITION(ModuleVersion(0,1,0) == m->GetVersion(), "Test module version") +#else + US_TEST_CONDITION("CppMicroServices" == m->GetName(), "Test module name"); + US_TEST_CONDITION(ModuleVersion(1,99,0) == m->GetVersion(), "Test module version") +#endif +} + +// Get context id, location and status of the module +void frame010a(ModuleContext* mc) +{ + Module* m = mc->GetModule(); + + long int contextid = m->GetModuleId(); + US_DEBUG << "CONTEXT ID:" << contextid; + + std::string location = m->GetLocation(); + US_DEBUG << "LOCATION:" << location; + US_TEST_CONDITION(!location.empty(), "Test for non-empty module location") + + US_TEST_CONDITION(m->IsLoaded(), "Test for loaded flag") +} + +//---------------------------------------------------------------------------- +//Test result of GetService(ServiceReference()). Should throw std::invalid_argument +void frame018a(ModuleContext* mc) +{ + try + { + mc->GetService(ServiceReferenceU()); + US_DEBUG << "Got service object, expected std::invalid_argument exception"; + US_TEST_FAILED_MSG(<< "Got service object, excpected std::invalid_argument exception") + } + catch (const std::invalid_argument& ) + {} + catch (...) + { + US_TEST_FAILED_MSG(<< "Got wrong exception, expected std::invalid_argument") + } +} + +// Load libA and check that it exists and that the service it registers exists, +// also check that the expected events occur +void frame020a(ModuleContext* mc, TestModuleListener& listener, +#ifdef US_BUILD_SHARED_LIBS + SharedLibrary& libA) +{ + try + { + libA.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) + } + + Module* moduleA = ModuleRegistry::GetModule("TestModuleA Module"); + US_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for existing module TestModuleA") + + US_TEST_CONDITION(moduleA->GetName() == "TestModuleA Module", "Test module name") +#else + SharedLibrary& /*libA*/) +{ +#endif + + // Check if libA registered the expected service + try + { + ServiceReferenceU sr1 = mc->GetServiceReference("org.cppmicroservices.TestModuleAService"); + InterfaceMap o1 = mc->GetService(sr1); + US_TEST_CONDITION(!o1.empty(), "Test if service object found"); + + try + { + US_TEST_CONDITION(mc->UngetService(sr1), "Test if Service UnGet returns true"); + } + catch (const std::logic_error le) + { + US_TEST_FAILED_MSG(<< "UnGetService exception: " << le.what()) + } + + // check the listeners for events + std::vector pEvts; +#ifdef US_BUILD_SHARED_LIBS + pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleA)); + pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleA)); +#endif + + std::vector seEvts; +#ifdef US_BUILD_SHARED_LIBS + seEvts.push_back(ServiceEvent(ServiceEvent::REGISTERED, sr1)); +#endif + + US_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); + + } + catch (const ServiceException& /*se*/) + { + US_TEST_FAILED_MSG(<< "test module, expected service not found"); + } + +#ifdef US_BUILD_SHARED_LIBS + US_TEST_CONDITION(moduleA->IsLoaded() == true, "Test if loaded correctly"); +#endif +} + + +// Unload libA and check for correct events +void frame030b(ModuleContext* mc, TestModuleListener& listener, SharedLibrary& libA) +{ +#ifdef US_BUILD_SHARED_LIBS + Module* moduleA = ModuleRegistry::GetModule("TestModuleA Module"); + US_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for non-null module") +#endif + + ServiceReferenceU sr1 + = mc->GetServiceReference("org.cppmicroservices.TestModuleAService"); + US_TEST_CONDITION(sr1, "Test for valid service reference") + + try + { + libA.Unload(); +#ifdef US_BUILD_SHARED_LIBS + US_TEST_CONDITION(moduleA->IsLoaded() == false, "Test for unloaded state") +#endif + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG(<< "UnLoad module exception: " << e.what()) + } + + std::vector pEvts; +#ifdef US_BUILD_SHARED_LIBS + pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADING, moduleA)); + pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADED, moduleA)); +#endif + + std::vector seEvts; +#ifdef US_BUILD_SHARED_LIBS + seEvts.push_back(ServiceEvent(ServiceEvent::UNREGISTERING, sr1)); +#endif + + US_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); +} + + +struct LocalListener { + void ServiceChanged(const ServiceEvent) {} +}; + +// Add a service listener with a broken LDAP filter to Get an exception +void frame045a(ModuleContext* mc) +{ + LocalListener sListen1; + std::string brokenFilter = "A broken LDAP filter"; + + try + { + mc->AddServiceListener(&sListen1, &LocalListener::ServiceChanged, brokenFilter); + } + catch (const std::invalid_argument& /*ia*/) + { + //assertEquals("InvalidSyntaxException.GetFilter should be same as input string", brokenFilter, ise.GetFilter()); + } + catch (...) + { + US_TEST_FAILED_MSG(<< "test module, wrong exception on broken LDAP filter:"); + } +} + +} // end unnamed namespace + +int usModuleTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ModuleTest"); + + frame02a(); + + ModuleContext* mc = GetModuleContext(); + TestModuleListener listener; + + 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); + + SharedLibrary libA(LIB_PATH, "TestModuleA"); + frame020a(mc, listener, libA); + frame030b(mc, listener, libA); + + frame045a(mc); + + mc->RemoveModuleListener(&listener, &TestModuleListener::ModuleChanged); + mc->RemoveServiceListener(&listener, &TestModuleListener::ServiceChanged); + + US_TEST_END() +} diff --git a/test/usServiceControlInterface.h b/test/usServiceControlInterface.h new file mode 100644 index 0000000000..129832ff12 --- /dev/null +++ b/test/usServiceControlInterface.h @@ -0,0 +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 USSERVICECONTROLINTERFACE_H +#define USSERVICECONTROLINTERFACE_H + +#include +#include + +#include + +US_BEGIN_NAMESPACE + +struct ServiceControlInterface +{ + + virtual ~ServiceControlInterface() {} + + virtual void ServiceControl(int service, const std::string& operation, int ranking) = 0; +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(ServiceControlInterface), "org.us.testing.ServiceControlInterface") + +#endif // USSERVICECONTROLINTERFACE_H diff --git a/test/usServiceFactoryTest.cpp b/test/usServiceFactoryTest.cpp new file mode 100644 index 0000000000..14c7a8feaa --- /dev/null +++ b/test/usServiceFactoryTest.cpp @@ -0,0 +1,234 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include +#include +#include + +#include "usTestingMacros.h" +#include "usTestingConfig.h" + +US_USE_NAMESPACE + +namespace { + +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + +} // end unnamed namespace + + +US_BEGIN_NAMESPACE + +struct TestModuleH +{ + virtual ~TestModuleH() {} +}; + +struct TestModuleH2 +{ + virtual ~TestModuleH2() {} +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleH), "org.cppmicroservices.TestModuleH") +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleH2), "org.cppmicroservices.TestModuleH2") + + +void TestServiceFactoryModuleScope() +{ + + // Install and start test module H, a service factory and test that the methods + // in that interface works. + + SharedLibrary target(LIB_PATH, "TestModuleH"); + +#ifdef US_BUILD_SHARED_LIBS + try + { + target.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what()) + } + + Module* moduleH = ModuleRegistry::GetModule("TestModuleH Module"); + US_TEST_CONDITION_REQUIRED(moduleH != 0, "Test for existing module TestModuleH") + + std::vector registeredRefs = moduleH->GetRegisteredServices(); + US_TEST_CONDITION_REQUIRED(registeredRefs.size() == 2, "# of registered services") + US_TEST_CONDITION(registeredRefs[0].GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_MODULE(), "service scope") + US_TEST_CONDITION(registeredRefs[1].GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_PROTOTYPE(), "service scope") +#endif + + ModuleContext* mc = GetModuleContext(); + // Check that a service reference exist + const ServiceReferenceU sr1 = mc->GetServiceReference("org.cppmicroservices.TestModuleH"); + US_TEST_CONDITION_REQUIRED(sr1, "Service shall be present.") + US_TEST_CONDITION(sr1.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_MODULE(), "service scope") + + InterfaceMap service = mc->GetService(sr1); + US_TEST_CONDITION_REQUIRED(service.size() >= 1, "GetService()") + InterfaceMap::const_iterator serviceIter = service.find("org.cppmicroservices.TestModuleH"); + US_TEST_CONDITION_REQUIRED(serviceIter != service.end(), "GetService()") + US_TEST_CONDITION_REQUIRED(serviceIter->second != NULL, "GetService()") + + InterfaceMap service2 = mc->GetService(sr1); + US_TEST_CONDITION(service == service2, "Same service pointer") + +#ifdef US_BUILD_SHARED_LIBS + std::vector usedRefs = mc->GetModule()->GetServicesInUse(); + US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use") + US_TEST_CONDITION(usedRefs[0] == sr1, "service ref in use") + + InterfaceMap service3 = moduleH->GetModuleContext()->GetService(sr1); + US_TEST_CONDITION(service != service3, "Different service pointer") + US_TEST_CONDITION(moduleH->GetModuleContext()->UngetService(sr1), "UngetService()") +#endif + + US_TEST_CONDITION_REQUIRED(mc->UngetService(sr1), "ungetService()") + + target.Unload(); +} + +void TestServiceFactoryPrototypeScope() +{ + + // Install and start test module H, a service factory and test that the methods + // in that interface works. + + SharedLibrary target(LIB_PATH, "TestModuleH"); + +#ifdef US_BUILD_SHARED_LIBS + try + { + target.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what()) + } + + Module* moduleH = ModuleRegistry::GetModule("TestModuleH Module"); + US_TEST_CONDITION_REQUIRED(moduleH != 0, "Test for existing module TestModuleH") +#endif + + ModuleContext* mc = GetModuleContext(); + // Check that a service reference exist + const ServiceReference sr1 = mc->GetServiceReference(); + US_TEST_CONDITION_REQUIRED(sr1, "Service shall be present.") + US_TEST_CONDITION(sr1.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_PROTOTYPE(), "service scope") + + ServiceObjects svcObjects = mc->GetServiceObjects(sr1); + TestModuleH2* prototypeServiceH2 = svcObjects.GetService(); + + const ServiceReferenceU sr1void = mc->GetServiceReference(us_service_interface_iid()); + ServiceObjects svcObjectsVoid = mc->GetServiceObjects(sr1void); + InterfaceMap prototypeServiceH2Void = svcObjectsVoid.GetService(); + US_TEST_CONDITION_REQUIRED(prototypeServiceH2Void.find(us_service_interface_iid()) != prototypeServiceH2Void.end(), + "ServiceObjects::GetService()") + +#ifdef US_BUILD_SHARED_LIBS + // There should be only one service in use + US_TEST_CONDITION_REQUIRED(mc->GetModule()->GetServicesInUse().size() == 1, "services in use") +#endif + + TestModuleH2* moduleScopeService = mc->GetService(sr1); + US_TEST_CONDITION_REQUIRED(moduleScopeService && moduleScopeService != prototypeServiceH2, "GetService()") + + US_TEST_CONDITION_REQUIRED(prototypeServiceH2 != prototypeServiceH2Void.find(us_service_interface_iid())->second, + "GetService()") + + svcObjectsVoid.UngetService(prototypeServiceH2Void); + + TestModuleH2* moduleScopeService2 = mc->GetService(sr1); + US_TEST_CONDITION(moduleScopeService == moduleScopeService2, "Same service pointer") + +#ifdef US_BUILD_SHARED_LIBS + std::vector usedRefs = mc->GetModule()->GetServicesInUse(); + US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use") + US_TEST_CONDITION(usedRefs[0] == sr1, "service ref in use") +#endif + + std::string filter = "(" + ServiceConstants::SERVICE_ID() + "=" + sr1.GetProperty(ServiceConstants::SERVICE_ID()).ToString() + ")"; + const ServiceReference sr2 = mc->GetServiceReferences(filter).front(); + US_TEST_CONDITION_REQUIRED(sr2, "Service shall be present.") + US_TEST_CONDITION(sr2.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_PROTOTYPE(), "service scope") + US_TEST_CONDITION(any_cast(sr2.GetProperty(ServiceConstants::SERVICE_ID())) == any_cast(sr1.GetProperty(ServiceConstants::SERVICE_ID())), "same service id") + + try + { + svcObjects.UngetService(moduleScopeService2); + US_TEST_FAILED_MSG(<< "std::invalid_argument exception expected") + } + catch (const std::invalid_argument&) + { + // this is expected + } + +#ifdef US_BUILD_SHARED_LIBS + // There should still be only one service in use + usedRefs = mc->GetModule()->GetServicesInUse(); + US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use") +#endif + + ServiceObjects svcObjects2 = svcObjects; + ServiceObjects svcObjects3 = mc->GetServiceObjects(sr1); + try + { + svcObjects3.UngetService(prototypeServiceH2); + US_TEST_FAILED_MSG(<< "std::invalid_argument exception expected") + } + catch (const std::invalid_argument&) + { + // this is expected + } + + svcObjects2.UngetService(prototypeServiceH2); + prototypeServiceH2 = svcObjects2.GetService(); + TestModuleH2* prototypeServiceH2_2 = svcObjects3.GetService(); + + US_TEST_CONDITION_REQUIRED(prototypeServiceH2_2 && prototypeServiceH2_2 != prototypeServiceH2, "prototype service") + + svcObjects2.UngetService(prototypeServiceH2); + svcObjects3.UngetService(prototypeServiceH2_2); + US_TEST_CONDITION_REQUIRED(mc->UngetService(sr1), "ungetService()") + + target.Unload(); +} + +int usServiceFactoryTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ServiceFactoryTest"); + + TestServiceFactoryModuleScope(); + TestServiceFactoryPrototypeScope(); + + US_TEST_END() +} diff --git a/test/usServiceListenerTest.cpp b/test/usServiceListenerTest.cpp new file mode 100644 index 0000000000..42c6235d70 --- /dev/null +++ b/test/usServiceListenerTest.cpp @@ -0,0 +1,567 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +#include +#include + +#include +#include +#include +#include + +#include + +US_USE_NAMESPACE + +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + +class TestServiceListener +{ + +private: + + friend bool runLoadUnloadTest(const std::string&, int cnt, SharedLibrary&, + const std::vector&); + + const bool checkUsingModules; + std::vector events; + + bool teststatus; + + ModuleContext* mc; + +public: + + TestServiceListener(ModuleContext* mc, bool checkUsingModules = true) + : checkUsingModules(checkUsingModules), events(), teststatus(true), mc(mc) + {} + + bool getTestStatus() const + { + return teststatus; + } + + void clearEvents() + { + events.clear(); + } + + bool checkEvents(const std::vector& eventTypes) + { + if (events.size() != eventTypes.size()) + { + dumpEvents(eventTypes); + return false; + } + + for (std::size_t i=0; i < eventTypes.size(); ++i) + { + if (eventTypes[i] != events[i].GetType()) + { + dumpEvents(eventTypes); + return false; + } + } + return true; + } + + void serviceChanged(const ServiceEvent evt) + { + events.push_back(evt); + US_TEST_OUTPUT( << "ServiceEvent: " << evt ); + if (ServiceEvent::UNREGISTERING == evt.GetType()) + { + ServiceReferenceU sr = evt.GetServiceReference(); + + // Validate that no module is marked as using the service + std::vector usingModules; + sr.GetUsingModules(usingModules); + if (checkUsingModules && !usingModules.empty()) + { + teststatus = false; + printUsingModules(sr, "*** Using modules (unreg) should be empty but is: "); + } + + // Check if the service can be fetched + InterfaceMap service = mc->GetService(sr); + sr.GetUsingModules(usingModules); + // if (UNREGISTERSERVICE_VALID_DURING_UNREGISTERING) { + // In this mode the service shall be obtainable during + // unregistration. + if (service.empty()) + { + teststatus = false; + US_TEST_OUTPUT( << "*** Service should be available to ServiceListener " + << "while handling unregistering event." ); + } + US_TEST_OUTPUT( << "Service (unreg): " << service.begin()->first << " -> " << service.begin()->second ); + if (checkUsingModules && usingModules.size() != 1) + { + teststatus = false; + printUsingModules(sr, "*** One using module expected " + "(unreg, after getService), found: "); + } + else + { + printUsingModules(sr, "Using modules (unreg, after getService): "); + } + // } else { + // // In this mode the service shall NOT be obtainable during + // // unregistration. + // if (null!=service) { + // teststatus = false; + // out.print("*** Service should not be available to ServiceListener " + // +"while handling unregistering event."); + // } + // if (checkUsingBundles && null!=usingBundles) { + // teststatus = false; + // printUsingBundles(sr, + // "*** Using bundles (unreg, after getService), " + // +"should be null but is: "); + // } else { + // printUsingBundles(sr, + // "Using bundles (unreg, after getService): null"); + // } + // } + mc->UngetService(sr); + + // Check that the UNREGISTERING service can not be looked up + // using the service registry. + try + { + long sid = any_cast(sr.GetProperty(ServiceConstants::SERVICE_ID())); + std::stringstream ss; + ss << "(" << ServiceConstants::SERVICE_ID() << "=" << sid << ")"; + std::vector srs = mc->GetServiceReferences("", ss.str()); + if (srs.empty()) + { + US_TEST_OUTPUT( << "ServiceReference for UNREGISTERING service is not" + " found in the service registry; ok." ); + } + else + { + teststatus = false; + US_TEST_OUTPUT( << "*** ServiceReference for UNREGISTERING service," + << sr << ", not found in the service registry; fail." ); + US_TEST_OUTPUT( << "Found the following Service references:") ; + for(std::vector::const_iterator sr = srs.begin(); + sr != srs.end(); ++sr) + { + US_TEST_OUTPUT( << (*sr) ); + } + } + } + catch (const std::exception& e) + { + teststatus = false; + US_TEST_OUTPUT( << "*** Unexpected excpetion when trying to lookup a" + " service while it is in state UNREGISTERING: " + << e.what() ); + } + } + } + + void printUsingModules(const ServiceReferenceU& sr, const std::string& caption) + { + std::vector usingModules; + sr.GetUsingModules(usingModules); + + US_TEST_OUTPUT( << (caption.empty() ? "Using modules: " : caption) ); + for(std::vector::const_iterator module = usingModules.begin(); + module != usingModules.end(); ++module) + { + US_TEST_OUTPUT( << " -" << (*module) ); + } + } + + // Print expected and actual service events. + void dumpEvents(const std::vector& eventTypes) + { + std::size_t max = events.size() > eventTypes.size() ? events.size() : eventTypes.size(); + US_TEST_OUTPUT( << "Expected event type -- Actual event" ); + for (std::size_t i=0; i < max; ++i) + { + ServiceEvent evt = i < events.size() ? events[i] : ServiceEvent(); + if (i < eventTypes.size()) + { + US_TEST_OUTPUT( << " " << eventTypes[i] << "--" << evt ); + } + else + { + US_TEST_OUTPUT( << " " << "- NONE - " << "--" << evt ); + } + } + } + +}; // end of class ServiceListener + +bool runLoadUnloadTest(const std::string& name, int cnt, SharedLibrary& target, + const std::vector& events) +{ + bool teststatus = true; + + ModuleContext* mc = GetModuleContext(); + + for (int i = 0; i < cnt && teststatus; ++i) + { + TestServiceListener sListen(mc); + try + { + mc->AddServiceListener(&sListen, &TestServiceListener::serviceChanged); + //mc->AddServiceListener(MessageDelegate1(&sListen, &ServiceListener::serviceChanged)); + } + catch (const std::logic_error& ise) + { + teststatus = false; + US_TEST_FAILED_MSG( << "service listener registration failed " << ise.what() + << " :" << name << ":FAIL" ); + } + + // Start the test target to get a service published. + try + { + target.Load(); + } + catch (const std::exception& e) + { + teststatus = false; + US_TEST_FAILED_MSG( << "Failed to load module, got exception: " + << e.what() << " + in " << name << ":FAIL" ); + } + + // Stop the test target to get a service unpublished. + try + { + target.Unload(); + } + catch (const std::exception& e) + { + teststatus = false; + US_TEST_FAILED_MSG( << "Failed to unload module, got exception: " + << e.what() << " + in " << name << ":FAIL" ); + } + + if (teststatus && !sListen.checkEvents(events)) + { + teststatus = false; + US_TEST_FAILED_MSG( << "Service listener event notification error :" + << name << ":FAIL" ); + } + + try + { + mc->RemoveServiceListener(&sListen, &TestServiceListener::serviceChanged); + teststatus &= sListen.teststatus; + sListen.clearEvents(); + } + catch (const std::logic_error& ise) + { + teststatus = false; + US_TEST_FAILED_MSG( << "service listener removal failed " << ise.what() + << " :" << name << ":FAIL" ); + } + } + return teststatus; +} + +void frameSL02a() +{ + ModuleContext* mc = GetModuleContext(); + + TestServiceListener listener1(mc); + TestServiceListener listener2(mc); + + try + { + mc->RemoveServiceListener(&listener1, &TestServiceListener::serviceChanged); + mc->AddServiceListener(&listener1, &TestServiceListener::serviceChanged); + mc->RemoveServiceListener(&listener2, &TestServiceListener::serviceChanged); + mc->AddServiceListener(&listener2, &TestServiceListener::serviceChanged); + } + catch (const std::logic_error& ise) + { + US_TEST_FAILED_MSG( << "service listener registration failed " << ise.what() + << " : frameSL02a:FAIL" ); + } + + SharedLibrary target(LIB_PATH, "TestModuleA"); + + // Start the test target to get a service published. + try + { + target.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG( << "Failed to load module, got exception: " + << e.what() << " + in frameSL02a:FAIL" ); + } + + std::vector events; + events.push_back(ServiceEvent::REGISTERED); + + US_TEST_CONDITION(listener1.checkEvents(events), "Check first service listener") + US_TEST_CONDITION(listener2.checkEvents(events), "Check second service listener") + + mc->RemoveServiceListener(&listener1, &TestServiceListener::serviceChanged); + mc->RemoveServiceListener(&listener2, &TestServiceListener::serviceChanged); + + target.Unload(); +} + +void frameSL05a() +{ + std::vector events; + events.push_back(ServiceEvent::REGISTERED); + events.push_back(ServiceEvent::UNREGISTERING); + SharedLibrary libA(LIB_PATH, "TestModuleA"); + bool testStatus = runLoadUnloadTest("FrameSL05a", 1, libA, events); + US_TEST_CONDITION(testStatus, "FrameSL05a") +} + +void frameSL10a() +{ + std::vector events; + events.push_back(ServiceEvent::REGISTERED); + events.push_back(ServiceEvent::UNREGISTERING); + SharedLibrary libA2(LIB_PATH, "TestModuleA2"); + bool testStatus = runLoadUnloadTest("FrameSL10a", 1, libA2, events); + US_TEST_CONDITION(testStatus, "FrameSL10a") +} + +void frameSL25a() +{ + ModuleContext* mc = GetModuleContext(); + + TestServiceListener sListen(mc, false); + try + { + mc->AddServiceListener(&sListen, &TestServiceListener::serviceChanged); + } + catch (const std::logic_error& ise) + { + US_TEST_OUTPUT( << "service listener registration failed " << ise.what() ); + throw; + } + + SharedLibrary libSL1(LIB_PATH, "TestModuleSL1"); + SharedLibrary libSL3(LIB_PATH, "TestModuleSL3"); + SharedLibrary libSL4(LIB_PATH, "TestModuleSL4"); + + std::vector expectedServiceEventTypes; + + // Startup + expectedServiceEventTypes.push_back(ServiceEvent::REGISTERED); // at start of libSL1 + expectedServiceEventTypes.push_back(ServiceEvent::REGISTERED); // FooService at start of libSL4 + expectedServiceEventTypes.push_back(ServiceEvent::REGISTERED); // at start of libSL3 + + // Stop libSL4 + expectedServiceEventTypes.push_back(ServiceEvent::UNREGISTERING); // FooService at first stop of libSL4 + +#ifdef US_BUILD_SHARED_LIBS + // Shutdown + expectedServiceEventTypes.push_back(ServiceEvent::UNREGISTERING); // at stop of libSL1 + expectedServiceEventTypes.push_back(ServiceEvent::UNREGISTERING); // at stop of libSL3 +#endif + + // Start libModuleTestSL1 to ensure that the Service interface is available. + try + { + US_TEST_OUTPUT( << "Starting libModuleTestSL1: " << libSL1.GetFilePath() ); + libSL1.Load(); + } + catch (const std::exception& e) + { + US_TEST_OUTPUT( << "Failed to load module, got exception: " << e.what() ); + throw; + } + + // Start libModuleTestSL4 that will require the serivce interface and publish + // us::FooService + try + { + US_TEST_OUTPUT( << "Starting libModuleTestSL4: " << libSL4.GetFilePath() ); + libSL4.Load(); + } + catch (const std::exception& e) + { + US_TEST_OUTPUT( << "Failed to load module, got exception: " << e.what() ); + throw; + } + + // Start libModuleTestSL3 that will require the serivce interface and get the service + try + { + US_TEST_OUTPUT( << "Starting libModuleTestSL3: " << libSL3.GetFilePath() ); + libSL3.Load(); + } + catch (const std::exception& e) + { + US_TEST_OUTPUT( << "Failed to load module, got exception: " << e.what() ); + throw; + } + + // Check that libSL3 has been notified about the FooService. + US_TEST_OUTPUT( << "Check that FooService is added to service tracker in libSL3" ); + try + { + ServiceReferenceU libSL3SR = mc->GetServiceReference("ActivatorSL3"); + InterfaceMap libSL3Activator = mc->GetService(libSL3SR); + US_TEST_CONDITION_REQUIRED(!libSL3Activator.empty(), "ActivatorSL3 service != 0"); + + ServiceReference libSL3PropsI(libSL3SR); + ModulePropsInterface* propsInterface = mc->GetService(libSL3PropsI); + US_TEST_CONDITION_REQUIRED(propsInterface, "ModulePropsInterface != 0"); + + ModulePropsInterface::Properties::const_iterator i = propsInterface->GetProperties().find("serviceAdded"); + US_TEST_CONDITION_REQUIRED(i != propsInterface->GetProperties().end(), "Property serviceAdded"); + Any serviceAddedField3 = i->second; + US_TEST_CONDITION_REQUIRED(!serviceAddedField3.Empty() && any_cast(serviceAddedField3), + "libSL3 notified about presence of FooService"); + mc->UngetService(libSL3SR); + } + catch (const ServiceException& se) + { + US_TEST_FAILED_MSG( << "Failed to get service reference:" << se ); + } + + // Check that libSL1 has been notified about the FooService. + US_TEST_OUTPUT( << "Check that FooService is added to service tracker in libSL1" ); + try + { + ServiceReferenceU libSL1SR = mc->GetServiceReference("ActivatorSL1"); + InterfaceMap libSL1Activator = mc->GetService(libSL1SR); + US_TEST_CONDITION_REQUIRED(!libSL1Activator.empty(), "ActivatorSL1 service != 0"); + + ServiceReference libSL1PropsI(libSL1SR); + ModulePropsInterface* propsInterface = mc->GetService(libSL1PropsI); + US_TEST_CONDITION_REQUIRED(propsInterface, "Cast to ModulePropsInterface"); + + ModulePropsInterface::Properties::const_iterator i = propsInterface->GetProperties().find("serviceAdded"); + US_TEST_CONDITION_REQUIRED(i != propsInterface->GetProperties().end(), "Property serviceAdded"); + Any serviceAddedField1 = i->second; + US_TEST_CONDITION_REQUIRED(!serviceAddedField1.Empty() && any_cast(serviceAddedField1), + "libSL1 notified about presence of FooService"); + mc->UngetService(libSL1SR); + } + catch (const ServiceException& se) + { + US_TEST_FAILED_MSG( << "Failed to get service reference:" << se ); + } + + // Stop the service provider: libSL4 + try + { + US_TEST_OUTPUT( << "Stop libSL4: " << libSL4.GetFilePath() ); + libSL4.Unload(); + } + catch (const std::exception& e) + { + US_TEST_OUTPUT( << "Failed to unload module, got exception:" << e.what() ); + throw; + } + + // Check that libSL3 has been notified about the removal of FooService. + US_TEST_OUTPUT( << "Check that FooService is removed from service tracker in libSL3" ); + try + { + ServiceReferenceU libSL3SR = mc->GetServiceReference("ActivatorSL3"); + InterfaceMap libSL3Activator = mc->GetService(libSL3SR); + US_TEST_CONDITION_REQUIRED(!libSL3Activator.empty(), "ActivatorSL3 service != 0"); + + ServiceReference libSL3PropsI(libSL3SR); + ModulePropsInterface* propsInterface = mc->GetService(libSL3PropsI); + US_TEST_CONDITION_REQUIRED(propsInterface, "Cast to ModulePropsInterface"); + + ModulePropsInterface::Properties::const_iterator i = propsInterface->GetProperties().find("serviceRemoved"); + US_TEST_CONDITION_REQUIRED(i != propsInterface->GetProperties().end(), "Property serviceRemoved"); + + Any serviceRemovedField3 = i->second; + US_TEST_CONDITION(!serviceRemovedField3.Empty() && any_cast(serviceRemovedField3), + "libSL3 notified about removal of FooService"); + mc->UngetService(libSL3SR); + } + catch (const ServiceException& se) + { + US_TEST_FAILED_MSG( << "Failed to get service reference:" << se ); + } + + // Stop libSL1 + try + { + US_TEST_OUTPUT( << "Stop libSL1:" << libSL1.GetFilePath() ); + libSL1.Unload(); + } + catch (const std::exception& e) + { + US_TEST_OUTPUT( << "Failed to unload module got exception" << e.what() ); + throw; + } + + // Stop pSL3 + try + { + US_TEST_OUTPUT( << "Stop libSL3:" << libSL3.GetFilePath() ); + libSL3.Unload(); + } + catch (const std::exception& e) + { + US_TEST_OUTPUT( << "Failed to unload module got exception" << e.what() ); + throw; + } + + // Check service events seen by this class + US_TEST_OUTPUT( << "Checking ServiceEvents(ServiceListener):" ); + if (!sListen.checkEvents(expectedServiceEventTypes)) + { + US_TEST_FAILED_MSG( << "Service listener event notification error" ); + } + + US_TEST_CONDITION_REQUIRED(sListen.getTestStatus(), "Service listener checks"); + try + { + mc->RemoveServiceListener(&sListen, &TestServiceListener::serviceChanged); + sListen.clearEvents(); + } + catch (const std::logic_error& ise) + { + US_TEST_FAILED_MSG( << "service listener removal failed: " << ise.what() ); + } + +} + +int usServiceListenerTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ServiceListenerTest"); + + frameSL02a(); + frameSL05a(); + frameSL10a(); + frameSL25a(); + + US_TEST_END() +} diff --git a/test/usServiceRegistryPerformanceTest.cpp b/test/usServiceRegistryPerformanceTest.cpp new file mode 100644 index 0000000000..8de3197608 --- /dev/null +++ b/test/usServiceRegistryPerformanceTest.cpp @@ -0,0 +1,424 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usTestingMacros.h" + +#include +#include + +US_USE_NAMESPACE + +#ifdef US_PLATFORM_APPLE +#include +#elif defined(US_PLATFORM_POSIX) +#include +#include +#ifndef _POSIX_MONOTONIC_CLOCK +#error Monotonic clock support missing on this POSIX platform +#endif +#elif defined(US_PLATFORM_WINDOWS) +#include +#else +#error High precision timer support nod available on this platform +#endif + +#include + +class HighPrecisionTimer +{ + +public: + + inline HighPrecisionTimer(); + + inline void Start(); + + inline long long ElapsedMilli(); + + inline long long ElapsedMicro(); + +private: + +#ifdef US_PLATFORM_APPLE + static double timeConvert; + uint64_t startTime; +#elif defined(US_PLATFORM_POSIX) + timespec startTime; +#elif defined(US_PLATFORM_WINDOWS) + LARGE_INTEGER timerFrequency; + LARGE_INTEGER startTime; +#endif +}; + +#ifdef US_PLATFORM_APPLE + +double HighPrecisionTimer::timeConvert = 0.0; + +inline HighPrecisionTimer::HighPrecisionTimer() +: startTime(0) +{ + if (timeConvert == 0) + { + mach_timebase_info_data_t timeBase; + mach_timebase_info(&timeBase); + timeConvert = static_cast(timeBase.numer) / static_cast(timeBase.denom) / 1000.0; + } +} + +inline void HighPrecisionTimer::Start() +{ + startTime = mach_absolute_time(); +} + +inline long long HighPrecisionTimer::ElapsedMilli() +{ + uint64_t current = mach_absolute_time(); + return static_cast(current - startTime) * timeConvert / 1000.0; +} + +inline long long HighPrecisionTimer::ElapsedMicro() +{ + uint64_t current = mach_absolute_time(); + return static_cast(current - startTime) * timeConvert; +} + +#elif defined(US_PLATFORM_POSIX) + +inline HighPrecisionTimer::HighPrecisionTimer() +{ + startTime.tv_nsec = 0; + startTime.tv_sec = 0; +} + +inline void HighPrecisionTimer::Start() +{ + clock_gettime(CLOCK_MONOTONIC, &startTime); +} + +inline long long HighPrecisionTimer::ElapsedMilli() +{ + timespec current; + clock_gettime(CLOCK_MONOTONIC, ¤t); + return (static_cast(current.tv_sec)*1000 + current.tv_nsec/1000/1000) - + (static_cast(startTime.tv_sec)*1000 + startTime.tv_nsec/1000/1000); +} + +inline long long HighPrecisionTimer::ElapsedMicro() +{ + timespec current; + clock_gettime(CLOCK_MONOTONIC, ¤t); + return (static_cast(current.tv_sec)*1000*1000 + current.tv_nsec/1000) - + (static_cast(startTime.tv_sec)*1000*1000 + startTime.tv_nsec/1000); +} + +#elif defined(US_PLATFORM_WINDOWS) + +inline HighPrecisionTimer::HighPrecisionTimer() +{ + if (!QueryPerformanceFrequency(&timerFrequency)) + throw std::runtime_error("QueryPerformanceFrequency() failed"); +} + +inline void HighPrecisionTimer::Start() +{ + //DWORD_PTR oldmask = SetThreadAffinityMask(GetCurrentThread(), 0); + QueryPerformanceCounter(&startTime); + //SetThreadAffinityMask(GetCurrentThread(), oldmask); +} + +inline long long HighPrecisionTimer::ElapsedMilli() +{ + LARGE_INTEGER current; + QueryPerformanceCounter(¤t); + return (current.QuadPart - startTime.QuadPart) / (timerFrequency.QuadPart / 1000); +} + +inline long long HighPrecisionTimer::ElapsedMicro() +{ + LARGE_INTEGER current; + QueryPerformanceCounter(¤t); + return (current.QuadPart - startTime.QuadPart) / (timerFrequency.QuadPart / (1000*1000)); +} + +#endif + +class MyServiceListener; + +struct IPerfTestService +{ + virtual ~IPerfTestService() {} +}; + +US_DECLARE_SERVICE_INTERFACE(IPerfTestService, "org.cppmicroservices.test.IPerfTestService") + + +class ServiceRegistryPerformanceTest +{ + +private: + + friend class MyServiceListener; + + ModuleContext* mc; + + int nListeners; + int nServices; + + std::size_t nRegistered; + std::size_t nUnregistering; + std::size_t nModified; + + std::vector > regs; + std::vector listeners; + std::vector services; + +public: + + ServiceRegistryPerformanceTest(ModuleContext* context); + + void InitTestCase(); + void CleanupTestCase(); + + void TestAddListeners(); + void TestRegisterServices(); + + void TestModifyServices(); + void TestUnregisterServices(); + +private: + + std::ostream& Log() const + { + return std::cout; + } + + void AddListeners(int n); + void RegisterServices(int n); + void ModifyServices(); + void UnregisterServices(); + +}; + +class MyServiceListener +{ + +private: + + ServiceRegistryPerformanceTest* ts; + +public: + + MyServiceListener(ServiceRegistryPerformanceTest* ts) + : ts(ts) + { + } + + void ServiceChanged(const ServiceEvent ev) + { + switch(ev.GetType()) + { + case ServiceEvent::REGISTERED: + ts->nRegistered++; + break; + case ServiceEvent::UNREGISTERING: + ts->nUnregistering++; + break; + case ServiceEvent::MODIFIED: + ts->nModified++; + break; + default: + break; + } + } +}; + + +ServiceRegistryPerformanceTest::ServiceRegistryPerformanceTest(ModuleContext* context) + : mc(context) + , nListeners(100) + , nServices(1000) + , nRegistered(0) + , nUnregistering(0) + , nModified(0) +{ +} + +void ServiceRegistryPerformanceTest::InitTestCase() +{ + Log() << "Initialize event counters\n"; + + nRegistered = 0; + nUnregistering = 0; + nModified = 0; +} + +void ServiceRegistryPerformanceTest::CleanupTestCase() +{ + Log() << "Remove all service listeners\n"; + + for(std::size_t i = 0; i < listeners.size(); i++) + { + try + { + MyServiceListener* l = listeners[i]; + mc->RemoveServiceListener(l, &MyServiceListener::ServiceChanged); + delete l; + } + catch (const std::exception& e) + { + Log() << e.what(); + } + } + listeners.clear(); +} + +void ServiceRegistryPerformanceTest::TestAddListeners() +{ + AddListeners(nListeners); +} + +void ServiceRegistryPerformanceTest::AddListeners(int n) +{ + Log() << "adding " << n << " service listeners\n"; + for(int i = 0; i < n; i++) + { + MyServiceListener* l = new MyServiceListener(this); + try + { + listeners.push_back(l); + mc->AddServiceListener(l, &MyServiceListener::ServiceChanged, "(perf.service.value>=0)"); + } + catch (const std::exception& e) + { + Log() << e.what(); + } + } + Log() << "listener count=" << listeners.size() << "\n"; +} + +void ServiceRegistryPerformanceTest::TestRegisterServices() +{ + Log() << "Register services, and check that we get #of services (" + << nServices << ") * #of listeners (" << nListeners << ") REGISTERED events\n"; + + Log() << "registering " << nServices << " services, listener count=" << listeners.size() << "\n"; + + HighPrecisionTimer t; + t.Start(); + RegisterServices(nServices); + long long ms = t.ElapsedMilli(); + Log() << "register took " << ms << "ms\n"; + US_TEST_CONDITION_REQUIRED(nServices * listeners.size() == nRegistered, + "# REGISTERED events must be same as # of registered services * # of listeners"); +} + +void ServiceRegistryPerformanceTest::RegisterServices(int n) +{ + class PerfTestService : public IPerfTestService + { + }; + + std::string pid("my.service."); + + for(int i = 0; i < n; i++) + { + ServiceProperties props; + std::stringstream ss; + ss << pid << i; + props["service.pid"] = ss.str(); + props["perf.service.value"] = i+1; + + PerfTestService* service = new PerfTestService(); + services.push_back(service); + ServiceRegistration reg = + mc->RegisterService(service, props); + regs.push_back(reg); + } +} + +void ServiceRegistryPerformanceTest::TestModifyServices() +{ + Log() << "Modify all services, and check that we get #of services (" + << nServices << ") * #of listeners (" << nListeners << ") MODIFIED events\n"; + + HighPrecisionTimer t; + t.Start(); + ModifyServices(); + long long ms = t.ElapsedMilli(); + Log() << "modify took " << ms << "ms\n"; + US_TEST_CONDITION_REQUIRED(nServices * listeners.size() == nModified, + "# MODIFIED events must be same as # of modified services * # of listeners"); +} + +void ServiceRegistryPerformanceTest::ModifyServices() +{ + Log() << "modifying " << regs.size() << " services, listener count=" << listeners.size() << "\n"; + + for(std::size_t i = 0; i < regs.size(); i++) + { + ServiceRegistration reg = regs[i]; + ServiceProperties props; + props["perf.service.value"] = i * 2; + reg.SetProperties(props); + } +} + +void ServiceRegistryPerformanceTest::TestUnregisterServices() +{ + Log() << "Unregister all services, and check that we get #of services (" + << nServices << ") * #of listeners (" << nListeners + << ") UNREGISTERING events\n"; + + HighPrecisionTimer t; + t.Start(); + UnregisterServices(); + long long ms = t.ElapsedMilli(); + Log() << "unregister took " << ms << "ms\n"; + US_TEST_CONDITION_REQUIRED(nServices * listeners.size() == nUnregistering, "# UNREGISTERING events must be same as # of (un)registered services * # of listeners"); +} + +void ServiceRegistryPerformanceTest::UnregisterServices() +{ + Log() << "unregistering " << regs.size() << " services, listener count=" + << listeners.size() << "\n"; + for(std::size_t i = 0; i < regs.size(); i++) + { + ServiceRegistration reg = regs[i]; + reg.Unregister(); + } + regs.clear(); +} + + +int usServiceRegistryPerformanceTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ServiceRegistryPerformanceTest") + + ServiceRegistryPerformanceTest perfTest(GetModuleContext()); + perfTest.InitTestCase(); + perfTest.TestAddListeners(); + perfTest.TestRegisterServices(); + perfTest.TestModifyServices(); + perfTest.TestUnregisterServices(); + perfTest.CleanupTestCase(); + + US_TEST_END() +} diff --git a/test/usServiceRegistryTest.cpp b/test/usServiceRegistryTest.cpp new file mode 100644 index 0000000000..bd15ed18f2 --- /dev/null +++ b/test/usServiceRegistryTest.cpp @@ -0,0 +1,135 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +#include "usTestingMacros.h" +#include +#include +#include + +#include + +US_USE_NAMESPACE + +struct ITestServiceA +{ + virtual ~ITestServiceA() {} +}; + +US_DECLARE_SERVICE_INTERFACE(ITestServiceA, "org.cppmicroservices.testing.ITestServiceA") + +int TestMultipleServiceRegistrations() +{ + struct TestServiceA : public ITestServiceA + { + }; + + ModuleContext* context = GetModuleContext(); + + TestServiceA s1; + TestServiceA s2; + + ServiceRegistration reg1 = context->RegisterService(&s1); + ServiceRegistration reg2 = context->RegisterService(&s2); + + std::vector > refs = context->GetServiceReferences(); + US_TEST_CONDITION_REQUIRED(refs.size() == 2, "Testing for two registered ITestServiceA services") + + reg2.Unregister(); + refs = context->GetServiceReferences(); + US_TEST_CONDITION_REQUIRED(refs.size() == 1, "Testing for one registered ITestServiceA services") + + reg1.Unregister(); + refs = context->GetServiceReferences(); + US_TEST_CONDITION_REQUIRED(refs.empty(), "Testing for no ITestServiceA services") + + return EXIT_SUCCESS; +} + +int TestServicePropertiesUpdate() +{ + struct TestServiceA : public ITestServiceA + { + }; + + ModuleContext* context = GetModuleContext(); + + TestServiceA s1; + ServiceProperties props; + props["string"] = std::string("A std::string"); + props["bool"] = false; + const char* str = "A const char*"; + props["const char*"] = str; + + ServiceRegistration reg1 = context->RegisterService(&s1, props); + ServiceReference ref1 = context->GetServiceReference(); + + US_TEST_CONDITION_REQUIRED(context->GetServiceReferences().size() == 1, "Testing service count") + US_TEST_CONDITION_REQUIRED(any_cast(ref1.GetProperty("bool")) == false, "Testing bool property") + + // register second service with higher rank + TestServiceA s2; + ServiceProperties props2; + props2[ServiceConstants::SERVICE_RANKING()] = 50; + + ServiceRegistration reg2 = context->RegisterService(&s2, props2); + + // Get the service with the highest rank, this should be s2. + ServiceReference ref2 = context->GetServiceReference(); + TestServiceA* service = dynamic_cast(context->GetService(ref2)); + US_TEST_CONDITION_REQUIRED(service == &s2, "Testing highest service rank") + + props["bool"] = true; + // change the service ranking + props[ServiceConstants::SERVICE_RANKING()] = 100; + reg1.SetProperties(props); + + US_TEST_CONDITION_REQUIRED(context->GetServiceReferences().size() == 2, "Testing service count") + US_TEST_CONDITION_REQUIRED(any_cast(ref1.GetProperty("bool")) == true, "Testing bool property") + US_TEST_CONDITION_REQUIRED(any_cast(ref1.GetProperty(ServiceConstants::SERVICE_RANKING())) == 100, "Testing updated ranking") + + // Service with the highest ranking should now be s1 + service = dynamic_cast(context->GetService(ref1)); + US_TEST_CONDITION_REQUIRED(service == &s1, "Testing highest service rank") + + reg1.Unregister(); + US_TEST_CONDITION_REQUIRED(context->GetServiceReferences("").size() == 1, "Testing service count") + + service = dynamic_cast(context->GetService(ref2)); + US_TEST_CONDITION_REQUIRED(service == &s2, "Testing highest service rank") + + reg2.Unregister(); + US_TEST_CONDITION_REQUIRED(context->GetServiceReferences().empty(), "Testing service count") + + return EXIT_SUCCESS; +} + + +int usServiceRegistryTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ServiceRegistryTest"); + + US_TEST_CONDITION(TestMultipleServiceRegistrations() == EXIT_SUCCESS, "Testing service registrations: ") + US_TEST_CONDITION(TestServicePropertiesUpdate() == EXIT_SUCCESS, "Testing service property update: ") + + US_TEST_END() +} diff --git a/test/usServiceTemplateTest.cpp b/test/usServiceTemplateTest.cpp new file mode 100644 index 0000000000..783ebfa8d5 --- /dev/null +++ b/test/usServiceTemplateTest.cpp @@ -0,0 +1,211 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include + +#include "usTestingMacros.h" + +struct Interface1 {}; +US_DECLARE_SERVICE_INTERFACE(Interface1, "org.cppmicroservices.test.Interface1") +struct Interface2 {}; +US_DECLARE_SERVICE_INTERFACE(Interface2, "org.cppmicroservices.test.Interface2") +struct Interface3 {}; +US_DECLARE_SERVICE_INTERFACE(Interface3, "org.cppmicroservices.test.Interface3") + +struct MyService1 : public Interface1 +{}; + +struct MyService2 : public Interface1, public Interface2 +{}; + +struct MyService3 : public Interface1, public Interface2, public Interface3 +{}; + +struct MyFactory1 : public us::ServiceFactory +{ + std::map m_idToServiceMap; + + virtual us::InterfaceMap GetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/) + { + MyService1* s = new MyService1; + m_idToServiceMap.insert(std::make_pair(module->GetModuleId(), s)); + return us::MakeInterfaceMap(s); + } + + virtual void UngetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/, + const us::InterfaceMap& service) + { + std::map::iterator iter = m_idToServiceMap.find(module->GetModuleId()); + if (iter != m_idToServiceMap.end()) + { + US_TEST_CONDITION(static_cast(iter->second) == us::ExtractInterface(service), "Compare service pointer") + delete iter->second; + m_idToServiceMap.erase(iter); + } + } +}; + +struct MyFactory2 : public us::ServiceFactory +{ + std::map m_idToServiceMap; + + virtual us::InterfaceMap GetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/) + { + MyService2* s = new MyService2; + m_idToServiceMap.insert(std::make_pair(module->GetModuleId(), s)); + return us::MakeInterfaceMap(s); + } + + virtual void UngetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/, + const us::InterfaceMap& service) + { + std::map::iterator iter = m_idToServiceMap.find(module->GetModuleId()); + if (iter != m_idToServiceMap.end()) + { + US_TEST_CONDITION(static_cast(iter->second) == us::ExtractInterface(service), "Compare service pointer") + delete iter->second; + m_idToServiceMap.erase(iter); + } + } +}; + +struct MyFactory3 : public us::ServiceFactory +{ + std::map m_idToServiceMap; + + virtual us::InterfaceMap GetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/) + { + MyService3* s = new MyService3; + m_idToServiceMap.insert(std::make_pair(module->GetModuleId(), s)); + return us::MakeInterfaceMap(s); + } + + virtual void UngetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/, + const us::InterfaceMap& service) + { + std::map::iterator iter = m_idToServiceMap.find(module->GetModuleId()); + if (iter != m_idToServiceMap.end()) + { + US_TEST_CONDITION(static_cast(iter->second) == us::ExtractInterface(service), "Compare service pointer") + delete iter->second; + m_idToServiceMap.erase(iter); + } + } +}; + + +US_USE_NAMESPACE + +int usServiceTemplateTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ServiceTemplateTest"); + + ModuleContext* mc = GetModuleContext(); + + // Register compile tests + MyService1 s1; + MyService2 s2; + MyService3 s3; + + us::ServiceRegistration sr1 = mc->RegisterService(&s1); + us::ServiceRegistration sr2 = mc->RegisterService(&s2); + us::ServiceRegistration sr3 = mc->RegisterService(&s3); + + MyFactory1 f1; + us::ServiceRegistration sfr1 = mc->RegisterService(&f1); + + MyFactory2 f2; + us::ServiceRegistration sfr2 = mc->RegisterService(static_cast(&f2)); + + MyFactory3 f3; + us::ServiceRegistration sfr3 = mc->RegisterService(static_cast(&f3)); + +#ifdef US_BUILD_SHARED_LIBS + US_TEST_CONDITION(mc->GetModule()->GetRegisteredServices().size() == 6, "# of reg services") +#endif + + std::vector > s1refs = mc->GetServiceReferences(); + US_TEST_CONDITION(s1refs.size() == 6, "# of interface1 regs") + std::vector > s2refs = mc->GetServiceReferences(); + US_TEST_CONDITION(s2refs.size() == 4, "# of interface2 regs") + std::vector > s3refs = mc->GetServiceReferences(); + US_TEST_CONDITION(s3refs.size() == 2, "# of interface3 regs") + + Interface1* i1 = mc->GetService(sr1.GetReference()); + US_TEST_CONDITION(i1 == static_cast(&s1), "interface1 ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sr1.GetReference()), "unget interface1 ptr") + i1 = mc->GetService(sfr1.GetReference()); + US_TEST_CONDITION(i1 == static_cast(f1.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface1 factory ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr1.GetReference()), "unget interface1 factory ptr") + + i1 = mc->GetService(sr2.GetReference(InterfaceT())); + US_TEST_CONDITION(i1 == static_cast(&s2), "interface1 ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sr2.GetReference(InterfaceT())), "unget interface1 ptr") + i1 = mc->GetService(sfr2.GetReference(InterfaceT())); + US_TEST_CONDITION(i1 == static_cast(f2.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface1 factory ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr2.GetReference(InterfaceT())), "unget interface1 factory ptr") + Interface2* i2 = mc->GetService(sr2.GetReference(InterfaceT())); + US_TEST_CONDITION(i2 == static_cast(&s2), "interface2 ptr") + i2 = NULL; + US_TEST_CONDITION(mc->UngetService(sr2.GetReference(InterfaceT())), "unget interface2 ptr") + i2 = mc->GetService(sfr2.GetReference(InterfaceT())); + US_TEST_CONDITION(i2 == static_cast(f2.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface2 factory ptr") + i2 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr2.GetReference(InterfaceT())), "unget interface2 factory ptr") + + i1 = mc->GetService(sr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i1 == static_cast(&s3), "interface1 ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sr3.GetReference(InterfaceT())), "unget interface1 ptr") + i1 = mc->GetService(sfr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i1 == static_cast(f3.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface1 factory ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr3.GetReference(InterfaceT())), "unget interface1 factory ptr") + i2 = mc->GetService(sr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i2 == static_cast(&s3), "interface2 ptr") + i2 = NULL; + US_TEST_CONDITION(mc->UngetService(sr3.GetReference(InterfaceT())), "unget interface2 ptr") + i2 = mc->GetService(sfr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i2 == static_cast(f3.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface2 factory ptr") + i2 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr3.GetReference(InterfaceT())), "unget interface2 factory ptr") + Interface3* i3 = mc->GetService(sr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i3 == static_cast(&s3), "interface3 ptr") + i3 = NULL; + US_TEST_CONDITION(mc->UngetService(sr3.GetReference(InterfaceT())), "unget interface3 ptr") + i3 = mc->GetService(sfr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i3 == static_cast(f3.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface3 factory ptr") + i3 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr3.GetReference(InterfaceT())), "unget interface3 factory ptr") + + sr1.Unregister(); + sr2.Unregister(); + sr3.Unregister(); + + US_TEST_END() +} diff --git a/test/usServiceTrackerTest.cpp b/test/usServiceTrackerTest.cpp new file mode 100644 index 0000000000..d602d4bd02 --- /dev/null +++ b/test/usServiceTrackerTest.cpp @@ -0,0 +1,223 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "usServiceControlInterface.h" + +#include + +US_USE_NAMESPACE + +bool CheckConvertibility(const std::vector& refs, + std::vector::const_iterator idBegin, + std::vector::const_iterator idEnd) +{ + std::vector ids; + ids.assign(idBegin, idEnd); + + for (std::vector::const_iterator sri = refs.begin(); + sri != refs.end(); ++sri) + { + for (std::vector::iterator idIter = ids.begin(); + idIter != ids.end(); ++idIter) + { + if (sri->IsConvertibleTo(*idIter)) + { + ids.erase(idIter); + break; + } + } + } + + return ids.empty(); +} + + +int usServiceTrackerTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ServiceTrackerTest") + +#ifdef US_PLATFORM_WINDOWS + const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + + ModuleContext* mc = GetModuleContext(); + SharedLibrary libS(LIB_PATH, "TestModuleS"); + +#ifdef US_BUILD_SHARED_LIBS + // Start the test target to get a service published. + try + { + libS.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what() ); + } +#endif + + // 1. Create a ServiceTracker with ServiceTrackerCustomizer == null + + std::string s1("org.cppmicroservices.TestModuleSService"); + ServiceReferenceU servref = mc->GetServiceReference(s1 + "0"); + + US_TEST_CONDITION_REQUIRED(servref != 0, "Test if registered service of id org.cppmicroservices.TestModuleSService0"); + + ServiceReference servCtrlRef = mc->GetServiceReference(); + US_TEST_CONDITION_REQUIRED(servCtrlRef != 0, "Test if constrol service was registered"); + + ServiceControlInterface* serviceController = mc->GetService(servCtrlRef); + US_TEST_CONDITION_REQUIRED(serviceController != 0, "Test valid service controller"); + + std::auto_ptr > st1(new ServiceTracker(mc, servref)); + + // 2. Check the size method with an unopened service tracker + + US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Test if size == 0"); + + // 3. Open the service tracker and see what it finds, + // expect to find one instance of the implementation, + // "org.cppmicroservices.TestModuleSService0" + + st1->Open(); + std::vector sa2; + st1->GetServiceReferences(sa2); + + US_TEST_CONDITION_REQUIRED(sa2.size() == 1, "Checking ServiceTracker size"); + US_TEST_CONDITION_REQUIRED(s1 + "0" == sa2[0].GetInterfaceId(), "Checking service implementation name"); + + // 5. Close this service tracker + st1->Close(); + + // 6. Check the size method, now when the servicetracker is closed + US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Checking ServiceTracker size"); + + // 7. Check if we still track anything , we should get null + sa2.clear(); + st1->GetServiceReferences(sa2); + US_TEST_CONDITION_REQUIRED(sa2.empty(), "Checking ServiceTracker size"); + + // 8. A new Servicetracker, this time with a filter for the object + std::string fs = std::string("(") + ServiceConstants::OBJECTCLASS() + "=" + s1 + "*" + ")"; + LDAPFilter f1(fs); + st1.reset(new ServiceTracker(mc, f1)); + // add a service + serviceController->ServiceControl(1, "register", 7); + + // 9. Open the service tracker and see what it finds, + // expect to find two instances of references to + // "org.cppmicroservices.TestModuleSService*" + // i.e. they refer to the same piece of code + + std::vector ids; + ids.push_back((s1 + "0")); + ids.push_back((s1 + "1")); + ids.push_back((s1 + "2")); + ids.push_back((s1 + "3")); + + st1->Open(); + sa2.clear(); + st1->GetServiceReferences(sa2); + US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Checking service reference count"); + US_TEST_CONDITION_REQUIRED(CheckConvertibility(sa2, ids.begin(), ids.begin()+2), "Check for expected interface id [0]"); + US_TEST_CONDITION_REQUIRED(sa2[1].IsConvertibleTo(s1 + "1"), "Check for expected interface id [1]"); + + // 10. Get libTestModuleS to register one more service and see if it appears + serviceController->ServiceControl(2, "register", 1); + sa2.clear(); + st1->GetServiceReferences(sa2); + + US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count"); + + US_TEST_CONDITION_REQUIRED(CheckConvertibility(sa2, ids.begin(), ids.begin()+3), "Check for expected interface id [2]"); + + // 11. Get libTestModuleS to register one more service and see if it appears + serviceController->ServiceControl(3, "register", 2); + sa2.clear(); + st1->GetServiceReferences(sa2); + US_TEST_CONDITION_REQUIRED(sa2.size() == 4, "Checking service reference count"); + US_TEST_CONDITION_REQUIRED(CheckConvertibility(sa2, ids.begin(), ids.end()), "Check for expected interface id [3]"); + + // 12. Get libTestModuleS to unregister one service and see if it disappears + serviceController->ServiceControl(3, "unregister", 0); + sa2.clear(); + st1->GetServiceReferences(sa2); + US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count"); + + // 13. Get the highest ranking service reference, it should have ranking 7 + ServiceReferenceU h1 = st1->GetServiceReference(); + int rank = any_cast(h1.GetProperty(ServiceConstants::SERVICE_RANKING())); + US_TEST_CONDITION_REQUIRED(rank == 7, "Check service rank"); + + // 14. Get the service of the highest ranked service reference + + InterfaceMap o1 = st1->GetService(h1); + US_TEST_CONDITION_REQUIRED(!o1.empty(), "Check for non-null service"); + + // 14a Get the highest ranked service, directly this time + InterfaceMap o3 = st1->GetService(); + US_TEST_CONDITION_REQUIRED(!o3.empty(), "Check for non-null service"); + US_TEST_CONDITION_REQUIRED(o1 == o3, "Check for equal service instances"); + + // 15. Now release the tracking of that service and then try to get it + // from the servicetracker, which should yield a null object + serviceController->ServiceControl(1, "unregister", 7); + InterfaceMap o2 = st1->GetService(h1); + US_TEST_CONDITION_REQUIRED(o2.empty(), "Checkt that service is null"); + + // 16. Get all service objects this tracker tracks, it should be 2 + std::vector ts1; + st1->GetServices(ts1); + US_TEST_CONDITION_REQUIRED(ts1.size() == 2, "Check service count"); + + // 17. Test the remove method. + // First register another service, then remove it being tracked + serviceController->ServiceControl(1, "register", 7); + h1 = st1->GetServiceReference(); + std::vector sa3; + st1->GetServiceReferences(sa3); + US_TEST_CONDITION_REQUIRED(sa3.size() == 3, "Check service reference count"); + US_TEST_CONDITION_REQUIRED(CheckConvertibility(sa3, ids.begin(), ids.begin()+3), "Check for expected interface id [0]"); + + st1->Remove(h1); // remove tracking on one servref + sa2.clear(); + st1->GetServiceReferences(sa2); + US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Check service reference count"); + + // 18. Test the addingService method,add a service reference + + // 19. Test the removedService method, remove a service reference + + + // 20. Test the waitForService method + InterfaceMap o9 = st1->WaitForService(50); + US_TEST_CONDITION_REQUIRED(!o9.empty(), "Checking WaitForService method"); + + US_TEST_END() +} diff --git a/test/usSharedLibraryTest.cpp b/test/usSharedLibraryTest.cpp new file mode 100644 index 0000000000..862ae23479 --- /dev/null +++ b/test/usSharedLibraryTest.cpp @@ -0,0 +1,118 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +#include "usTestingMacros.h" +#include "usTestingConfig.h" + +#include +#include + +US_USE_NAMESPACE + +int usSharedLibraryTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("SharedLibraryTest"); + +#ifdef US_PLATFORM_WINDOWS + const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; + const std::string LIB_PREFIX = ""; + const std::string LIB_SUFFIX = ".dll"; + const char PATH_SEPARATOR = '\\'; +#elif defined(US_PLATFORM_APPLE) + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; + const std::string LIB_PREFIX = "lib"; + const std::string LIB_SUFFIX = ".dylib"; + const char PATH_SEPARATOR = '/'; +#else + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; + const std::string LIB_PREFIX = "lib"; + const std::string LIB_SUFFIX = ".so"; + const char PATH_SEPARATOR = '/'; + +#endif + + const std::string libAFilePath = LIB_PATH + PATH_SEPARATOR + LIB_PREFIX + "TestModuleA" + LIB_SUFFIX; + SharedLibrary lib1(libAFilePath); + US_TEST_CONDITION(lib1.GetFilePath() == libAFilePath, "Absolute file path") + US_TEST_CONDITION(lib1.GetLibraryPath() == LIB_PATH, "Library path") + US_TEST_CONDITION(lib1.GetName() == "TestModuleA", "Name") + US_TEST_CONDITION(lib1.GetPrefix() == LIB_PREFIX, "Prefix") + US_TEST_CONDITION(lib1.GetSuffix() == LIB_SUFFIX, "Suffix") + lib1.SetName("bla"); + US_TEST_CONDITION(lib1.GetName() == "TestModuleA", "Name after SetName()") + lib1.SetLibraryPath("bla"); + US_TEST_CONDITION(lib1.GetLibraryPath() == LIB_PATH, "Library path after SetLibraryPath()") + lib1.SetPrefix("bla"); + US_TEST_CONDITION(lib1.GetPrefix() == LIB_PREFIX, "Prefix after SetPrefix()") + lib1.SetSuffix("bla"); + US_TEST_CONDITION(lib1.GetSuffix() == LIB_SUFFIX, "Suffix after SetSuffix()") + US_TEST_CONDITION(lib1.GetFilePath() == libAFilePath, "File path after setters") + + lib1.SetFilePath("bla"); + US_TEST_CONDITION(lib1.GetFilePath() == "bla", "Invalid file path") + US_TEST_CONDITION(lib1.GetLibraryPath().empty(), "Empty lib path") + US_TEST_CONDITION(lib1.GetName() == "bla", "Invalid file name") + US_TEST_CONDITION(lib1.GetPrefix() == LIB_PREFIX, "Invalid prefix") + US_TEST_CONDITION(lib1.GetSuffix() == LIB_SUFFIX, "Invalid suffix") + + US_TEST_FOR_EXCEPTION(std::runtime_error, lib1.Load()) + US_TEST_CONDITION(lib1.IsLoaded() == false, "Is loaded") + US_TEST_CONDITION(lib1.GetHandle() == NULL, "Handle") + + lib1.SetFilePath(libAFilePath); + lib1.Load(); + US_TEST_CONDITION(lib1.IsLoaded() == true, "Is loaded") + US_TEST_CONDITION(lib1.GetHandle() != NULL, "Handle") + US_TEST_FOR_EXCEPTION(std::logic_error, lib1.Load()) + + lib1.SetFilePath("bla"); + US_TEST_CONDITION(lib1.GetFilePath() == libAFilePath, "File path") + lib1.Unload(); + + + SharedLibrary lib2(LIB_PATH, "TestModuleA"); + US_TEST_CONDITION(lib2.GetFilePath() == libAFilePath, "File path") + lib2.SetPrefix(""); + US_TEST_CONDITION(lib2.GetPrefix().empty(), "Lib prefix") + US_TEST_CONDITION(lib2.GetFilePath() == LIB_PATH + PATH_SEPARATOR + "TestModuleA" + LIB_SUFFIX, "File path") + + SharedLibrary lib3 = lib2; + US_TEST_CONDITION(lib3.GetFilePath() == lib2.GetFilePath(), "Compare file path") + lib3.SetPrefix(LIB_PREFIX); + US_TEST_CONDITION(lib3.GetFilePath() == libAFilePath, "Compare file path") + lib3.Load(); + US_TEST_CONDITION(lib3.IsLoaded(), "lib3 loaded") + US_TEST_CONDITION(!lib2.IsLoaded(), "lib2 not loaded") + lib1 = lib3; + US_TEST_FOR_EXCEPTION(std::logic_error, lib1.Load()) + lib2.SetPrefix(LIB_PREFIX); + lib2.Load(); + + lib3.Unload(); + US_TEST_CONDITION(!lib3.IsLoaded(), "lib3 unloaded") + US_TEST_CONDITION(!lib1.IsLoaded(), "lib3 unloaded") + lib2.Unload(); + lib1.Unload(); + + US_TEST_END() +} diff --git a/test/usStaticModuleResourceTest.cpp b/test/usStaticModuleResourceTest.cpp new file mode 100644 index 0000000000..fd068d07c4 --- /dev/null +++ b/test/usStaticModuleResourceTest.cpp @@ -0,0 +1,157 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include +#include +#include +#include + +#include "usTestingMacros.h" +#include "usTestingConfig.h" + +#include + +#include + +US_USE_NAMESPACE + +namespace { + +std::string GetResourceContent(const ModuleResource& resource) +{ + std::string line; + ModuleResourceStream rs(resource); + std::getline(rs, line); + return line; +} + +struct ResourceComparator { + bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const + { + return mr1 < mr2; + } +}; + +void testResourceOperators(Module* module) +{ + std::vector resources = module->FindResources("", "res.txt", false); + US_TEST_CONDITION_REQUIRED(resources.size() == 2, "Check resource count") + US_TEST_CONDITION(resources[0] != resources[1], "Check non-equality for equally named resources") +} + +void testResourcesWithStaticImport(Module* module) +{ + ModuleResource resource = module->GetResource("res.txt"); + US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid res.txt resource") + std::string line = GetResourceContent(resource); + US_TEST_CONDITION(line == "dynamic resource", "Check dynamic resource content") + + resource = module->GetResource("dynamic.txt"); + US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid dynamic.txt resource") + line = GetResourceContent(resource); + US_TEST_CONDITION(line == "dynamic", "Check dynamic resource content") + + resource = module->GetResource("static.txt"); + US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource") + line = GetResourceContent(resource); + US_TEST_CONDITION(line == "static", "Check dynamic resource content") + + std::vector resources = module->FindResources("", "*.txt", false); + std::stable_sort(resources.begin(), resources.end(), ResourceComparator()); +#ifdef US_BUILD_SHARED_LIBS + US_TEST_CONDITION(resources.size() == 4, "Check imported resource count") + line = GetResourceContent(resources[0]); + US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content") + line = GetResourceContent(resources[1]); + US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content") + line = GetResourceContent(resources[2]); + US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content") + line = GetResourceContent(resources[3]); + US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content") +#else + US_TEST_CONDITION(resources.size() == 6, "Check imported resource count") + line = GetResourceContent(resources[0]); + US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content") + // skip foo.txt + line = GetResourceContent(resources[2]); + US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content") + line = GetResourceContent(resources[3]); + US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content") + // skip special_chars.dummy.txt + line = GetResourceContent(resources[5]); + US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content") +#endif +} + +} // end unnamed namespace + + +int usStaticModuleResourceTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("StaticModuleResourceTest"); + + assert(GetModuleContext()); + + +#ifdef US_BUILD_SHARED_LIBS + +#ifdef US_PLATFORM_WINDOWS + const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + + SharedLibrary libB(LIB_PATH, "TestModuleB"); + + try + { + libB.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) + } + + Module* module = ModuleRegistry::GetModule("TestModuleB Module"); + US_TEST_CONDITION_REQUIRED(module != NULL, "Test for existing module TestModuleB") + + US_TEST_CONDITION(module->GetName() == "TestModuleB Module", "Test module name") +#else + Module* module = GetModuleContext()->GetModule(); +#endif + + testResourceOperators(module); + testResourcesWithStaticImport(module); + +#ifdef US_BUILD_SHARED_LIBS + ModuleResource resource = module->GetResource("static.txt"); + US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource") + + libB.Unload(); + + US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, "Check invalid static.txt resource") +#endif + + US_TEST_END() +} diff --git a/test/usStaticModuleTest.cpp b/test/usStaticModuleTest.cpp new file mode 100644 index 0000000000..d158c6a742 --- /dev/null +++ b/test/usStaticModuleTest.cpp @@ -0,0 +1,195 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "usTestUtilModuleListener.h" +#include "usTestingMacros.h" +#include "usTestingConfig.h" + +US_USE_NAMESPACE + +namespace { + +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + +// Load libTestModuleB and check that it exists and that the service it registers exists, +// also check that the expected events occur +void frame020a(ModuleContext* mc, TestModuleListener& listener, +#ifdef US_BUILD_SHARED_LIBS + SharedLibrary& libB) +{ + try + { + libB.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) + } + + Module* moduleB = ModuleRegistry::GetModule("TestModuleB Module"); + US_TEST_CONDITION_REQUIRED(moduleB != 0, "Test for existing module TestModuleB") + + US_TEST_CONDITION(moduleB->GetName() == "TestModuleB Module", "Test module name") +#else + SharedLibrary& /*libB*/) +{ +#endif + + // Check if libB registered the expected service + try + { + std::vector refs = mc->GetServiceReferences("org.cppmicroservices.TestModuleBService"); + US_TEST_CONDITION_REQUIRED(refs.size() == 2, "Test that both the service from the shared and imported library are regsitered"); + + InterfaceMap o1 = mc->GetService(refs.front()); + US_TEST_CONDITION(!o1.empty(), "Test if first service object found"); + + InterfaceMap o2 = mc->GetService(refs.back()); + US_TEST_CONDITION(!o2.empty(), "Test if second service object found"); + + try + { + US_TEST_CONDITION(mc->UngetService(refs.front()), "Test if Service UnGet for first service returns true"); + US_TEST_CONDITION(mc->UngetService(refs.back()), "Test if Service UnGet for second service returns true"); + } + catch (const std::logic_error le) + { + US_TEST_FAILED_MSG(<< "UnGetService exception: " << le.what()) + } + + // check the listeners for events + std::vector pEvts; +#ifdef US_BUILD_SHARED_LIBS + pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleB)); + pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleB)); +#endif + + std::vector seEvts; +#ifdef US_BUILD_SHARED_LIBS + seEvts.push_back(ServiceEvent(ServiceEvent::REGISTERED, refs.back())); + seEvts.push_back(ServiceEvent(ServiceEvent::REGISTERED, refs.front())); +#endif + + US_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); + + } + catch (const ServiceException& /*se*/) + { + US_TEST_FAILED_MSG(<< "test module, expected service not found"); + } + +#ifdef US_BUILD_SHARED_LIBS + US_TEST_CONDITION(moduleB->IsLoaded() == true, "Test if loaded correctly"); +#endif +} + + +// Unload libB and check for correct events +void frame030b(ModuleContext* mc, TestModuleListener& listener, SharedLibrary& libB) +{ +#ifdef US_BUILD_SHARED_LIBS + Module* moduleB = ModuleRegistry::GetModule("TestModuleB Module"); + US_TEST_CONDITION_REQUIRED(moduleB != 0, "Test for non-null module") +#endif + + std::vector refs + = mc->GetServiceReferences("org.cppmicroservices.TestModuleBService"); + US_TEST_CONDITION(refs.front(), "Test for first valid service reference") + US_TEST_CONDITION(refs.back(), "Test for second valid service reference") + + try + { + libB.Unload(); +#ifdef US_BUILD_SHARED_LIBS + US_TEST_CONDITION(moduleB->IsLoaded() == false, "Test for unloaded state") +#endif + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG(<< "UnLoad module exception: " << e.what()) + } + + std::vector pEvts; +#ifdef US_BUILD_SHARED_LIBS + pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADING, moduleB)); + pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADED, moduleB)); +#endif + + std::vector seEvts; +#ifdef US_BUILD_SHARED_LIBS + seEvts.push_back(ServiceEvent(ServiceEvent::UNREGISTERING, refs.back())); + seEvts.push_back(ServiceEvent(ServiceEvent::UNREGISTERING, refs.front())); +#endif + + US_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); +} + +} // end unnamed namespace + +int usStaticModuleTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("StaticModuleTest"); + + ModuleContext* mc = GetModuleContext(); + TestModuleListener listener; + + 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; + } + + SharedLibrary libB(LIB_PATH, "TestModuleB"); + frame020a(mc, listener, libB); + frame030b(mc, listener, libB); + + mc->RemoveModuleListener(&listener, &TestModuleListener::ModuleChanged); + mc->RemoveServiceListener(&listener, &TestModuleListener::ServiceChanged); + + US_TEST_END() +} diff --git a/test/usTestManager.cpp b/test/usTestManager.cpp new file mode 100644 index 0000000000..100d5b5997 --- /dev/null +++ b/test/usTestManager.cpp @@ -0,0 +1,82 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usTestManager.h" + +#include "usModuleImport.h" + +US_BEGIN_NAMESPACE + +TestManager& TestManager::GetInstance() +{ + static TestManager instance; + return instance; +} + +void TestManager::Initialize() +{ + m_FailedTests = 0; + m_PassedTests = 0; +} + +int TestManager::NumberOfFailedTests() +{ + return m_FailedTests; +} + +int TestManager::NumberOfPassedTests() +{ + return m_PassedTests; +} + +void TestManager::TestFailed() +{ + m_FailedTests++; +} + +void TestManager::TestPassed() +{ + m_PassedTests++; +} + +US_END_NAMESPACE + +#ifndef US_BUILD_SHARED_LIBS +US_IMPORT_MODULE_RESOURCES(CppMicroServices) +US_IMPORT_MODULE(TestModuleA) +US_IMPORT_MODULE(TestModuleA2) +US_IMPORT_MODULE(TestModuleB) +US_IMPORT_MODULE_RESOURCES(TestModuleB) +US_IMPORT_MODULE(TestModuleH) +US_IMPORT_MODULE(TestModuleM) +US_IMPORT_MODULE_RESOURCES(TestModuleM) +US_IMPORT_MODULE(TestModuleR) +US_IMPORT_MODULE_RESOURCES(TestModuleR) +US_IMPORT_MODULE(TestModuleS) +US_IMPORT_MODULE(TestModuleSL1) +US_IMPORT_MODULE(TestModuleSL3) +US_IMPORT_MODULE(TestModuleSL4) + +US_LOAD_IMPORTED_MODULES_INTO_MAIN( + TestModuleA TestModuleA2 TestModuleB TestModuleImportedByB TestModuleH TestModuleM + TestModuleR TestModuleS TestModuleSL1 TestModuleSL3 TestModuleSL4 + ) +#endif diff --git a/test/usTestManager.h b/test/usTestManager.h new file mode 100644 index 0000000000..080198ef5b --- /dev/null +++ b/test/usTestManager.h @@ -0,0 +1,57 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef US_TESTMANAGER_H_INCLUDED +#define US_TESTMANAGER_H_INCLUDED + +#include + +US_BEGIN_NAMESPACE + +class TestManager +{ +public: + + TestManager() : m_FailedTests(0), m_PassedTests(0) {} + virtual ~TestManager() {} + + static TestManager& GetInstance(); + + /** \brief Must be called at the beginning of a test run. */ + void Initialize(); + + int NumberOfFailedTests(); + int NumberOfPassedTests(); + + /** \brief Tell manager a subtest failed */ + void TestFailed(); + + /** \brief Tell manager a subtest passed */ + void TestPassed(); + +protected: + int m_FailedTests; + int m_PassedTests; +}; + +US_END_NAMESPACE + +#endif // US_TESTMANAGER_H_INCLUDED diff --git a/test/usTestResource.txt b/test/usTestResource.txt new file mode 100644 index 0000000000..b5125a157a --- /dev/null +++ b/test/usTestResource.txt @@ -0,0 +1 @@ +meant to be compiled into the test driver diff --git a/test/usTestUtilModuleListener.cpp b/test/usTestUtilModuleListener.cpp new file mode 100644 index 0000000000..9098708462 --- /dev/null +++ b/test/usTestUtilModuleListener.cpp @@ -0,0 +1,160 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usTestUtilModuleListener.h" + +#include "usUtils_p.h" + +US_BEGIN_NAMESPACE + +TestModuleListener::TestModuleListener() + : serviceEvents(), moduleEvents() +{} + +void TestModuleListener::ModuleChanged(const ModuleEvent event) +{ + moduleEvents.push_back(event); + US_DEBUG << "ModuleEvent:" << event; +} + +void TestModuleListener::ServiceChanged(const ServiceEvent event) +{ + serviceEvents.push_back(event); + US_DEBUG << "ServiceEvent:" << event; +} + +ModuleEvent TestModuleListener::GetModuleEvent() const +{ + if (moduleEvents.empty()) + { + return ModuleEvent(); + } + return moduleEvents.back(); +} + +ServiceEvent TestModuleListener::GetServiceEvent() const +{ + if (serviceEvents.empty()) + { + return ServiceEvent(); + } + return serviceEvents.back(); +} + +bool TestModuleListener::CheckListenerEvents( + bool pexp, ModuleEvent::Type ptype, + bool sexp, ServiceEvent::Type stype, + Module* moduleX, ServiceReferenceU* servX) +{ + std::vector pEvts; + std::vector seEvts; + + if (pexp) pEvts.push_back(ModuleEvent(ptype, moduleX)); + if (sexp) seEvts.push_back(ServiceEvent(stype, *servX)); + + return CheckListenerEvents(pEvts, seEvts); +} + +bool TestModuleListener::CheckListenerEvents(const std::vector& pEvts) +{ + bool listenState = true; // assume everything will work + + if (pEvts.size() != moduleEvents.size()) + { + listenState = false; + US_DEBUG << "*** Module event mismatch: expected " + << pEvts.size() << " event(s), found " + << moduleEvents.size() << " event(s)."; + + const std::size_t max = pEvts.size() > moduleEvents.size() ? pEvts.size() : moduleEvents.size(); + for (std::size_t i = 0; i < max; ++i) + { + const ModuleEvent& pE = i < pEvts.size() ? pEvts[i] : ModuleEvent(); + const ModuleEvent& pR = i < moduleEvents.size() ? moduleEvents[i] : ModuleEvent(); + US_DEBUG << " " << pE << " - " << pR; + } + } + else + { + for (std::size_t i = 0; i < pEvts.size(); ++i) + { + const ModuleEvent& pE = pEvts[i]; + const ModuleEvent& pR = moduleEvents[i]; + if (pE.GetType() != pR.GetType() + || pE.GetModule() != pR.GetModule()) + { + listenState = false; + US_DEBUG << "*** Wrong module event: " << pR << " expected " << pE; + } + } + } + + moduleEvents.clear(); + return listenState; +} + +bool TestModuleListener::CheckListenerEvents(const std::vector& seEvts) +{ + bool listenState = true; // assume everything will work + + if (seEvts.size() != serviceEvents.size()) + { + listenState = false; + US_DEBUG << "*** Service event mismatch: expected " + << seEvts.size() << " event(s), found " + << serviceEvents.size() << " event(s)."; + + const std::size_t max = seEvts.size() > serviceEvents.size() ? seEvts.size() : serviceEvents.size(); + for (std::size_t i = 0; i < max; ++i) + { + const ServiceEvent& seE = i < seEvts.size() ? seEvts[i] : ServiceEvent(); + const ServiceEvent& seR = i < serviceEvents.size() ? serviceEvents[i] : ServiceEvent(); + US_DEBUG << " " << seE << " - " << seR; + } + } + else + { + for (std::size_t i = 0; i < seEvts.size(); ++i) + { + const ServiceEvent& seE = seEvts[i]; + const ServiceEvent& seR = serviceEvents[i]; + if (seE.GetType() != seR.GetType() + || (!(seE.GetServiceReference() == seR.GetServiceReference()))) + { + listenState = false; + US_DEBUG << "*** Wrong service event: " << seR << " expected " << seE; + } + } + } + + serviceEvents.clear(); + return listenState; +} + +bool TestModuleListener::CheckListenerEvents( + const std::vector& pEvts, + const std::vector& seEvts) +{ + if (!CheckListenerEvents(pEvts)) return false; + return CheckListenerEvents(seEvts); +} + +US_END_NAMESPACE diff --git a/test/usTestUtilModuleListener.h b/test/usTestUtilModuleListener.h new file mode 100644 index 0000000000..825d5a1d68 --- /dev/null +++ b/test/usTestUtilModuleListener.h @@ -0,0 +1,68 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USTESTUTILMODULELISTENER_H +#define USTESTUTILMODULELISTENER_H + +#include "usConfig.h" + +#include "usModuleEvent.h" +#include "usServiceEvent.h" + +US_BEGIN_NAMESPACE + +class ModuleContext; + +class TestModuleListener { + +public: + + TestModuleListener(); + + void ModuleChanged(const ModuleEvent event); + + void ServiceChanged(const ServiceEvent event); + + ModuleEvent GetModuleEvent() const; + + ServiceEvent GetServiceEvent() const; + + bool CheckListenerEvents( + bool pexp, ModuleEvent::Type ptype, + bool sexp, ServiceEvent::Type stype, + Module* moduleX, ServiceReferenceU* servX); + + bool CheckListenerEvents(const std::vector& pEvts); + + bool CheckListenerEvents(const std::vector& seEvts); + + bool CheckListenerEvents(const std::vector& pEvts, + const std::vector& seEvts); + +private: + + std::vector serviceEvents; + std::vector moduleEvents; +}; + +US_END_NAMESPACE + +#endif // USTESTUTILMODULELISTENER_H diff --git a/test/usTestingConfig.h.in b/test/usTestingConfig.h.in new file mode 100644 index 0000000000..5750e36123 --- /dev/null +++ b/test/usTestingConfig.h.in @@ -0,0 +1,12 @@ +#ifndef USTESTINGCONFIG_H +#define USTESTINGCONFIG_H + +#ifdef CMAKE_INTDIR +#define US_LIBRARY_OUTPUT_DIRECTORY "@CMAKE_LIBRARY_OUTPUT_DIRECTORY@/" CMAKE_INTDIR +#define US_RUNTIME_OUTPUT_DIRECTORY "@CMAKE_RUNTIME_OUTPUT_DIRECTORY@/" CMAKE_INTDIR +#else +#define US_LIBRARY_OUTPUT_DIRECTORY "@CMAKE_LIBRARY_OUTPUT_DIRECTORY@" +#define US_RUNTIME_OUTPUT_DIRECTORY "@CMAKE_RUNTIME_OUTPUT_DIRECTORY@" +#endif + +#endif // USTESTINGCONFIG_H diff --git a/test/usTestingMacros.h b/test/usTestingMacros.h new file mode 100644 index 0000000000..0b85d3769d --- /dev/null +++ b/test/usTestingMacros.h @@ -0,0 +1,132 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include + +#include "usTestManager.h" + +US_BEGIN_NAMESPACE + /** \brief Indicate a failed test. */ + class TestFailedException : public std::exception { + public: + TestFailedException() {} + }; +US_END_NAMESPACE + +/** + * + * \brief Output some text without generating a terminating newline. + * + * */ +#define US_TEST_OUTPUT_NO_ENDL(x) \ + std::cout x << std::flush; + +/** \brief Output some text. */ +#define US_TEST_OUTPUT(x) \ + US_TEST_OUTPUT_NO_ENDL(x << "\n") + +/** \brief Do some general test preparations. Must be called first in the + main test function. */ +#define US_TEST_BEGIN(testName) \ + std::string usTestName(#testName); \ + US_PREPEND_NAMESPACE(TestManager)::GetInstance().Initialize(); \ + try { + +/** \brief Fail and finish test with message MSG */ +#define US_TEST_FAILED_MSG(MSG) \ + US_TEST_OUTPUT(MSG) \ + throw US_PREPEND_NAMESPACE(TestFailedException)(); + +/** \brief Must be called last in the main test function. */ +#define US_TEST_END() \ + } catch (const US_PREPEND_NAMESPACE(TestFailedException)&) { \ + US_TEST_OUTPUT(<< "Further test execution skipped.") \ + US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestFailed(); \ + } catch (const std::exception& ex) { \ + US_TEST_OUTPUT(<< "Exception occured " << ex.what()) \ + US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestFailed(); \ + } \ + if (US_PREPEND_NAMESPACE(TestManager)::GetInstance().NumberOfFailedTests() > 0) { \ + US_TEST_OUTPUT(<< usTestName << ": [DONE FAILED] , subtests passed: " << \ + US_PREPEND_NAMESPACE(TestManager)::GetInstance().NumberOfPassedTests() << " failed: " << \ + US_PREPEND_NAMESPACE(TestManager)::GetInstance().NumberOfFailedTests() ) \ + return EXIT_FAILURE; \ + } else { \ + US_TEST_OUTPUT(<< usTestName << ": " \ + << US_PREPEND_NAMESPACE(TestManager)::GetInstance().NumberOfPassedTests() \ + << " tests [DONE PASSED]") \ + return EXIT_SUCCESS; \ + } + +#define US_TEST_CONDITION(COND,MSG) \ + US_TEST_OUTPUT_NO_ENDL(<< MSG) \ + if ( ! (COND) ) { \ + US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestFailed(); \ + US_TEST_OUTPUT(<< " [FAILED]\n" << "In " << __FILE__ \ + << ", line " << __LINE__ \ + << ": " #COND " : [FAILED]") \ + } else { \ + US_TEST_OUTPUT(<< " [PASSED]") \ + US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestPassed(); \ + } + +#define US_TEST_CONDITION_REQUIRED(COND,MSG) \ + US_TEST_OUTPUT_NO_ENDL(<< MSG) \ + if ( ! (COND) ) { \ + US_TEST_FAILED_MSG(<< " [FAILED]\n" << " +--> in " << __FILE__ \ + << ", line " << __LINE__ \ + << ", expression is false: \"" #COND "\"") \ + } else { \ + US_TEST_OUTPUT(<< " [PASSED]") \ + US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestPassed(); \ + } + +/** + * \brief Begin block which should be checked for exceptions + * + * This macro, together with US_TEST_FOR_EXCEPTION_END, can be used + * to test whether a code block throws an expected exception. The test FAILS if the + * exception is NOT thrown. + */ +#define US_TEST_FOR_EXCEPTION_BEGIN(EXCEPTIONCLASS) \ + try { + +#define US_TEST_FOR_EXCEPTION_END(EXCEPTIONCLASS) \ + US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestFailed(); \ + US_TEST_OUTPUT( << "Expected an '" << #EXCEPTIONCLASS << "' exception. [FAILED]") \ + } \ + catch (EXCEPTIONCLASS) { \ + US_TEST_OUTPUT(<< "Caught an expected '" << #EXCEPTIONCLASS \ + << "' exception. [PASSED]") \ + US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestPassed(); \ + } + + +/** + * \brief Simplified version of US_TEST_FOR_EXCEPTION_BEGIN / END for + * a single statement + */ +#define US_TEST_FOR_EXCEPTION(EXCEPTIONCLASS, STATEMENT) \ + US_TEST_FOR_EXCEPTION_BEGIN(EXCEPTIONCLASS) \ + STATEMENT ; \ + US_TEST_FOR_EXCEPTION_END(EXCEPTIONCLASS) diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt new file mode 100644 index 0000000000..336f1d20ee --- /dev/null +++ b/tools/CMakeLists.txt @@ -0,0 +1,19 @@ + +include_directories(${US_INCLUDE_DIRS}) + +add_definitions(-DUS_RCC_EXECUTABLE_NAME=\"${US_RCC_EXECUTABLE_NAME}\") + +set(srcs usResourceCompiler.cpp) +if(US_ENABLE_RESOURCE_COMPRESSION) + list(APPEND srcs usResourceCompressor.c) +endif() + +add_executable(${US_RCC_EXECUTABLE_NAME} ${srcs}) +if(WIN32) + target_link_libraries(${US_RCC_EXECUTABLE_NAME} Shlwapi) +endif() + +install(TARGETS ${US_RCC_EXECUTABLE_NAME} + EXPORT ${PROJECT_NAME}Targets + FRAMEWORK DESTINATION . COMPONENT sdk + RUNTIME DESTINATION bin COMPONENT sdk) diff --git a/tools/miniz.c b/tools/miniz.c new file mode 100644 index 0000000000..39a1752410 --- /dev/null +++ b/tools/miniz.c @@ -0,0 +1,4766 @@ +/* miniz.c v1.14 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing + See "unlicense" statement at the end of this file. + Rich Geldreich , last updated May 20, 2012 + Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt + + Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define + MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). + + * Change History + 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include (thanks fermtect). + 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. + Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. + Eliminated a bunch of warnings when compiling with GCC 32-bit/64. + Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly + "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). + Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. + Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. + Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. + Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) + Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). + 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. + level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson for the feedback/bug report. + 5/28/11 v1.11 - Added statement from unlicense.org + 5/27/11 v1.10 - Substantial compressor optimizations: + Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a + Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). + Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. + Refactored the compression code for better readability and maintainability. + Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large + drop in throughput on some files). + 5/15/11 v1.09 - Initial stable release. + + * Low-level Deflate/Inflate implementation notes: + + Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or + greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses + approximately as well as zlib. + + Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function + coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory + block large enough to hold the entire file. + + The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. + + * zlib-style API notes: + + miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in + zlib replacement in many apps: + The z_stream struct, optional memory allocation callbacks + deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound + inflateInit/inflateInit2/inflate/inflateEnd + compress, compress2, compressBound, uncompress + CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. + Supports raw deflate streams or standard zlib streams with adler-32 checking. + + Limitations: + The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. + I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but + there are no guarantees that miniz.c pulls this off perfectly. + + * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by + Alex Evans. Supports 1-4 bytes/pixel images. + + * ZIP archive API notes: + + The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to + get the job done with minimal fuss. There are simple API's to retrieve file information, read files from + existing archives, create new archives, append new files to existing archives, or clone archive data from + one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), + or you can specify custom file read/write callbacks. + + - Archive reading: Just call this function to read a single file from a disk archive: + + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, + size_t *pSize, mz_uint zip_flags); + + For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central + directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. + + - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: + + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + + The locate operation can optionally check file comments too, which (as one example) can be used to identify + multiple versions of the same file in an archive. This function uses a simple linear search through the central + directory, so it's not very fast. + + Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and + retrieve detailed info on each file by calling mz_zip_reader_file_stat(). + + - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data + to disk and builds an exact image of the central directory in memory. The central directory image is written + all at once at the end of the archive file when the archive is finalized. + + The archive writer can optionally align each file's local header and file data to any power of 2 alignment, + which can be useful when the archive will be read from optical media. Also, the writer supports placing + arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still + readable by any ZIP tool. + + - Archive appending: The simple way to add a single file to an archive is to call this function: + + mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, + const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + + The archive will be created if it doesn't already exist, otherwise it'll be appended to. + Note the appending is done in-place and is not an atomic operation, so if something goes wrong + during the operation it's possible the archive could be left without a central directory (although the local + file headers and file data will be fine, so the archive will be recoverable). + + For more complex archive modification scenarios: + 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to + preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the + compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and + you're done. This is safe but requires a bunch of temporary disk space or heap memory. + + 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), + append new files as needed, then finalize the archive which will write an updated central directory to the + original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a + possibility that the archive's central directory could be lost with this method if anything goes wrong, though. + + - ZIP archive support limitations: + No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. + Requires streams capable of seeking. + + * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the + below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. + + * Important: For best perf. be sure to customize the below macros for your target platform: + #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 + #define MINIZ_LITTLE_ENDIAN 1 + #define MINIZ_HAS_64BIT_REGISTERS 1 +*/ + +#ifndef MINIZ_HEADER_INCLUDED +#define MINIZ_HEADER_INCLUDED + +#include + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) +#include +#endif + +// Defines to completely disable specific portions of miniz.c: +// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. + +// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. +//#define MINIZ_NO_STDIO + +// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or +// get/set file times. +//#define MINIZ_NO_TIME + +// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. +//#define MINIZ_NO_ARCHIVE_APIS + +// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. +//#define MINIZ_NO_ARCHIVE_WRITING_APIS + +// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. +//#define MINIZ_NO_ZLIB_APIS + +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. +//#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. +// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc +// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user +// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. +//#define MINIZ_NO_MALLOC + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +// MINIZ_X86_OR_X64_CPU is only used to help set the below macros. +#define MINIZ_X86_OR_X64_CPU 1 +#endif + +#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. +#define MINIZ_LITTLE_ENDIAN 1 +#endif + +#if MINIZ_X86_OR_X64_CPU +// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). +#define MINIZ_HAS_64BIT_REGISTERS 1 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// ------------------- zlib-style API Definitions. + +// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! +typedef unsigned long mz_ulong; + +// Heap allocation callbacks. +// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. +typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); +typedef void (*mz_free_func)(void *opaque, void *address); +typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); + +#define MZ_ADLER32_INIT (1) +// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); + +#define MZ_CRC32_INIT (0) +// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. +mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); + +// Compression strategies. +enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; + +// Method +#define MZ_DEFLATED 8 + +#ifndef MINIZ_NO_ZLIB_APIS + +#define MZ_VERSION "9.1.14" +#define MZ_VERNUM 0x91E0 +#define MZ_VER_MAJOR 9 +#define MZ_VER_MINOR 1 +#define MZ_VER_REVISION 14 +#define MZ_VER_SUBREVISION 0 + +// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). +enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; + +// Return status codes. MZ_PARAM_ERROR is non-standard. +enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; + +// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. +enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; + +// Window bits +#define MZ_DEFAULT_WINDOW_BITS 15 + +struct mz_internal_state; + +// Compression/decompression stream struct. +typedef struct mz_stream_s +{ + const unsigned char *next_in; // pointer to next byte to read + unsigned int avail_in; // number of bytes available at next_in + mz_ulong total_in; // total number of bytes consumed so far + + unsigned char *next_out; // pointer to next byte to write + unsigned int avail_out; // number of bytes that can be written to next_out + mz_ulong total_out; // total number of bytes produced so far + + char *msg; // error msg (unused) + struct mz_internal_state *state; // internal state, allocated by zalloc/zfree + + mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) + mz_free_func zfree; // optional heap free function (defaults to free) + void *opaque; // heap alloc function user pointer + + int data_type; // data_type (unused) + mz_ulong adler; // adler32 of the source or uncompressed data + mz_ulong reserved; // not used +} mz_stream; + +typedef mz_stream *mz_streamp; + +// Returns the version string of miniz.c. +const char *mz_version(void); + +// mz_deflateInit() initializes a compressor with default options: +// Parameters: +// pStream must point to an initialized mz_stream struct. +// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. +// level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. +// (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if the input parameters are bogus. +// MZ_MEM_ERROR on out of memory. +int mz_deflateInit(mz_streamp pStream, int level); + +// mz_deflateInit2() is like mz_deflate(), except with more control: +// Additional parameters: +// method must be MZ_DEFLATED +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) +// mem_level must be between [1, 9] (it's checked but ignored by miniz.c) +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); + +// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). +int mz_deflateReset(mz_streamp pStream); + +// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. +// Return values: +// MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). +// MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) +int mz_deflate(mz_streamp pStream, int flush); + +// mz_deflateEnd() deinitializes a compressor: +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +int mz_deflateEnd(mz_streamp pStream); + +// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + +// Single-call compression functions mz_compress() and mz_compress2(): +// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); + +// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). +mz_ulong mz_compressBound(mz_ulong source_len); + +// Initializes a decompressor. +int mz_inflateInit(mz_streamp pStream); + +// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). +int mz_inflateInit2(mz_streamp pStream, int window_bits); + +// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. +// On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). +// MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. +// Return values: +// MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. +// MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_DATA_ERROR if the deflate stream is invalid. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again +// with more input data, or with more room in the output buffer (except when using single call decompression, described above). +int mz_inflate(mz_streamp pStream, int flush); + +// Deinitializes a decompressor. +int mz_inflateEnd(mz_streamp pStream); + +// Single-call decompression. +// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); + +// Returns a string description of the specified error code, or NULL if the error code is invalid. +const char *mz_error(int err); + +// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + typedef unsigned char Byte; + typedef unsigned int uInt; + typedef mz_ulong uLong; + typedef Byte Bytef; + typedef uInt uIntf; + typedef char charf; + typedef int intf; + typedef void *voidpf; + typedef uLong uLongf; + typedef void *voidp; + typedef void *const voidpc; + #define Z_NULL 0 + #define Z_NO_FLUSH MZ_NO_FLUSH + #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH + #define Z_SYNC_FLUSH MZ_SYNC_FLUSH + #define Z_FULL_FLUSH MZ_FULL_FLUSH + #define Z_FINISH MZ_FINISH + #define Z_BLOCK MZ_BLOCK + #define Z_OK MZ_OK + #define Z_STREAM_END MZ_STREAM_END + #define Z_NEED_DICT MZ_NEED_DICT + #define Z_ERRNO MZ_ERRNO + #define Z_STREAM_ERROR MZ_STREAM_ERROR + #define Z_DATA_ERROR MZ_DATA_ERROR + #define Z_MEM_ERROR MZ_MEM_ERROR + #define Z_BUF_ERROR MZ_BUF_ERROR + #define Z_VERSION_ERROR MZ_VERSION_ERROR + #define Z_PARAM_ERROR MZ_PARAM_ERROR + #define Z_NO_COMPRESSION MZ_NO_COMPRESSION + #define Z_BEST_SPEED MZ_BEST_SPEED + #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION + #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION + #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY + #define Z_FILTERED MZ_FILTERED + #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY + #define Z_RLE MZ_RLE + #define Z_FIXED MZ_FIXED + #define Z_DEFLATED MZ_DEFLATED + #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS + #define alloc_func mz_alloc_func + #define free_func mz_free_func + #define internal_state mz_internal_state + #define z_stream mz_stream + #define deflateInit mz_deflateInit + #define deflateInit2 mz_deflateInit2 + #define deflateReset mz_deflateReset + #define deflate mz_deflate + #define deflateEnd mz_deflateEnd + #define deflateBound mz_deflateBound + #define compress mz_compress + #define compress2 mz_compress2 + #define compressBound mz_compressBound + #define inflateInit mz_inflateInit + #define inflateInit2 mz_inflateInit2 + #define inflate mz_inflate + #define inflateEnd mz_inflateEnd + #define uncompress mz_uncompress + #define crc32 mz_crc32 + #define adler32 mz_adler32 + #define MAX_WBITS 15 + #define MAX_MEM_LEVEL 9 + #define zError mz_error + #define ZLIB_VERSION MZ_VERSION + #define ZLIB_VERNUM MZ_VERNUM + #define ZLIB_VER_MAJOR MZ_VER_MAJOR + #define ZLIB_VER_MINOR MZ_VER_MINOR + #define ZLIB_VER_REVISION MZ_VER_REVISION + #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION + #define zlibVersion mz_version + #define zlib_version mz_version() +#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +#endif // MINIZ_NO_ZLIB_APIS + +// ------------------- Types and macros + +typedef unsigned char mz_uint8; +typedef signed short mz_int16; +typedef unsigned short mz_uint16; +typedef unsigned int mz_uint32; +typedef unsigned int mz_uint; +typedef long long mz_int64; +typedef unsigned long long mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +// Works around MSVC's spammy "warning C4127: conditional expression is constant" message. +#ifdef _MSC_VER + #define MZ_MACRO_END while (0, 0) +#else + #define MZ_MACRO_END while (0) +#endif + +// ------------------- ZIP archive reading/writing + +#ifndef MINIZ_NO_ARCHIVE_APIS + +enum +{ + MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 +}; + +typedef struct +{ + mz_uint32 m_file_index; + mz_uint32 m_central_dir_ofs; + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; +#ifndef MINIZ_NO_TIME + time_t m_time; +#endif + mz_uint32 m_crc32; + mz_uint64 m_comp_size; + mz_uint64 m_uncomp_size; + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + mz_uint64 m_local_header_ofs; + mz_uint32 m_comment_size; + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; +} mz_zip_archive_file_stat; + +typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); +typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); + +struct mz_zip_internal_state_tag; +typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + +typedef enum +{ + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 +} mz_zip_mode; + +typedef struct +{ + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + mz_uint m_total_files; + mz_zip_mode m_zip_mode; + + mz_uint m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + +} mz_zip_archive; + +typedef enum +{ + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 +} mz_zip_flags; + +// ZIP archive reading + +// Inits a ZIP archive reader. +// These functions read and validate the archive's central directory. +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); +#endif + +// Returns the total number of files in the archive. +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); + +// Returns detailed information about an archive file entry. +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); + +// Determines if an archive file entry is a directory entry. +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); + +// Retrieves the filename of an archive file entry. +// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); + +// Attempts to locates a file in the archive's central directory. +// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH +// Returns -1 if the file cannot be found. +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + +// Extracts a archive file to a memory buffer using no memory allocation. +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + +// Extracts a archive file to a memory buffer. +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); + +// Extracts a archive file to a dynamically allocated heap buffer. +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); + +// Extracts a archive file using a callback function to output the file's data. +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +// Extracts a archive file to a disk file and sets its last accessed and modified times. +// This function only extracts files, not archive directory records. +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); +#endif + +// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. +mz_bool mz_zip_reader_end(mz_zip_archive *pZip); + +// ZIP archive writing + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +// Inits a ZIP archive writer. +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); +#endif + +// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. +// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. +// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). +// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. +// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before +// the archive is finalized the file's central directory will be hosed. +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); + +// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. +// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + +#ifndef MINIZ_NO_STDIO +// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +#endif + +// Adds a file to an archive by fully cloning the data from another archive. +// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); + +// Finalizes the archive by writing the central directory records followed by the end of central directory record. +// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). +// An archive must be manually finalized by calling this function for it to be valid. +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); + +// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. +// Note for the archive to be valid, it must have been finalized before ending. +mz_bool mz_zip_writer_end(mz_zip_archive *pZip); + +// Misc. high-level helper functions: + +// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + +// Reads a single file from an archive into a heap block. +// Returns NULL on failure. +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); + +#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +#endif // #ifndef MINIZ_NO_ARCHIVE_APIS + +// ------------------- Low-level Decompression API Definitions + +// Decompression flags used by tinfl_decompress(). +// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. +// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. +// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). +// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. +enum +{ + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +// High level decompression functions: +// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. +// On return: +// Function returns a pointer to the decompressed data, or NULL on failure. +// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must free() the returned block when it's no longer needed. +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. +// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. +// Returns 1 on success or 0 on failure. +typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; + +// Max size of LZ dictionary. +#define TINFL_LZ_DICT_SIZE 32768 + +// Return status. +typedef enum +{ + TINFL_STATUS_BAD_PARAM = -3, + TINFL_STATUS_ADLER32_MISMATCH = -2, + TINFL_STATUS_FAILED = -1, + TINFL_STATUS_DONE = 0, + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +// Initializes the decompressor to its initial state. +#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. +// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + +// Internal/private bits follow. +enum +{ + TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +typedef struct +{ + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; +} tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS + #define TINFL_USE_64BIT_BITBUF 1 +#endif + +#if TINFL_USE_64BIT_BITBUF + typedef mz_uint64 tinfl_bit_buf_t; + #define TINFL_BITBUF_SIZE (64) +#else + typedef mz_uint32 tinfl_bit_buf_t; + #define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag +{ + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + +// ------------------- Low-level Compression API Definitions + +// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). +#define TDEFL_LESS_MEMORY 0 + +// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): +// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). +enum +{ + TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF +}; + +// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. +// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). +// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. +// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). +// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) +// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. +// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. +// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. +enum +{ + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 +}; + +// High level compression functions: +// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of source block to compress. +// flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must free() the returned block when it's no longer needed. +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. +// Returns 0 on failure. +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// Compresses an image to a compressed PNG file in memory. +// On entry: +// pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pLen_out will be set to the size of the PNG image file. +// The caller must free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); + +// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. +typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); + +// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; + +// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). +#if TDEFL_LESS_MEMORY +enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#else +enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#endif + +// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. +typedef enum +{ + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1, +} tdefl_status; + +// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums +typedef enum +{ + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 +} tdefl_flush; + +// tdefl's compression state structure. +typedef struct +{ + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; +} tdefl_compressor; + +// Initializes the compressor. +// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. +// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. +// If pBut_buf_func is NULL the user should always call the tdefl_compress() API. +// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); + +// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. +// tdefl_compress_buffer() always consumes the entire input buffer. +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); +mz_uint32 tdefl_get_adler32(tdefl_compressor *d); + +// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros. +#ifndef MINIZ_NO_ZLIB_APIS +// Create tdefl_compress() flags given zlib-style compression parameters. +// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) +// window_bits may be -15 (raw deflate) or 15 (zlib) +// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); +#endif // #ifndef MINIZ_NO_ZLIB_APIS + +#ifdef __cplusplus +} +#endif + +#endif // MINIZ_HEADER_INCLUDED + +// ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.) + +#ifndef MINIZ_HEADER_FILE_ONLY + +typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1]; +typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1]; +typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1]; + +#include +#include + +#define MZ_ASSERT(x) assert(x) + +#ifdef MINIZ_NO_MALLOC + #define MZ_MALLOC(x) NULL + #define MZ_FREE(x) (void)x, ((void)0) + #define MZ_REALLOC(p, x) NULL +#else + #define MZ_MALLOC(x) malloc(x) + #define MZ_FREE(x) free(x) + #define MZ_REALLOC(p, x) realloc(p, x) +#endif + +#define MZ_MAX(a,b) (((a)>(b))?(a):(b)) +#define MZ_MIN(a,b) (((a)<(b))?(a):(b)) +#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) + #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#else + #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) + #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#endif + +#ifdef _MSC_VER + #define MZ_FORCEINLINE __forceinline +#elif defined(__GNUC__) + #define MZ_FORCEINLINE __attribute__((__always_inline__)) +#else + #define MZ_FORCEINLINE inline +#endif + +#ifdef __cplusplus + extern "C" { +#endif + +// ------------------- zlib-style API's + +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) +{ + mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; + if (!ptr) return MZ_ADLER32_INIT; + while (buf_len) { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { + s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; + } + for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; + } + return (s2 << 16) + s1; +} + +// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) +{ + static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; + mz_uint32 crcu32 = (mz_uint32)crc; + if (!ptr) return MZ_CRC32_INIT; + crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } + return ~crcu32; +} + +#ifndef MINIZ_NO_ZLIB_APIS + +static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } +static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } +static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); } + +const char *mz_version(void) +{ + return MZ_VERSION; +} + +int mz_deflateInit(mz_streamp pStream, int level) +{ + return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); +} + +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) +{ + tdefl_compressor *pComp; + mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); + + if (!pStream) return MZ_STREAM_ERROR; + if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = MZ_ADLER32_INIT; + pStream->msg = NULL; + pStream->reserved = 0; + pStream->total_in = 0; + pStream->total_out = 0; + if (!pStream->zalloc) pStream->zalloc = def_alloc_func; + if (!pStream->zfree) pStream->zfree = def_free_func; + + pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pComp; + + if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) + { + mz_deflateEnd(pStream); + return MZ_PARAM_ERROR; + } + + return MZ_OK; +} + +int mz_deflateReset(mz_streamp pStream) +{ + if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; + pStream->total_in = pStream->total_out = 0; + tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, ((tdefl_compressor*)pStream->state)->m_flags); + return MZ_OK; +} + +int mz_deflate(mz_streamp pStream, int flush) +{ + size_t in_bytes, out_bytes; + mz_ulong orig_total_in, orig_total_out; + int mz_status = MZ_OK; + + if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; + if (!pStream->avail_out) return MZ_BUF_ERROR; + + if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; + + if (((tdefl_compressor*)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) + return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; + + orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; + for ( ; ; ) + { + tdefl_status defl_status; + in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; + + defl_status = tdefl_compress((tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); + pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state); + + pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (defl_status < 0) + { + mz_status = MZ_STREAM_ERROR; + break; + } + else if (defl_status == TDEFL_STATUS_DONE) + { + mz_status = MZ_STREAM_END; + break; + } + else if (!pStream->avail_out) + break; + else if ((!pStream->avail_in) && (flush != MZ_FINISH)) + { + if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) + break; + return MZ_BUF_ERROR; // Can't make forward progress without some input. + } + } + return mz_status; +} + +int mz_deflateEnd(mz_streamp pStream) +{ + if (!pStream) return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) +{ + (void)pStream; + // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) + return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); +} + +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) +{ + int status; + mz_stream stream; + memset(&stream, 0, sizeof(stream)); + + // In case mz_ulong is 64-bits (argh I hate longs). + if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_deflateInit(&stream, level); + if (status != MZ_OK) return status; + + status = mz_deflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_deflateEnd(&stream); + return (status == MZ_OK) ? MZ_BUF_ERROR : status; + } + + *pDest_len = stream.total_out; + return mz_deflateEnd(&stream); +} + +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); +} + +mz_ulong mz_compressBound(mz_ulong source_len) +{ + return mz_deflateBound(NULL, source_len); +} + +typedef struct +{ + tinfl_decompressor m_decomp; + mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; + mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; + tinfl_status m_last_status; +} inflate_state; + +int mz_inflateInit2(mz_streamp pStream, int window_bits) +{ + inflate_state *pDecomp; + if (!pStream) return MZ_STREAM_ERROR; + if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + if (!pStream->zalloc) pStream->zalloc = def_alloc_func; + if (!pStream->zfree) pStream->zfree = def_free_func; + + pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); + if (!pDecomp) return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pDecomp; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + pDecomp->m_window_bits = window_bits; + + return MZ_OK; +} + +int mz_inflateInit(mz_streamp pStream) +{ + return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); +} + +int mz_inflate(mz_streamp pStream, int flush) +{ + inflate_state* pState; + mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; + size_t in_bytes, out_bytes, orig_avail_in; + tinfl_status status; + + if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; + if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; + if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; + + pState = (inflate_state*)pStream->state; + if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; + orig_avail_in = pStream->avail_in; + + first_call = pState->m_first_call; pState->m_first_call = 0; + if (pState->m_last_status < 0) return MZ_DATA_ERROR; + + if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; + pState->m_has_flushed |= (flush == MZ_FINISH); + + if ((flush == MZ_FINISH) && (first_call)) + { + // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. + decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; + in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); + pState->m_last_status = status; + pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; + + if (status < 0) + return MZ_DATA_ERROR; + else if (status != TINFL_STATUS_DONE) + { + pState->m_last_status = TINFL_STATUS_FAILED; + return MZ_BUF_ERROR; + } + return MZ_STREAM_END; + } + // flush != MZ_FINISH then we must assume there's more input. + if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; + + if (pState->m_dict_avail) + { + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; + pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + } + + for ( ; ; ) + { + in_bytes = pStream->avail_in; + out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; + + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); + pState->m_last_status = status; + + pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); + + pState->m_dict_avail = (mz_uint)out_bytes; + + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; + pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + + if (status < 0) + return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). + else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) + return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. + else if (flush == MZ_FINISH) + { + // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. + if (status == TINFL_STATUS_DONE) + return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; + // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. + else if (!pStream->avail_out) + return MZ_BUF_ERROR; + } + else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) + break; + } + + return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; +} + +int mz_inflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + mz_stream stream; + int status; + memset(&stream, 0, sizeof(stream)); + + // In case mz_ulong is 64-bits (argh I hate longs). + if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_inflateInit(&stream); + if (status != MZ_OK) + return status; + + status = mz_inflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_inflateEnd(&stream); + return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; + } + *pDest_len = stream.total_out; + + return mz_inflateEnd(&stream); +} + +const char *mz_error(int err) +{ + static struct { int m_err; const char *m_pDesc; } s_error_descs[] = + { + { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, + { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } + }; + mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; + return NULL; +} + +#endif //MINIZ_NO_ZLIB_APIS + +// ------------------- Low-level Decompression (completely independent from all compression API's) + +#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) +#define TINFL_MEMSET(p, c, l) memset(p, c, l) + +#define TINFL_CR_BEGIN switch(r->m_state) { case 0: +#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END +#define TINFL_CR_FINISH } + +// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never +// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. +#define TINFL_GET_BYTE(state_index, c) do { \ + if (pIn_buf_cur >= pIn_buf_end) { \ + for ( ; ; ) { \ + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ + TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ + if (pIn_buf_cur < pIn_buf_end) { \ + c = *pIn_buf_cur++; \ + break; \ + } \ + } else { \ + c = 0; \ + break; \ + } \ + } \ + } else c = *pIn_buf_cur++; } MZ_MACRO_END + +#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END + +// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. +// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a +// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the +// bit buffer contains >=15 bits (deflate's max. Huffman code size). +#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ + do { \ + temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ + } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ + } while (num_bits < 15); + +// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read +// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully +// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. +// The slow path is only executed at the very end of the input buffer. +#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ + int temp; mz_uint code_len, c; \ + if (num_bits < 15) { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) { \ + TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ + } else { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ + } \ + } \ + if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ + code_len = temp >> 9, temp &= 511; \ + else { \ + code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ + } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END + +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) +{ + static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; + static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + static const int s_min_table_sizes[3] = { 257, 1, 4 }; + + tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; + const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; + mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; + size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; + + // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). + if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } + + num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); + if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } + } + + do + { + TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; + if (r->m_type == 0) + { + TINFL_SKIP_BITS(5, num_bits & 7); + for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } + if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } + while ((counter) && (num_bits)) + { + TINFL_GET_BITS(51, dist, 8); + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = (mz_uint8)dist; + counter--; + } + while (counter) + { + size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } + while (pIn_buf_cur >= pIn_buf_end) + { + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) + { + TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); + } + else + { + TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); + } + } + n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); + TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; + } + } + else if (r->m_type == 3) + { + TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); + } + else + { + if (r->m_type == 1) + { + mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; + r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); + for ( i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8; + } + else + { + for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } + MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } + r->m_table_sizes[2] = 19; + } + for ( ; (int)r->m_type >= 0; r->m_type--) + { + int tree_next, tree_cur; tinfl_huff_table *pTable; + mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; + used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } + if ((65536 != total) && (used_syms > 1)) + { + TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); + } + for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) + { + mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; + cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } + if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) + { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; + } + if (r->m_type == 2) + { + for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); ) + { + mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } + if ((dist == 16) && (!counter)) + { + TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); + } + num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; + TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; + } + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) + { + TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); + } + TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); + } + } + for ( ; ; ) + { + mz_uint8 *pSrc; + for ( ; ; ) + { + if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) + { + TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); + if (counter >= 256) + break; + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = (mz_uint8)counter; + } + else + { + int sym2; mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } +#else + if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); + } + counter = sym2; bit_buf >>= code_len; num_bits -= code_len; + if (counter & 256) + break; + +#if !TINFL_USE_64BIT_BITBUF + if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); + } + bit_buf >>= code_len; num_bits -= code_len; + + pOut_buf_cur[0] = (mz_uint8)counter; + if (sym2 & 256) + { + pOut_buf_cur++; + counter = sym2; + break; + } + pOut_buf_cur[1] = (mz_uint8)sym2; + pOut_buf_cur += 2; + } + } + if ((counter &= 511) == 256) break; + + num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; + if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } + + TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); + num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; + if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } + + dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; + if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + { + TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); + } + + pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + + if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) + { + while (counter--) + { + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; + } + continue; + } +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + else if ((counter >= 9) && (counter <= dist)) + { + const mz_uint8 *pSrc_end = pSrc + (counter & ~7); + do + { + ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; + ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; + pOut_buf_cur += 8; + } while ((pSrc += 8) < pSrc_end); + if ((counter &= 7) < 3) + { + if (counter) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + continue; + } + } +#endif + do + { + pOut_buf_cur[0] = pSrc[0]; + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur[2] = pSrc[2]; + pOut_buf_cur += 3; pSrc += 3; + } while ((int)(counter -= 3) > 2); + if ((int)counter > 0) + { + pOut_buf_cur[0] = pSrc[0]; + if ((int)counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + } + } + } while (!(r->m_final & 1)); + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } + } + TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); + TINFL_CR_FINISH + +common_exit: + r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) + { + const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; + } + for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; + } + r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; + } + return status; +} + +// Higher level helper functions. +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; + *pOut_len = 0; + tinfl_init(&decomp); + for ( ; ; ) + { + size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) + { + MZ_FREE(pBuf); *pOut_len = 0; return NULL; + } + src_buf_ofs += src_buf_size; + *pOut_len += dst_buf_size; + if (status == TINFL_STATUS_DONE) break; + new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; + pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); + if (!pNew_buf) + { + MZ_FREE(pBuf); *pOut_len = 0; return NULL; + } + pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; + } + return pBuf; +} + +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); + status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; +} + +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + int result = 0; + tinfl_decompressor decomp; + mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; + if (!pDict) + return TINFL_STATUS_FAILED; + tinfl_init(&decomp); + for ( ; ; ) + { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, + (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + in_buf_ofs += in_buf_size; + if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + break; + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) + { + result = (status == TINFL_STATUS_DONE); + break; + } + dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); + } + MZ_FREE(pDict); + *pIn_buf_size = in_buf_ofs; + return result; +} + +// ------------------- Low-level Compression (independent from all decompression API's) + +// Purposely making these tables static for faster init and thread safety. +static const mz_uint16 s_tdefl_len_sym[256] = { + 257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272, + 273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276, + 277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278, + 279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280, + 281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281, + 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, + 283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283, + 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 }; + +static const mz_uint8 s_tdefl_len_extra[256] = { + 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, + 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 }; + +static const mz_uint8 s_tdefl_small_dist_sym[512] = { + 0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11, + 11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13, + 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14, + 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14, + 14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15, + 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 }; + +static const mz_uint8 s_tdefl_small_dist_extra[512] = { + 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7 }; + +static const mz_uint8 s_tdefl_large_dist_sym[128] = { + 0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26, + 26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28, + 28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 }; + +static const mz_uint8 s_tdefl_large_dist_extra[128] = { + 0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, + 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, + 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 }; + +// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. +typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; +static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1) +{ + mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); + for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } + while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; + for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) + { + const mz_uint32* pHist = &hist[pass << 8]; + mz_uint offsets[256], cur_ofs = 0; + for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } + for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; + { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } + } + return pCur_syms; +} + +// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. +static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) +{ + int root, leaf, next, avbl, used, dpth; + if (n==0) return; else if (n==1) { A[0].m_key = 1; return; } + A[0].m_key += A[1].m_key; root = 0; leaf = 2; + for (next=1; next < n-1; next++) + { + if (leaf>=n || A[root].m_key=n || (root=0; next--) A[next].m_key = A[A[next].m_key].m_key+1; + avbl = 1; used = dpth = 0; root = n-2; next = n-1; + while (avbl>0) + { + while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; } + while (avbl>used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } + avbl = 2*used; dpth++; used = 0; + } +} + +// Limits canonical Huffman code table's max code size. +enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; +static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) +{ + int i; mz_uint32 total = 0; if (code_list_len <= 1) return; + for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; + for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); + while (total != (1UL << max_code_size)) + { + pNum_codes[max_code_size]--; + for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } + total--; + } +} + +static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) +{ + int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); + if (static_table) + { + for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; + } + else + { + tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; + int num_used_syms = 0; + const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; + for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } + + pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); + + for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; + + tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); + + MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); + for (i = 1, j = num_used_syms; i <= code_size_limit; i++) + for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); + } + + next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); + + for (i = 0; i < table_len; i++) + { + mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; + code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); + d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; + } +} + +#define TDEFL_PUT_BITS(b, l) do { \ + mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \ + d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \ + while (d->m_bits_in >= 8) { \ + if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ + d->m_bit_buffer >>= 8; \ + d->m_bits_in -= 8; \ + } \ +} MZ_MACRO_END + +#define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \ + if (rle_repeat_count < 3) { \ + d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ + while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ + } else { \ + d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ +} rle_repeat_count = 0; } } + +#define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \ + if (rle_z_count < 3) { \ + d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ + } else if (rle_z_count <= 10) { \ + d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ + } else { \ + d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ +} rle_z_count = 0; } } + +static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + +static void tdefl_start_dynamic_block(tdefl_compressor *d) +{ + int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; + mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; + + d->m_huff_count[0][256] = 1; + + tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); + tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); + + for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; + for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; + + memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); + memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); + total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; + + memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); + for (i = 0; i < total_code_sizes_to_pack; i++) + { + mz_uint8 code_size = code_sizes_to_pack[i]; + if (!code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + if (code_size != prev_code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; + } + else if (++rle_repeat_count == 6) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + } + prev_code_size = code_size; + } + if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } + + tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); + + TDEFL_PUT_BITS(2, 2); + + TDEFL_PUT_BITS(num_lit_codes - 257, 5); + TDEFL_PUT_BITS(num_dist_codes - 1, 5); + + for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; + num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); + for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); + + for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; ) + { + mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); + TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); + if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); + } +} + +static void tdefl_start_static_block(tdefl_compressor *d) +{ + mz_uint i; + mz_uint8 *p = &d->m_huff_code_sizes[0][0]; + + for (i = 0; i <= 143; ++i) *p++ = 8; + for ( ; i <= 255; ++i) *p++ = 9; + for ( ; i <= 279; ++i) *p++ = 7; + for ( ; i <= 287; ++i) *p++ = 8; + + memset(d->m_huff_code_sizes[1], 5, 32); + + tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); + tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); + + TDEFL_PUT_BITS(1, 2); +} + +static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + mz_uint8 *pOutput_buf = d->m_pOutput_buf; + mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; + mz_uint64 bit_buffer = d->m_bit_buffer; + mz_uint bits_in = d->m_bits_in; + +#define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); } + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + + if (flags & 1) + { + mz_uint s0, s1, n0, n1, sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + // This sequence coaxes MSVC into using cmov's vs. jmp's. + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + n0 = s_tdefl_small_dist_extra[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[match_dist >> 8]; + n1 = s_tdefl_large_dist_extra[match_dist >> 8]; + sym = (match_dist < 512) ? s0 : s1; + num_extra_bits = (match_dist < 512) ? n0 : n1; + + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + } + + if (pOutput_buf >= d->m_pOutput_buf_end) + return MZ_FALSE; + + *(mz_uint64*)pOutput_buf = bit_buffer; + pOutput_buf += (bits_in >> 3); + bit_buffer >>= (bits_in & ~7); + bits_in &= 7; + } + +#undef TDEFL_PUT_BITS_FAST + + d->m_pOutput_buf = pOutput_buf; + d->m_bits_in = 0; + d->m_bit_buffer = 0; + + while (bits_in) + { + mz_uint32 n = MZ_MIN(bits_in, 16); + TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); + bit_buffer >>= n; + bits_in -= n; + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#else +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + if (flags & 1) + { + mz_uint sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + if (match_dist < 512) + { + sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + } + else + { + sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; + } + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS + +static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) +{ + if (static_block) + tdefl_start_static_block(d); + else + tdefl_start_dynamic_block(d); + return tdefl_compress_lz_codes(d); +} + +static int tdefl_flush_block(tdefl_compressor *d, int flush) +{ + mz_uint saved_bit_buf, saved_bits_in; + mz_uint8 *pSaved_output_buf; + mz_bool comp_block_succeeded = MZ_FALSE; + int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; + mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; + + d->m_pOutput_buf = pOutput_buf_start; + d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; + + MZ_ASSERT(!d->m_output_flush_remaining); + d->m_output_flush_ofs = 0; + d->m_output_flush_remaining = 0; + + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); + d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); + + if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) + { + TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); + } + + TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); + + pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; + + if (!use_raw_block) + comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); + + // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. + if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && + ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) ) + { + mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + TDEFL_PUT_BITS(0, 2); + if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } + for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) + { + TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); + } + for (i = 0; i < d->m_total_lz_bytes; ++i) + { + TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); + } + } + // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. + else if (!comp_block_succeeded) + { + d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + tdefl_compress_block(d, MZ_TRUE); + } + + if (flush) + { + if (flush == TDEFL_FINISH) + { + if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } + if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } + } + else + { + mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } + } + } + + MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); + + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; + + if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) + { + if (d->m_pPut_buf_func) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) + return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); + } + else if (pOutput_buf_start == d->m_output_buf) + { + int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); + d->m_out_buf_ofs += bytes_to_copy; + if ((n -= bytes_to_copy) != 0) + { + d->m_output_flush_ofs = bytes_to_copy; + d->m_output_flush_remaining = n; + } + } + else + { + d->m_out_buf_ofs += n; + } + } + + return d->m_output_flush_remaining; +} + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES +#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p) +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint16 *s = (const mz_uint16*)(d->m_dict + pos), *p, *q; + mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; + for ( ; ; ) + { + for ( ; ; ) + { + if (--num_probes_left == 0) return; + #define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break; + TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; + } + if (!dist) break; q = (const mz_uint16*)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; + do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && + (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); + if (!probe_len) + { + *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; + } + else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q)) > match_len) + { + *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; + c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); + } + } +} +#else +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint8 *s = d->m_dict + pos, *p, *q; + mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; + for ( ; ; ) + { + for ( ; ; ) + { + if (--num_probes_left == 0) return; + #define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break; + TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; + } + if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; + if (probe_len > match_len) + { + *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; + c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; + } + } +} +#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +static mz_bool tdefl_compress_fast(tdefl_compressor *d) +{ + // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. + mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; + mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; + mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + + while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) + { + const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; + mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); + d->m_src_buf_left -= num_bytes_to_process; + lookahead_size += num_bytes_to_process; + + while (num_bytes_to_process) + { + mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); + memcpy(d->m_dict + dst_pos, d->m_pSrc, n); + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); + d->m_pSrc += n; + dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; + num_bytes_to_process -= n; + } + + dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); + if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; + + while (lookahead_size >= 4) + { + mz_uint cur_match_dist, cur_match_len = 1; + mz_uint8 *pCur_dict = d->m_dict + cur_pos; + mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; + mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; + mz_uint probe_pos = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)lookahead_pos; + + if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) + { + const mz_uint16 *p = (const mz_uint16 *)pCur_dict; + const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); + mz_uint32 probe_len = 32; + do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && + (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); + cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); + if (!probe_len) + cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; + + if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U))) + { + cur_match_len = 1; + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + else + { + mz_uint32 s0, s1; + cur_match_len = MZ_MIN(cur_match_len, lookahead_size); + + MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); + + cur_match_dist--; + + pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); + *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; + pLZ_code_buf += 3; + *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); + + s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; + s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; + d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; + + d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; + } + } + else + { + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + + if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } + + total_lz_bytes += cur_match_len; + lookahead_pos += cur_match_len; + dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; + MZ_ASSERT(lookahead_size >= cur_match_len); + lookahead_size -= cur_match_len; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; + } + } + + while (lookahead_size) + { + mz_uint8 lit = d->m_dict[cur_pos]; + + total_lz_bytes++; + *pLZ_code_buf++ = lit; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } + + d->m_huff_count[0][lit]++; + + lookahead_pos++; + dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + lookahead_size--; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; + } + } + } + + d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + return MZ_TRUE; +} +#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + +static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) +{ + d->m_total_lz_bytes++; + *d->m_pLZ_code_buf++ = lit; + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } + d->m_huff_count[0][lit]++; +} + +static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) +{ + mz_uint32 s0, s1; + + MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); + + d->m_total_lz_bytes += match_len; + + d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); + + match_dist -= 1; + d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); + d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; + + *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } + + s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; + d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; + + if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; +} + +static mz_bool tdefl_compress_normal(tdefl_compressor *d) +{ + const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; + tdefl_flush flush = d->m_flush; + + while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) + { + mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; + // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. + if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) + { + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; + mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); + const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; + src_buf_left -= num_bytes_to_process; + d->m_lookahead_size += num_bytes_to_process; + while (pSrc != pSrc_end) + { + mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); + dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; + } + } + else + { + while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + { + mz_uint8 c = *pSrc++; + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + src_buf_left--; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) + { + mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; + mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); + } + } + } + d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); + if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + break; + + // Simple lazy/greedy parsing state machine. + len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) + { + if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) + { + mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; + cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } + if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; + } + } + else + { + tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); + } + if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) + { + cur_match_dist = cur_match_len = 0; + } + if (d->m_saved_match_len) + { + if (cur_match_len > d->m_saved_match_len) + { + tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); + if (cur_match_len >= 128) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + d->m_saved_match_len = 0; len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; + } + } + else + { + tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); + len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; + } + } + else if (!cur_match_dist) + tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); + else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; + } + // Move the lookahead forward by len_to_move bytes. + d->m_lookahead_pos += len_to_move; + MZ_ASSERT(d->m_lookahead_size >= len_to_move); + d->m_lookahead_size -= len_to_move; + d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE); + // Check if it's time to flush the current LZ codes to the internal output buffer. + if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || + ( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) ) + { + int n; + d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + } + } + + d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; + return MZ_TRUE; +} + +static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) +{ + if (d->m_pIn_buf_size) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + } + + if (d->m_pOut_buf_size) + { + size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); + d->m_output_flush_ofs += (mz_uint)n; + d->m_output_flush_remaining -= (mz_uint)n; + d->m_out_buf_ofs += n; + + *d->m_pOut_buf_size = d->m_out_buf_ofs; + } + + return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) +{ + if (!d) + { + if (pIn_buf_size) *pIn_buf_size = 0; + if (pOut_buf_size) *pOut_buf_size = 0; + return TDEFL_STATUS_BAD_PARAM; + } + + d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; + d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; + d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; + d->m_out_buf_ofs = 0; + d->m_flush = flush; + + if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || + (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) ) + { + if (pIn_buf_size) *pIn_buf_size = 0; + if (pOut_buf_size) *pOut_buf_size = 0; + return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); + } + d->m_wants_to_finish |= (flush == TDEFL_FINISH); + + if ((d->m_output_flush_remaining) || (d->m_finished)) + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && + ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && + ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) + { + if (!tdefl_compress_fast(d)) + return d->m_prev_return_status; + } + else +#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + { + if (!tdefl_compress_normal(d)) + return d->m_prev_return_status; + } + + if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) + d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); + + if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) + { + if (tdefl_flush_block(d, flush) < 0) + return d->m_prev_return_status; + d->m_finished = (flush == TDEFL_FINISH); + if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } + } + + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); +} + +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) +{ + MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); +} + +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; + d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; + d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); + d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; + d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; + d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; + d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; + d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; + d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; + d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + return TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) +{ + return d->m_prev_return_status; +} + +mz_uint32 tdefl_get_adler32(tdefl_compressor *d) +{ + return d->m_adler32; +} + +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; + pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; + succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); + succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); + MZ_FREE(pComp); return succeeded; +} + +typedef struct +{ + size_t m_size, m_capacity; + mz_uint8 *m_pBuf; + mz_bool m_expandable; +} tdefl_output_buffer; + +static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) +{ + tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; + size_t new_size = p->m_size + len; + if (new_size > p->m_capacity) + { + size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; + do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); + pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; + p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; + } + memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; + return MZ_TRUE; +} + +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); + if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; + out_buf.m_expandable = MZ_TRUE; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; + *pOut_len = out_buf.m_size; return out_buf.m_pBuf; +} + +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); + if (!pOut_buf) return 0; + out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; + return out_buf.m_size; +} + +#ifndef MINIZ_NO_ZLIB_APIS +static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + +// level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) +{ + mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); + if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; + + if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; + else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; + else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; + else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; + else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; + + return comp_flags; +} +#endif //MINIZ_NO_ZLIB_APIS + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) +#endif + +// Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at +// http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) +{ + tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; + if (!pComp) return NULL; + MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57+MZ_MAX(64, (1+bpl)*h); if (NULL == (out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } + // write dummy header + for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); + // compress image data + tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, TDEFL_DEFAULT_MAX_PROBES | TDEFL_WRITE_ZLIB_HEADER); + for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8*)pImage + y * bpl, bpl, TDEFL_NO_FLUSH); } + if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } + // write real header + *pLen_out = out_buf.m_size-41; + { + mz_uint8 pnghdr[41]={0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52, + 0,0,(mz_uint8)(w>>8),(mz_uint8)w,0,0,(mz_uint8)(h>>8),(mz_uint8)h,8,"\0\0\04\02\06"[num_chans],0,0,0,0,0,0,0, + (mz_uint8)(*pLen_out>>24),(mz_uint8)(*pLen_out>>16),(mz_uint8)(*pLen_out>>8),(mz_uint8)*pLen_out,0x49,0x44,0x41,0x54}; + c=(mz_uint32)mz_crc32(MZ_CRC32_INIT,pnghdr+12,17); for (i=0; i<4; ++i, c<<=8) ((mz_uint8*)(pnghdr+29))[i]=(mz_uint8)(c>>24); + memcpy(out_buf.m_pBuf, pnghdr, 41); + } + // write footer (IDAT CRC-32, followed by IEND chunk) + if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+41-4, *pLen_out+4); for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-16)[i] = (mz_uint8)(c >> 24); + // compute final size of file, grab compressed data buffer and return + *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; +} + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +// ------------------- .ZIP archive reading + +#ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef MINIZ_NO_STDIO + #define MZ_FILE void * +#else + #include + #include + #if defined(_MSC_VER) || defined(__MINGW64__) + #include + #define MZ_FILE FILE + #define MZ_FOPEN fopen + #define MZ_FCLOSE fclose + #define MZ_FREAD fread + #define MZ_FWRITE fwrite + #define MZ_FTELL64 _ftelli64 + #define MZ_FSEEK64 _fseeki64 + #define MZ_FILE_STAT_STRUCT _stat + #define MZ_FILE_STAT _stat + #define MZ_FFLUSH fflush + #define MZ_FREOPEN freopen + #define MZ_DELETE_FILE remove + #elif defined(__MINGW32__) + #include + #define MZ_FILE FILE + #define MZ_FOPEN fopen + #define MZ_FCLOSE fclose + #define MZ_FREAD fread + #define MZ_FWRITE fwrite + #define MZ_FTELL64 ftello64 + #define MZ_FSEEK64 fseeko64 + #define MZ_FILE_STAT_STRUCT _stat + #define MZ_FILE_STAT _stat + #define MZ_FFLUSH fflush + #define MZ_FREOPEN freopen + #define MZ_DELETE_FILE remove + #else + #include + #define MZ_FILE FILE + #define MZ_FOPEN fopen + #define MZ_FCLOSE fclose + #define MZ_FREAD fread + #define MZ_FWRITE fwrite + #define MZ_FTELL64 ftello + #define MZ_FSEEK64 fseeko + #define MZ_FILE_STAT_STRUCT stat + #define MZ_FILE_STAT stat + #define MZ_FFLUSH fflush + #define MZ_FREOPEN freopen + #define MZ_DELETE_FILE remove + #endif // #ifdef _MSC_VER +#endif // #ifdef MINIZ_NO_STDIO + +#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) + +// Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. +enum +{ + // ZIP archive identifiers and record sizes + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, + // Central directory header record offsets + MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, + MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, + MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, + // Local directory header offsets + MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, + MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, + MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, + // End of central directory offsets + MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, +}; + +typedef struct +{ + void *m_p; + size_t m_size, m_capacity; + mz_uint m_element_size; +} mz_zip_array; + +struct mz_zip_internal_state_tag +{ + mz_zip_array m_central_dir; + mz_zip_array m_central_dir_offsets; + mz_zip_array m_sorted_central_dir_offsets; + MZ_FILE *m_pFile; + void *m_pMem; + size_t m_mem_size; + size_t m_mem_capacity; +}; + +#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] + +static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) +{ + pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); + memset(pArray, 0, sizeof(mz_zip_array)); +} + +static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) +{ + void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; + if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } + if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; + pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) +{ + if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) +{ + if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } + pArray->m_size = new_size; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) +{ + return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) +{ + size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; + memcpy((mz_uint8*)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); + return MZ_TRUE; +} + +#ifndef MINIZ_NO_TIME +static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) +{ + struct tm tm; + memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; + tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; + tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; + return mktime(&tm); +} + +static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) +{ + struct tm *tm = localtime(&time); + *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); + *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); +} +#endif + +#ifndef MINIZ_NO_STDIO +static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) +{ +#ifdef MINIZ_NO_TIME + (void)pFilename; *pDOS_date = *pDOS_time = 0; +#else + struct MZ_FILE_STAT_STRUCT file_stat; if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; + mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); +#endif // #ifdef MINIZ_NO_TIME + return MZ_TRUE; +} + +static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) +{ +#ifndef MINIZ_NO_TIME + struct utimbuf t; t.actime = access_time; t.modtime = modified_time; + return !utime(pFilename, &t); +#else + pFilename, access_time, modified_time; + return MZ_TRUE; +#endif // #ifndef MINIZ_NO_TIME +} +#endif + +static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) +{ + (void)flags; + if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return MZ_FALSE; + + if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; + if (!pZip->m_pFree) pZip->m_pFree = def_free_func; + if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; + + pZip->m_zip_mode = MZ_ZIP_MODE_READING; + pZip->m_archive_size = 0; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return MZ_FALSE; + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; pR++; + } + return (pL == pE) ? (l_len < r_len) : (l < r); +} + +#define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END + +// Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) +static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const int size = pZip->m_total_files; + int start = (size - 2) >> 1, end; + while (start >= 0) + { + int child, root = start; + for ( ; ; ) + { + if ((child = (root << 1) + 1) >= size) + break; + child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; + } + start--; + } + + end = size - 1; + while (end > 0) + { + int child, root = 0; + MZ_SWAP_UINT32(pIndices[end], pIndices[0]); + for ( ; ; ) + { + if ((child = (root << 1) + 1) >= end) + break; + child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; + } + end--; + } +} + +static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) +{ + mz_uint cdir_size, num_this_disk, cdir_disk_index; + mz_uint64 cdir_ofs; + mz_int64 cur_file_ofs; + const mz_uint8 *p; + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. + if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + // Find the end of central directory record by scanning the file from the end towards the beginning. + cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); + for ( ; ; ) + { + int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) + return MZ_FALSE; + for (i = n - 4; i >= 0; --i) + if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + break; + if (i >= 0) + { + cur_file_ofs += i; + break; + } + if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + return MZ_FALSE; + cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); + } + // Read and verify the end of central directory record. + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || + ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) + return MZ_FALSE; + + num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); + cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); + if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) + return MZ_FALSE; + + if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + + cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); + if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) + return MZ_FALSE; + + pZip->m_central_directory_file_ofs = cdir_ofs; + + if (pZip->m_total_files) + { + mz_uint i, n; + // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices. + if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) + return MZ_FALSE; + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) + return MZ_FALSE; + + // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported). + p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; + for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) + { + mz_uint total_header_size, comp_size, decomp_size, disk_index; + if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + return MZ_FALSE; + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) + return MZ_FALSE; + disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); + if ((disk_index != num_this_disk) && (disk_index != 1)) + return MZ_FALSE; + if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) + return MZ_FALSE; + if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) + return MZ_FALSE; + n -= total_header_size; p += total_header_size; + } + } + + if ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) + mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) +{ + if ((!pZip) || (!pZip->m_pRead)) + return MZ_FALSE; + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + pZip->m_archive_size = size; + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end(pZip); + return MZ_FALSE; + } + return MZ_TRUE; +} + +static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); + memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); + return s; +} + +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) +{ + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + pZip->m_archive_size = size; + pZip->m_pRead = mz_zip_mem_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pMem = (void *)pMem; + pZip->m_pState->m_mem_size = size; + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end(pZip); + return MZ_FALSE; + } + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) +{ + mz_uint64 file_size; + MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); + if (!pFile) + return MZ_FALSE; + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + return MZ_FALSE; + file_size = MZ_FTELL64(pFile); + if (!mz_zip_reader_init_internal(pZip, flags)) + { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + pZip->m_pRead = mz_zip_file_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = file_size; + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end(pZip); + return MZ_FALSE; + } + return MZ_TRUE; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_total_files : 0; +} + +static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index) +{ + if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return NULL; + return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); +} + +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint m_bit_flag; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if (!p) + return MZ_FALSE; + m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + return (m_bit_flag & 1); +} + +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint filename_len, internal_attr, external_attr; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if (!p) + return MZ_FALSE; + + internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + if ((!internal_attr) && ((external_attr & 0x10) != 0)) + return MZ_TRUE; + + filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_len) + { + if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') + return MZ_TRUE; + } + + return MZ_FALSE; +} + +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) +{ + mz_uint n; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if ((!p) || (!pStat)) + return MZ_FALSE; + + // Unpack the central directory record. + pStat->m_file_index = file_index; + pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); + pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); + pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); + pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); +#ifndef MINIZ_NO_TIME + pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); +#endif + pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); + pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + + // Copy as much of the filename and comment as possible. + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); + memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; + + n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); + pStat->m_comment_size = n; + memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; + + return MZ_TRUE; +} + +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) +{ + mz_uint n; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_buf_size) + { + n = MZ_MIN(n, filename_buf_size - 1); + memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pFilename[n] = '\0'; + } + return n + 1; +} + +static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) +{ + mz_uint i; + if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) + return 0 == memcmp(pA, pB, len); + for (i = 0; i < len; ++i) + if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) + return MZ_FALSE; + return MZ_TRUE; +} + +static MZ_FORCEINLINE int mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; pR++; + } + return (pL == pE) ? (int)(l_len - r_len) : (l - r); +} + +static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const int size = pZip->m_total_files; + const mz_uint filename_len = (mz_uint)strlen(pFilename); + int l = 0, h = size - 1; + while (l <= h) + { + int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); + if (!comp) + return file_index; + else if (comp < 0) + l = m + 1; + else + h = m - 1; + } + return -1; +} + +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) +{ + mz_uint file_index; size_t name_len, comment_len; + if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return -1; + if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_p)) + return mz_zip_reader_locate_file_binary_search(pZip, pName); + name_len = strlen(pName); if (name_len > 0xFFFF) return -1; + comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; + for (file_index = 0; file_index < pZip->m_total_files; file_index++) + { + const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); + mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + if (filename_len < name_len) + continue; + if (comment_len) + { + mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); + const char *pFile_comment = pFilename + filename_len + file_extra_len; + if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) + continue; + } + if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) + { + int ofs = filename_len - 1; + do + { + if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) + break; + } while (--ofs >= 0); + ofs++; + pFilename += ofs; filename_len -= ofs; + } + if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) + return file_index; + } + return -1; +} + +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + int status = TINFL_STATUS_DONE; + mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + tinfl_decompressor inflator; + + if ((buf_size) && (!pBuf)) + return MZ_FALSE; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if (!file_stat.m_comp_size) + return MZ_TRUE; + + // Encryption and patch files are not supported. + if (file_stat.m_bit_flag & (1 | 32)) + return MZ_FALSE; + + // This function only supports stored and deflate. + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return MZ_FALSE; + + // Ensure supplied output buffer is large enough. + needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; + if (buf_size < needed_size) + return MZ_FALSE; + + // Read and parse the local directory entry. + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return MZ_FALSE; + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + // The file is stored or the caller has requested the compressed data. + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) + return MZ_FALSE; + return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); + } + + // Decompress the file either directly from memory or from a file input buffer. + tinfl_init(&inflator); + + if (pZip->m_pState->m_pMem) + { + // Read directly from the archive in memory. + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else if (pUser_read_buf) + { + // Use a user provided read buffer. + if (!user_read_buf_size) + return MZ_FALSE; + pRead_buf = (mz_uint8 *)pUser_read_buf; + read_buf_size = user_read_buf_size; + read_buf_avail = 0; + comp_remaining = file_stat.m_uncomp_size; + } + else + { + // Temporarily allocate a read buffer. + read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); +#ifdef _MSC_VER + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) +#else + if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) +#endif + return MZ_FALSE; + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return MZ_FALSE; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + do + { + size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + out_buf_ofs += out_buf_size; + } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); + + if (status == TINFL_STATUS_DONE) + { + // Make sure the entire file was decompressed, and check its CRC. + if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) + status = TINFL_STATUS_FAILED; + } + + if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); +} + +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); +} + +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); +} + +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) +{ + mz_uint64 comp_size, uncomp_size, alloc_size; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + void *pBuf; + + if (pSize) + *pSize = 0; + if (!p) + return NULL; + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + + alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; +#ifdef _MSC_VER + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) +#else + if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) +#endif + return NULL; + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) + return NULL; + + if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return NULL; + } + + if (pSize) *pSize = (size_t)alloc_size; + return pBuf; +} + +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) +{ + int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); + if (file_index < 0) + { + if (pSize) *pSize = 0; + return MZ_FALSE; + } + return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); +} + +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; + mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf = NULL; void *pWrite_buf = NULL; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if (!file_stat.m_comp_size) + return MZ_TRUE; + + // Encryption and patch files are not supported. + if (file_stat.m_bit_flag & (1 | 32)) + return MZ_FALSE; + + // This function only supports stored and deflate. + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return MZ_FALSE; + + // Read and parse the local directory entry. + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return MZ_FALSE; + + // Decompress the file either directly from memory or from a file input buffer. + if (pZip->m_pState->m_pMem) + { + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return MZ_FALSE; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + // The file is stored or the caller has requested the compressed data. + if (pZip->m_pState->m_pMem) + { +#ifdef _MSC_VER + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) +#else + if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) +#endif + return MZ_FALSE; + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) + status = TINFL_STATUS_FAILED; + else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); + cur_file_ofs += file_stat.m_comp_size; + out_buf_ofs += file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + while (comp_remaining) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + + if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + out_buf_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + } + } + } + else + { + tinfl_decompressor inflator; + tinfl_init(&inflator); + + if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + status = TINFL_STATUS_FAILED; + else + { + do + { + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + + if (out_buf_size) + { + if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) + { + status = TINFL_STATUS_FAILED; + break; + } + file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); + if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) + { + status = TINFL_STATUS_FAILED; + break; + } + } + } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } + } + + if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + // Make sure the entire file was decompressed, and check its CRC. + if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) + status = TINFL_STATUS_FAILED; + } + + if (!pZip->m_pState->m_pMem) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + if (pWrite_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) +{ + (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE*)pOpaque); +} + +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) +{ + mz_bool status; + mz_zip_archive_file_stat file_stat; + MZ_FILE *pFile; + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + pFile = MZ_FOPEN(pDst_filename, "wb"); + if (!pFile) + return MZ_FALSE; + status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); + if (MZ_FCLOSE(pFile) == EOF) + return MZ_FALSE; +#ifndef MINIZ_NO_TIME + if (status) + mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); +#endif + return status; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_bool mz_zip_reader_end(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return MZ_FALSE; + + if (pZip->m_pState) + { + mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + MZ_FCLOSE(pState->m_pFile); + pState->m_pFile = NULL; + } +#endif // #ifndef MINIZ_NO_STDIO + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + } + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) +{ + int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); +} +#endif + +// ------------------- .ZIP archive writing + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } +static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } +#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) +#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) + +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) +{ + if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return MZ_FALSE; + + if (pZip->m_file_offset_alignment) + { + // Ensure user specified file offset alignment is a power of 2. + if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) + return MZ_FALSE; + } + + if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; + if (!pZip->m_pFree) pZip->m_pFree = def_free_func; + if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + pZip->m_archive_size = existing_size; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return MZ_FALSE; + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + return MZ_TRUE; +} + +static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); +#ifdef _MSC_VER + if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) +#else + if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) +#endif + return 0; + if (new_size > pState->m_mem_capacity) + { + void *pNew_block; + size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; + if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) + return 0; + pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; + } + memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); + pState->m_mem_size = (size_t)new_size; + return n; +} + +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) +{ + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pIO_opaque = pZip; + if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) + return MZ_FALSE; + if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) + { + if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) + { + mz_zip_writer_end(pZip); + return MZ_FALSE; + } + pZip->m_pState->m_mem_capacity = initial_allocation_size; + } + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) +{ + MZ_FILE *pFile; + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pIO_opaque = pZip; + if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) + return MZ_FALSE; + if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) + { + mz_zip_writer_end(pZip); + return MZ_FALSE; + } + pZip->m_pState->m_pFile = pFile; + if (size_to_reserve_at_beginning) + { + mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); + do + { + size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) + { + mz_zip_writer_end(pZip); + return MZ_FALSE; + } + cur_ofs += n; size_to_reserve_at_beginning -= n; + } while (size_to_reserve_at_beginning); + } + return MZ_TRUE; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) +{ + mz_zip_internal_state *pState; + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return MZ_FALSE; + // No sense in trying to write to an archive that's already at the support max size + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + pState = pZip->m_pState; + + if (pState->m_pFile) + { +#ifdef MINIZ_NO_STDIO + pFilename; return MZ_FALSE; +#else + // Archive is being read from stdio - try to reopen as writable. + if (pZip->m_pIO_opaque != pZip) + return MZ_FALSE; + if (!pFilename) + return MZ_FALSE; + pZip->m_pWrite = mz_zip_file_write_func; + if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) + { + // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. + mz_zip_reader_end(pZip); + return MZ_FALSE; + } +#endif // #ifdef MINIZ_NO_STDIO + } + else if (pState->m_pMem) + { + // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. + if (pZip->m_pIO_opaque != pZip) + return MZ_FALSE; + pState->m_mem_capacity = pState->m_mem_size; + pZip->m_pWrite = mz_zip_heap_write_func; + } + // Archive is being read via a user provided read function - make sure the user has specified a write function too. + else if (!pZip->m_pWrite) + return MZ_FALSE; + + // Start writing new files at the archive's current central directory location. + pZip->m_archive_size = pZip->m_central_directory_file_ofs; + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + pZip->m_central_directory_file_ofs = 0; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) +{ + return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); +} + +typedef struct +{ + mz_zip_archive *m_pZip; + mz_uint64 m_cur_archive_file_ofs; + mz_uint64 m_comp_size; +} mz_zip_writer_add_state; + +static mz_bool mz_zip_writer_add_put_buf_callback(const void* pBuf, int len, void *pUser) +{ + mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; + if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) + return MZ_FALSE; + pState->m_cur_archive_file_ofs += len; + pState->m_comp_size += len; + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) +{ + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; + size_t orig_central_dir_size = pState->m_central_dir.m_size; + mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + + // No zip64 support yet + if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) + return MZ_FALSE; + + if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) + { + // Try to push the central directory array back into its original state. + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) +{ + // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. + if (*pArchive_name == '/') + return MZ_FALSE; + while (*pArchive_name) + { + if ((*pArchive_name == '\\') || (*pArchive_name == ':')) + return MZ_FALSE; + pArchive_name++; + } + return MZ_TRUE; +} + +static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) +{ + mz_uint32 n; + if (!pZip->m_file_offset_alignment) + return 0; + n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); + return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); +} + +static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) +{ + char buf[4096]; + memset(buf, 0, MZ_MIN(sizeof(buf), n)); + while (n) + { + mz_uint32 s = MZ_MIN(sizeof(buf), n); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) + return MZ_FALSE; + cur_file_ofs += s; n -= s; + } + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) +{ + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + tdefl_compressor *pComp = NULL; + mz_bool store_data_uncompressed; + mz_zip_internal_state *pState; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + + pState = pZip->m_pState; + + if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) + return MZ_FALSE; + // No zip64 support yet + if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return MZ_FALSE; + +#ifndef MINIZ_NO_TIME + { + time_t cur_time; time(&cur_time); + mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); + } +#endif // #ifndef MINIZ_NO_TIME + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > 0xFFFF) + return MZ_FALSE; + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) + { + // Set DOS Subdirectory attribute bit. + ext_attributes |= 0x10; + // Subdirectories cannot contain data. + if ((buf_size) || (uncomp_size)) + return MZ_FALSE; + } + + // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) + if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) + return MZ_FALSE; + + if ((!store_data_uncompressed) && (buf_size)) + { + if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) + return MZ_FALSE; + } + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } + cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); + + MZ_CLEAR_OBJ(local_dir_header); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + cur_archive_file_ofs += archive_name_size; + + if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, buf_size); + uncomp_size = buf_size; + if (uncomp_size <= 3) + { + level = 0; + store_data_uncompressed = MZ_TRUE; + } + } + + if (store_data_uncompressed) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + cur_archive_file_ofs += buf_size; + comp_size = buf_size; + + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + method = MZ_DEFLATED; + } + else if (buf_size) + { + mz_zip_writer_add_state state; + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || + (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + + method = MZ_DEFLATED; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pComp = NULL; + + // no zip64 support yet + if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) + return MZ_FALSE; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return MZ_FALSE; + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; + mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + MZ_FILE *pSrc_file = NULL; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return MZ_FALSE; + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > 0xFFFF) + return MZ_FALSE; + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) + return MZ_FALSE; + + pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); + if (!pSrc_file) + return MZ_FALSE; + MZ_FSEEK64(pSrc_file, 0, SEEK_END); + uncomp_size = MZ_FTELL64(pSrc_file); + MZ_FSEEK64(pSrc_file, 0, SEEK_SET); + + if (uncomp_size > 0xFFFFFFFF) + { + // No zip64 support yet + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + if (uncomp_size <= 3) + level = 0; + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) + return MZ_FALSE; + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } + cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); + + MZ_CLEAR_OBJ(local_dir_header); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + cur_archive_file_ofs += archive_name_size; + + if (uncomp_size) + { + mz_uint64 uncomp_remaining = uncomp_size; + void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); + if (!pRead_buf) + { + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + if (!level) + { + while (uncomp_remaining) + { + mz_uint n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); + if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + uncomp_remaining -= n; + cur_archive_file_ofs += n; + } + comp_size = uncomp_size; + } + else + { + mz_bool result = MZ_FALSE; + mz_zip_writer_add_state state; + tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + for ( ; ; ) + { + size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE); + tdefl_status status; + + if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) + break; + + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); + uncomp_remaining -= in_buf_size; + + status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); + if (status == TDEFL_STATUS_DONE) + { + result = MZ_TRUE; + break; + } + else if (status != TDEFL_STATUS_OKAY) + break; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + + if (!result) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + + method = MZ_DEFLATED; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + } + + MZ_FCLOSE(pSrc_file); pSrc_file = NULL; + + // no zip64 support yet + if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) + return MZ_FALSE; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return MZ_FALSE; + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) +{ + mz_uint n, bit_flags, num_alignment_padding_bytes; + mz_uint64 comp_bytes_remaining, local_dir_header_ofs; + mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + size_t orig_central_dir_size; + mz_zip_internal_state *pState; + void *pBuf; const mz_uint8 *pSrc_central_header; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return MZ_FALSE; + if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) + return MZ_FALSE; + pState = pZip->m_pState; + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + cur_dst_file_ofs = pZip->m_archive_size; + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) + return MZ_FALSE; + cur_dst_file_ofs += num_alignment_padding_bytes; + local_dir_header_ofs = cur_dst_file_ofs; + if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) + return MZ_FALSE; + + while (comp_bytes_remaining) + { + n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + cur_src_file_ofs += n; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + cur_dst_file_ofs += n; + + comp_bytes_remaining -= n; + } + + bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + if (bit_flags & 8) + { + // Copy data descriptor + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + + n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + + cur_src_file_ofs += n; + cur_dst_file_ofs += n; + } + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + + // no zip64 support yet + if (cur_dst_file_ofs > 0xFFFFFFFF) + return MZ_FALSE; + + orig_central_dir_size = pState->m_central_dir.m_size; + + memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + return MZ_FALSE; + + n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + if (pState->m_central_dir.m_size > 0xFFFFFFFF) + return MZ_FALSE; + n = (mz_uint32)pState->m_central_dir.m_size; + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + pZip->m_total_files++; + pZip->m_archive_size = cur_dst_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState; + mz_uint64 central_dir_ofs, central_dir_size; + mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return MZ_FALSE; + + pState = pZip->m_pState; + + // no zip64 support yet + if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + central_dir_ofs = 0; + central_dir_size = 0; + if (pZip->m_total_files) + { + // Write central directory + central_dir_ofs = pZip->m_archive_size; + central_dir_size = pState->m_central_dir.m_size; + pZip->m_central_directory_file_ofs = central_dir_ofs; + if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) + return MZ_FALSE; + pZip->m_archive_size += central_dir_size; + } + + // Write end of central directory record + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) + return MZ_FALSE; +#ifndef MINIZ_NO_STDIO + if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) + return MZ_FALSE; +#endif // #ifndef MINIZ_NO_STDIO + + pZip->m_archive_size += sizeof(hdr); + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) +{ + if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) + return MZ_FALSE; + if (pZip->m_pWrite != mz_zip_heap_write_func) + return MZ_FALSE; + if (!mz_zip_writer_finalize_archive(pZip)) + return MZ_FALSE; + + *pBuf = pZip->m_pState->m_pMem; + *pSize = pZip->m_pState->m_mem_size; + pZip->m_pState->m_pMem = NULL; + pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_end(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState; + mz_bool status = MZ_TRUE; + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) + return MZ_FALSE; + + pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + MZ_FCLOSE(pState->m_pFile); + pState->m_pFile = NULL; + } +#endif // #ifndef MINIZ_NO_STDIO + + if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); + pState->m_pMem = NULL; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + return status; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + mz_bool status, created_new_archive = MZ_FALSE; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + MZ_CLEAR_OBJ(zip_archive); + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return MZ_FALSE; + if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) + { + // Create a new archive. + if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) + return MZ_FALSE; + created_new_archive = MZ_TRUE; + } + else + { + // Append to an existing archive. + if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) + return MZ_FALSE; + if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) + { + mz_zip_reader_end(&zip_archive); + return MZ_FALSE; + } + } + status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); + // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) + if (!mz_zip_writer_finalize_archive(&zip_archive)) + status = MZ_FALSE; + if (!mz_zip_writer_end(&zip_archive)) + status = MZ_FALSE; + if ((!status) && (created_new_archive)) + { + // It's a new archive and something went wrong, so just delete it. + int ignoredStatus = MZ_DELETE_FILE(pZip_filename); + (void)ignoredStatus; + } + return status; +} + +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) +{ + int file_index; + mz_zip_archive zip_archive; + void *p = NULL; + + if (pSize) + *pSize = 0; + + if ((!pZip_filename) || (!pArchive_name)) + return NULL; + + MZ_CLEAR_OBJ(zip_archive); + if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) + return NULL; + + if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) + p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); + + mz_zip_reader_end(&zip_archive); + return p; +} + +#endif // #ifndef MINIZ_NO_STDIO + +#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +#endif // #ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef __cplusplus +} +#endif + +#endif // MINIZ_HEADER_FILE_ONLY + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + For more information, please refer to +*/ diff --git a/tools/usResourceCompiler.cpp b/tools/usResourceCompiler.cpp new file mode 100644 index 0000000000..443cd9c46f --- /dev/null +++ b/tools/usResourceCompiler.cpp @@ -0,0 +1,827 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usConfig.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "stdint_p.h" + +#include "usConfig.h" + +#ifdef US_ENABLE_RESOURCE_COMPRESSION +extern "C" { +const char* us_resource_compressor_error(); +unsigned char* us_resource_compressor(FILE*, long, int level, long* out_size); +} +#endif // US_ENABLE_RESOURCE_COMPRESSION + +#ifdef US_PLATFORM_WINDOWS +static const char DIR_SEP = '\\'; +#else +static const char DIR_SEP = '/'; +#endif + +class ResourceWriter; + +class Resource +{ + +public: + + enum Flags + { + NoFlags = 0x00, + Directory = 0x01, + Compressed = 0x02 + }; + + Resource(const std::string& name, const std::string& path = std::string(), unsigned int flags = NoFlags); + ~Resource(); + + std::string GetResourcePath() const; + + int64_t WriteName(ResourceWriter& writer, int64_t offset); + void WriteTreeInfo(ResourceWriter& writer); + int64_t WritePayload(ResourceWriter& writer, int64_t offset, std::string* errorMessage); + + std::string name; + std::string path; + unsigned int flags; + Resource* parent; + std::map children; + std::map sortedChildren; + + int64_t nameOffset; + int64_t dataOffset; + int64_t childOffset; + +}; + +class ResourceWriter +{ + +public: + + ResourceWriter(const std::string& fileName, const std::string& libName, + int compressionLevel, int compressionThreshold); + ~ResourceWriter(); + + bool AddFiles(const std::vector& files, const std::string& basePath); + bool Write(); + +private: + + friend class Resource; + + bool AddFile(const std::string& alias, const Resource& file); + + bool WriteHeader(); + bool WritePayloads(); + bool WriteNames(); + bool WriteDataTree(); + bool WriteRegistrationCode(); + + void WriteString(const std::string& str); + void WriteChar(char c); + void WriteHex(uint8_t tmp); + void WriteNumber2(uint16_t number); + void WriteNumber4(uint32_t number); + + std::ofstream out; + std::vector files; + + std::string libName; + std::string fileName; + + int compressionLevel; + int compressionThreshold; + + Resource* root; +}; + +Resource::Resource(const std::string& name, const std::string& path, unsigned int flags) + : name(name) + , path(path) + , flags(flags) + , parent(NULL) + , nameOffset(0) + , dataOffset(0) + , childOffset(0) +{ +} + +Resource::~Resource() +{ + for (std::map::iterator i = children.begin(); + i != children.end(); ++i) + { + delete i->second; + } +} + +std::string Resource::GetResourcePath() const +{ + std::string resource = name; + for (Resource* p = parent; p; p = p->parent) + { + resource = resource.insert(0, p->name + '/'); + } + return resource; +} + +int64_t Resource::WriteName(ResourceWriter& writer, int64_t offset) +{ + // capture the offset + nameOffset = offset; + + // write the resource name as a comment + writer.WriteString(" // "); + writer.WriteString(name); + writer.WriteString("\n "); + + // write the length of the name + writer.WriteNumber2(static_cast(name.size())); + writer.WriteString("\n "); + offset += 2; + + // write the hash value + writer.WriteNumber4(static_cast(US_HASH_FUNCTION_NAMESPACE::US_HASH_FUNCTION(std::string, name))); + writer.WriteString("\n "); + offset += 4; + + // write the name itself + for (std::size_t i = 0; i < name.length(); ++i) + { + writer.WriteHex(name[i]); + if (i != 0 && i % 32 == 0) + writer.WriteString("\n "); + } + offset += name.length(); + + // done + writer.WriteString("\n "); + return offset; +} + +void Resource::WriteTreeInfo(ResourceWriter& writer) +{ + // write the resource path as a comment + writer.WriteString(" // "); + writer.WriteString(GetResourcePath()); + writer.WriteString("\n "); + + if (flags & Directory) + { + // name offset (in the us_resource_name array) + writer.WriteNumber4(static_cast(nameOffset)); + + // flags + writer.WriteNumber2(flags); + + // child count + writer.WriteNumber4(static_cast(children.size())); + + // first child offset (in the us_resource_tree array) + writer.WriteNumber4(static_cast(childOffset)); + } + else + { + // name offset + writer.WriteNumber4(static_cast(nameOffset)); + + // flags + writer.WriteNumber2(flags); + + // padding (not used) + writer.WriteNumber4(0); + + // data offset + writer.WriteNumber4(static_cast(dataOffset)); + } + writer.WriteChar('\n'); +} + +int64_t Resource::WritePayload(ResourceWriter& writer, int64_t offset, std::string* errorMessage) +{ + // capture the offset + dataOffset = offset; + + // open the resource file on the file system + FILE* file = fopen(path.c_str(), "rb"); + if (!file) + { + *errorMessage = "File could not be opened: " + path; + return 0; + } + + // get the file size + fseek(file, 0, SEEK_END); + const long fileSize = ftell(file); + fseek(file, 0, SEEK_SET); + + unsigned char* fileBuffer = NULL; + long fileBufferSize = 0; + +#ifdef US_ENABLE_RESOURCE_COMPRESSION + // try compression + if (writer.compressionLevel != 0 && fileSize != 0) + { + long compressedSize = 0; + unsigned char* compressedBuffer = us_resource_compressor(file, fileSize, writer.compressionLevel, &compressedSize); + if (compressedBuffer == NULL) + { + *errorMessage = us_resource_compressor_error(); + return 0; + } + + int compressRatio = static_cast((100.0 * (fileSize - compressedSize)) / fileSize); + if (compressRatio >= writer.compressionThreshold) + { + fileBuffer = compressedBuffer; + fileBufferSize = compressedSize; + flags |= Compressed; + } + else + { + free(compressedBuffer); + } + } + + if (!(flags & Compressed)) +#endif // US_ENABLE_RESOURCE_COMPRESSION + { + fileBuffer = static_cast(malloc(sizeof(unsigned char)*fileSize)); + if (fileBuffer == NULL) + { + *errorMessage = "Could not allocate memory buffer for resource file " + path; + return 0; + } + if (fseek(file, 0, SEEK_SET) != 0) + { + free(fileBuffer); + *errorMessage = "Could not set stream position for resource file " + path; + return 0; + } + if (fread(fileBuffer, 1, fileSize, file) != static_cast(fileSize)) + { + free(fileBuffer); + *errorMessage = "Error reading resource file " + path; + return 0; + } + fileBufferSize = fileSize; + } + + if (fclose(file)) + { + *errorMessage = "Error closing resource file " + path; + free(fileBuffer); + return 0; + } + + // write the full path of the resource in the file system as a comment + writer.WriteString(" // "); + writer.WriteString(path); + writer.WriteString("\n "); + + // write the length + writer.WriteNumber4(static_cast(fileBufferSize)); + writer.WriteString("\n "); + offset += 4; + + // write the actual payload + int charsLeft = 16; + for (long i = 0; i < fileBufferSize; ++i) + { + --charsLeft; + writer.WriteHex(static_cast(fileBuffer[i])); + if (charsLeft == 0) + { + writer.WriteString("\n "); + charsLeft = 16; + } + } + + offset += fileBufferSize; + + free(fileBuffer); + + // done + writer.WriteString("\n "); + return offset; +} + +ResourceWriter::ResourceWriter(const std::string& fileName, const std::string& libName, + int compressionLevel, int compressionThreshold) + : libName(libName) + , fileName(fileName) + , compressionLevel(compressionLevel) + , compressionThreshold(compressionThreshold) + , root(NULL) +{ + out.exceptions(std::ofstream::goodbit); + out.open(fileName.c_str()); +} + +ResourceWriter::~ResourceWriter() +{ + delete root; +} + +bool ResourceWriter::AddFiles(const std::vector& files, const std::string& basePath) +{ + bool success = true; + for (std::size_t i = 0; i < files.size(); ++i) + { + const std::string& file = files[i]; + if (file.size() <= basePath.size() || file.substr(0, basePath.size()) != basePath) + { + std::cerr << "File " << file << " is not an absolute path starting with " << basePath << std::endl; + success = false; + } + else + { + const std::string relativePath = file.substr(basePath.size()); + std::string name = relativePath; + std::size_t index = relativePath.find_last_of(DIR_SEP); + if (index != std::string::npos) + { + name = relativePath.substr(index+1); + } + success &= AddFile(relativePath, Resource(name, file)); + } + } + return success; +} + +bool ResourceWriter::Write() +{ + if (!WriteHeader()) + { + std::cerr << "Could not write header." << std::endl; + return false; + } + if (!WritePayloads()) + { + std::cerr << "Could not write data blobs." << std::endl; + return false; + } + if (!WriteNames()) + { + std::cerr << "Could not write file names." << std::endl; + return false; + } + if (!WriteDataTree()) + { + std::cerr << "Could not write data tree." << std::endl; + return false; + } + if (!WriteRegistrationCode()) + { + std::cerr << "Could not write footer" << std::endl; + return false; + } + + return true; +} + +bool ResourceWriter::AddFile(const std::string& alias, const Resource& file) +{ + std::ifstream in(file.path.c_str(), std::ifstream::in | std::ifstream::binary); + if (!in) + { + std::cerr << "File could not be opened: " << file.path << std::endl; + return false; + } + in.seekg(0, std::ifstream::end); + std::ifstream::pos_type size = in.tellg(); + in.close(); + + if (size > 0xffffffff) + { + std::cerr << "File too big: " << file.path << std::endl; + return false; + } + + if (!root) + { + root = new Resource(std::string(), std::string(), Resource::Directory); + } + + Resource* parent = root; + std::stringstream ss(alias); + std::vector nodes; + { + std::string node; + while (std::getline(ss, node, DIR_SEP)) + { + if (node.empty()) + continue; + nodes.push_back(node); + } + } + + for(std::size_t i = 0; i < nodes.size()-1; ++i) + { + const std::string& node = nodes[i]; + if (parent->children.find(node) == parent->children.end()) + { + Resource* s = new Resource(node, std::string(), Resource::Directory); + s->parent = parent; + parent->children.insert(std::make_pair(node, s)); + parent->sortedChildren.insert(std::make_pair(static_cast(US_HASH_FUNCTION_NAMESPACE::US_HASH_FUNCTION(std::string, node)), s)); + parent = s; + } + else + { + parent = parent->children[node]; + } + } + + const std::string filename = nodes.back(); + Resource* s = new Resource(file); + s->parent = parent; + parent->children.insert(std::make_pair(filename, s)); + parent->sortedChildren.insert(std::make_pair(static_cast(US_HASH_FUNCTION_NAMESPACE::US_HASH_FUNCTION(std::string, filename)), s)); + return true; +} + +bool ResourceWriter::WriteHeader() +{ + std::stringstream ss; + std::time_t now = time(0); + ss << std::ctime(&now); + + WriteString("/*=============================================================================\n"); + WriteString(" Resource object code\n"); + WriteString("\n"); + WriteString(" Created: "); + WriteString(ss.str()); + WriteString(" by: The Resource Compiler for CppMicroServices version "); + WriteString(CppMicroServices_VERSION_STR); + WriteString("\n\n"); + WriteString(" WARNING! All changes made in this file will be lost!\n"); + WriteString( "=============================================================================*/\n\n"); + WriteString("#include \n"); + WriteString("#include \n\n"); + return true; +} + +bool ResourceWriter::WritePayloads() +{ + if (!root) + return false; + + WriteString("static const unsigned char us_resource_data[] = {\n"); + std::stack pending; + + pending.push(root); + int64_t offset = 0; + std::string errorMessage; + while (!pending.empty()) + { + Resource* file = pending.top(); + pending.pop(); + for (std::map::iterator i = file->children.begin(); + i != file->children.end(); ++i) + { + Resource* child = i->second; + if (child->flags & Resource::Directory) + { + pending.push(child); + } + else + { + offset = child->WritePayload(*this, offset, &errorMessage); + if (offset == 0) + { + std::cerr << errorMessage << std::endl; + return false; + } + } + } + } + WriteString("\n};\n\n"); + return true; +} + +bool ResourceWriter::WriteNames() +{ + if (!root) + return false; + + WriteString("static const unsigned char us_resource_name[] = {\n"); + + std::map names; + std::stack pending; + + pending.push(root); + int64_t offset = 0; + while (!pending.empty()) + { + Resource* file = pending.top(); + pending.pop(); + for (std::map::iterator it = file->children.begin(); + it != file->children.end(); ++it) + { + Resource* child = it->second; + if (child->flags & Resource::Directory) + { + pending.push(child); + } + if (names.find(child->name) != names.end()) + { + child->nameOffset = names[child->name]; + } + else + { + names.insert(std::make_pair(child->name, offset)); + offset = child->WriteName(*this, offset); + } + } + } + WriteString("\n};\n\n"); + return true; +} + +bool ResourceWriter::WriteDataTree() +{ + if (!root) + return false; + + WriteString("static const unsigned char us_resource_tree[] = {\n"); + std::stack pending; + + // calculate the child offsets in the us_resource_tree array + pending.push(root); + int offset = 1; + while (!pending.empty()) + { + Resource* file = pending.top(); + pending.pop(); + file->childOffset = offset; + + // calculate the offset now + for (std::map::iterator i = file->sortedChildren.begin(); + i != file->sortedChildren.end(); ++i) + { + Resource* child = i->second; + ++offset; + if (child->flags & Resource::Directory) + { + pending.push(child); + } + } + } + + // write the tree structure + pending.push(root); + root->WriteTreeInfo(*this); + while (!pending.empty()) + { + Resource *file = pending.top(); + pending.pop(); + + // write the actual data now + for (std::map::iterator i = file->sortedChildren.begin(); + i != file->sortedChildren.end(); ++i) + { + Resource *child = i->second; + child->WriteTreeInfo(*this); + if (child->flags & Resource::Directory) + { + pending.push(child); + } + } + } + WriteString("\n};\n\n"); + + return true; +} + +bool ResourceWriter::WriteRegistrationCode() +{ + WriteString("US_BEGIN_NAMESPACE\n\n"); + WriteString("extern US_EXPORT bool RegisterResourceData(int, ModuleInfo*, ModuleInfo::ModuleResourceData, ModuleInfo::ModuleResourceData, ModuleInfo::ModuleResourceData);\n\n"); + WriteString("US_END_NAMESPACE\n\n"); + + WriteString(std::string("extern \"C\" US_ABI_EXPORT int _us_init_resources_") + libName + + "(US_PREPEND_NAMESPACE(ModuleInfo)* moduleInfo)\n"); + WriteString("{\n"); + WriteString(" US_PREPEND_NAMESPACE(RegisterResourceData)(0x01, moduleInfo, us_resource_tree, us_resource_name, us_resource_data);\n"); + WriteString(" return 1;\n"); + WriteString("}\n"); + + return true; +} + +void ResourceWriter::WriteString(const std::string& str) +{ + out << str; +} + +void ResourceWriter::WriteChar(char c) +{ + out << c; +} + +void ResourceWriter::WriteHex(uint8_t tmp) +{ + const char* const digits = "0123456789abcdef"; + WriteChar('0'); + WriteChar('x'); + if (tmp < 16) + { + WriteChar(digits[tmp]); + } + else + { + WriteChar(digits[tmp >> 4]); + WriteChar(digits[tmp & 0xf]); + } + WriteChar(','); +} + +void ResourceWriter::WriteNumber2(uint16_t number) +{ + WriteHex(number >> 8); + WriteHex(static_cast(number)); +} + +void ResourceWriter::WriteNumber4(uint32_t number) +{ + WriteHex(number >> 24); + WriteHex(number >> 16); + WriteHex(number >> 8); + WriteHex(number); +} + + +#ifdef US_PLATFORM_POSIX +#include +std::string GetCurrentDir() +{ + char currDir[512]; + if (!getcwd(currDir, sizeof(currDir))) + { + std::cerr << "Getting the current directory failed." << std::endl; + exit(EXIT_FAILURE); + } + return std::string(currDir); +} + +bool IsAbsolutePath(const std::string& path) +{ + return path.find_first_of('/') == 0; +} +#else +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include +std::string GetCurrentDir() +{ + TCHAR currDir[512]; + DWORD dwRet; + dwRet = GetCurrentDirectory(sizeof(currDir), currDir); + + if( dwRet == 0 || dwRet > 512) + { + std::cerr << "Getting the current directory failed." << std::endl; + exit(EXIT_FAILURE); + } + return std::string(currDir); +} + +bool IsAbsolutePath(const std::string& path) +{ + return !PathIsRelative(path.c_str()); +} +#endif + +int main(int argc, char** argv) +{ + if (argc < 4) + { + std::cout << US_RCC_EXECUTABLE_NAME " - A resource compiler for C++ Micro Services modules\n" + "\n" + "Usage: " US_RCC_EXECUTABLE_NAME " LIBNAME OUTPUT INPUT... " + "[-c COMPRESSION_LEVEL] [-t COMPRESSION_THRESHOLD] [-d ROOT_DIR INPUT...]...\n\n" + "Convert all INPUT files into hex code written to OUTPUT.\n" + "\n" + " LIBNAME The modules library name as it is specified in the US_INITIALIZE_MODULE macro\n" + " OUTPUT Absolute path for the generated source file\n" + " INPUT Path to the resource file, relative to the current working directory or" + " the preceeding ROOT_DIR argument\n" + " -c The Zip compression level (0-9) or -1 [defaults to -1, the default level]\n" + " -t Size reduction threshold (0-100) to trigger compression [defaults to 30]\n" + " -d Absolute path to a directory containing resource files. All following INPUT" + " files must be relative to this root path\n"; + exit(EXIT_SUCCESS); + } + + std::string libName(argv[1]); + std::string fileName(argv[2]); + + // default zlib compression level + int compressionLevel = -1; + + // use compressed data if 30% reduction or better + int compressionThreshold = 30; + + std::map > inputFiles; + inputFiles.insert(std::make_pair(GetCurrentDir(), std::vector())); + + std::vector* currFiles = &inputFiles.begin()->second; + std::string currRootDir = inputFiles.begin()->first; + for (int i = 3; i < argc; i++) + { + if (std::strcmp(argv[i], "-d") == 0) + { + if (i == argc-1) + { + std::cerr << "No argument after -d given." << std::endl; + exit(EXIT_FAILURE); + } + currRootDir = argv[++i]; + inputFiles.insert(std::make_pair(currRootDir, std::vector())); + currFiles = &inputFiles[currRootDir]; + } + else if(std::strcmp(argv[i], "-c") == 0) + { + if (i == argc-1) + { + std::cerr << "No argument after -c given." << std::endl; + exit(EXIT_FAILURE); + } + compressionLevel = atoi(argv[++i]); + if (compressionLevel < -1 || compressionLevel > 10) + { + compressionLevel = -1; + } + } + else if(std::strcmp(argv[i], "-t") == 0) + { + if (i == argc-1) + { + std::cerr << "No argument after -t given." << std::endl; + exit(EXIT_FAILURE); + } + compressionThreshold = atoi(argv[++i]); + } + else + { + const std::string inputFile = argv[i]; + if (IsAbsolutePath(inputFile)) + { + currFiles->push_back(inputFile); + } + else + { + currFiles->push_back(currRootDir + DIR_SEP + inputFile); + } + } + } + + ResourceWriter writer(fileName, libName, compressionLevel, compressionThreshold); + for(std::map >::iterator i = inputFiles.begin(); + i != inputFiles.end(); ++i) + { + if (i->second.empty()) continue; + + if (!writer.AddFiles(i->second, i->first)) + { + return EXIT_FAILURE; + } + } + + return writer.Write() ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/tools/usResourceCompressor.c b/tools/usResourceCompressor.c new file mode 100644 index 0000000000..31e0ec28d6 --- /dev/null +++ b/tools/usResourceCompressor.c @@ -0,0 +1,141 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#define MINIZ_NO_TIME +#define MINIZ_NO_ARCHIVE_APIS +#include "miniz.c" + +#include +#include + +typedef unsigned char uint8; +typedef unsigned int uint; + +#define COMPRESS_MSG_BUFFER_SIZE 1024 +static char us_compress_error[COMPRESS_MSG_BUFFER_SIZE]; + +#define my_max(a,b) (((a) > (b)) ? (a) : (b)) +#define my_min(a,b) (((a) < (b)) ? (a) : (b)) + +#define BUF_SIZE (1024 * 1024) +static uint8 s_inbuf[BUF_SIZE]; + + +const char* us_resource_compressor_error() +{ + return us_compress_error; +} + +unsigned char* us_resource_compressor(FILE* pInfile, long file_loc, int level, long* out_size) +{ + const uint infile_size = (uint)file_loc; + z_stream stream; + uint infile_remaining = infile_size; + long bytes_written = 0; + unsigned char* s_outbuf = NULL; + + memset(us_compress_error, 0, COMPRESS_MSG_BUFFER_SIZE); + + if (file_loc < 0 || file_loc > INT_MAX) + { + sprintf(us_compress_error, "Resource too large to be processed."); + return NULL; + } + + s_outbuf = (unsigned char*)malloc(sizeof(unsigned char)*(infile_size+4)); + if (s_outbuf == NULL) + { + sprintf(us_compress_error, "Failed to allocate %d bytes for compression buffer.", infile_size); + return NULL; + } + + // Init the z_stream + memset(&stream, 0, sizeof(stream)); + stream.next_in = s_inbuf; + stream.avail_in = 0; + stream.next_out = s_outbuf+4; + stream.avail_out = infile_size; + + // Compression. + if (deflateInit2(&stream, level, MZ_DEFLATED, -MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY) != Z_OK) + { + sprintf(us_compress_error, "deflateInit() failed."); + free(s_outbuf); + return NULL; + } + + // Write the uncompressed file size in the first four bytes + s_outbuf[0] = (unsigned char)((file_loc & 0xff000000) >> 24); + s_outbuf[1] = (unsigned char)((file_loc & 0x00ff0000) >> 16); + s_outbuf[2] = (unsigned char)((file_loc & 0x0000ff00) >> 8); + s_outbuf[3] = (unsigned char)(file_loc & 0x000000ff); + + bytes_written = 4; + for ( ; ; ) + { + int status; + if (!stream.avail_in) + { + // Input buffer is empty, so read more bytes from input file. + uint n = my_min(BUF_SIZE, infile_remaining); + + if (fread(s_inbuf, 1, n, pInfile) != n) + { + sprintf(us_compress_error, "Failed reading from input file."); + free(s_outbuf); + return NULL; + } + + stream.next_in = s_inbuf; + stream.avail_in = n; + + infile_remaining -= n; + } + + status = deflate(&stream, infile_remaining ? Z_NO_FLUSH : Z_FINISH); + + if ((status == Z_STREAM_END) || (!stream.avail_out)) + { + // Output buffer is full, or compression is done. + bytes_written += infile_size - stream.avail_out; + break; + } + else if (status != Z_OK) + { + sprintf(us_compress_error, "deflate() failed with status %i.", status); + free(s_outbuf); + return NULL; + } + } + + if (deflateEnd(&stream) != Z_OK) + { + sprintf(us_compress_error, "deflateEnd() failed."); + free(s_outbuf); + return NULL; + } + + if (out_size != NULL) + { + *out_size = bytes_written; + } + return s_outbuf; +} diff --git a/usConfig.h.in b/usConfig.h.in new file mode 100644 index 0000000000..c855c1047d --- /dev/null +++ b/usConfig.h.in @@ -0,0 +1,237 @@ +/* + USCONFIG.h + this file is generated. Do not change! +*/ + +#ifndef USCONFIG_H +#define USCONFIG_H + +#cmakedefine US_BUILD_SHARED_LIBS +#cmakedefine CppMicroServices_EXPORTS +#cmakedefine US_ENABLE_AUTOLOADING_SUPPORT +#cmakedefine US_ENABLE_THREADING_SUPPORT +#cmakedefine US_ENABLE_SERVICE_FACTORY_SUPPORT +#cmakedefine US_ENABLE_RESOURCE_COMPRESSION +#cmakedefine US_USE_CXX11 +#cmakedefine US_GCC_RTTI_WORKAROUND_NEEDED + +///------------------------------------------------------------------- +// Version information +//------------------------------------------------------------------- + +#define CppMicroServices_VERSION_MAJOR @CppMicroServices_VERSION_MAJOR@ +#define CppMicroServices_VERSION_MINOR @CppMicroServices_VERSION_MINOR@ +#define CppMicroServices_VERSION_PATH @CppMicroServices_VERSION_PATCH@ +#define CppMicroServices_VERSION @CppMicroServices_VERSION@ +#define CppMicroServices_VERSION_STR "@CppMicroServices_VERSION@" + +///------------------------------------------------------------------- +// Macros used by the unit tests +//------------------------------------------------------------------- + +#define CppMicroServices_SOURCE_DIR "@CppMicroServices_SOURCE_DIR@" + +///------------------------------------------------------------------- +// Macros for import/export declarations +//------------------------------------------------------------------- + +#if defined(WIN32) + #define US_ABI_EXPORT __declspec(dllexport) + #define US_ABI_IMPORT __declspec(dllimport) + #define US_ABI_LOCAL +#else + #define US_ABI_EXPORT __attribute__ ((visibility ("default"))) + #define US_ABI_IMPORT __attribute__ ((visibility ("default"))) + #define US_ABI_LOCAL __attribute__ ((visibility ("hidden"))) +#endif + +#ifdef US_BUILD_SHARED_LIBS + // We are building a shared lib + #ifdef CppMicroServices_EXPORTS + #define US_EXPORT US_ABI_EXPORT + #else + #define US_EXPORT US_ABI_IMPORT + #endif +#else + // We are building a static lib + // Don't hide RTTI symbols of definitions in the C++ Micro Services + // headers that are included in DSOs with hidden visibility + #define US_EXPORT US_ABI_EXPORT +#endif + +//------------------------------------------------------------------- +// Namespace customization +//------------------------------------------------------------------- + +#define US_NAMESPACE @US_NAMESPACE@ + +#ifndef US_NAMESPACE /* user namespace */ + + # define US_PREPEND_NAMESPACE(name) ::name + # define US_USE_NAMESPACE + # define US_BEGIN_NAMESPACE + # define US_END_NAMESPACE + # define US_FORWARD_DECLARE_CLASS(name) class name; + # define US_FORWARD_DECLARE_STRUCT(name) struct name; + +#else /* user namespace */ + + # define US_PREPEND_NAMESPACE(name) ::US_NAMESPACE::name + # define US_USE_NAMESPACE using namespace ::US_NAMESPACE; + # define US_BEGIN_NAMESPACE namespace US_NAMESPACE { + # define US_END_NAMESPACE } + # define US_FORWARD_DECLARE_CLASS(name) \ + US_BEGIN_NAMESPACE class name; US_END_NAMESPACE + + # define US_FORWARD_DECLARE_STRUCT(name) \ + US_BEGIN_NAMESPACE struct name; US_END_NAMESPACE + + namespace US_NAMESPACE {} + +#endif /* user namespace */ + +//------------------------------------------------------------------- +// Platform defines +//------------------------------------------------------------------- + +#if defined(__APPLE__) + #define US_PLATFORM_APPLE +#endif + +#if defined(__linux__) + #define US_PLATFORM_LINUX +#endif + +#if defined(_WIN32) || defined(_WIN64) + #define US_PLATFORM_WINDOWS +#else + #define US_PLATFORM_POSIX +#endif + +//------------------------------------------------------------------- +// Macros for suppressing warnings +//------------------------------------------------------------------- + +#ifdef _MSC_VER +#define US_MSVC_PUSH_DISABLE_WARNING(wn) \ +__pragma(warning(push)) \ +__pragma(warning(disable:wn)) +#define US_MSVC_POP_WARNING \ +__pragma(warning(pop)) +#define US_MSVC_DISABLE_WARNING(wn) \ +__pragma(warning(disable:wn)) +#else +#define US_MSVC_PUSH_DISABLE_WARNING(wn) +#define US_MSVC_POP_WARNING +#define US_MSVC_DISABLE_WARNING(wn) +#endif + +// Do not warn about the usage of deprecated unsafe functions +US_MSVC_DISABLE_WARNING(4996) + +//------------------------------------------------------------------- +// Debuging & Logging +//------------------------------------------------------------------- + +#cmakedefine US_ENABLE_DEBUG_OUTPUT + +US_BEGIN_NAMESPACE + enum MsgType { DebugMsg = 0, InfoMsg = 1, WarningMsg = 2, ErrorMsg = 3 }; + typedef void (*MsgHandler)(MsgType, const char *); + US_EXPORT MsgHandler installMsgHandler(MsgHandler); +US_END_NAMESPACE + +//------------------------------------------------------------------- +// Hash Container +//------------------------------------------------------------------- + +#ifdef US_USE_CXX11 + + #include + #include + + #define US_HASH_FUNCTION_BEGIN(type) \ + template<> \ + struct hash : std::unary_function { \ + std::size_t operator()(const type& arg) const { + + #define US_HASH_FUNCTION_END } }; + + #define US_HASH_FUNCTION(type, arg) hash()(arg) + + #if defined(US_PLATFORM_WINDOWS) && (_MSC_VER < 1700) + #define US_HASH_FUNCTION_FRIEND(type) friend class ::std::hash + #else + #define US_HASH_FUNCTION_FRIEND(type) friend struct ::std::hash + #endif + + #define US_UNORDERED_MAP_TYPE ::std::unordered_map + #define US_UNORDERED_SET_TYPE ::std::unordered_set + + #define US_HASH_FUNCTION_NAMESPACE ::std + #define US_HASH_FUNCTION_NAMESPACE_BEGIN namespace std { + #define US_HASH_FUNCTION_NAMESPACE_END } + +#elif defined(__GNUC__) + + #include + #include + + #define US_HASH_FUNCTION_BEGIN(type) \ + template<> \ + struct hash : std::unary_function { \ + std::size_t operator()(const type& arg) const { + + #define US_HASH_FUNCTION_END } }; + + #define US_HASH_FUNCTION(type, arg) hash()(arg) + #define US_HASH_FUNCTION_FRIEND(type) friend struct ::std::tr1::hash + + #define US_UNORDERED_MAP_TYPE ::std::tr1::unordered_map + #define US_UNORDERED_SET_TYPE ::std::tr1::unordered_set + + #define US_HASH_FUNCTION_NAMESPACE ::std::tr1 + #define US_HASH_FUNCTION_NAMESPACE_BEGIN namespace std { namespace tr1 { + #define US_HASH_FUNCTION_NAMESPACE_END }} + +#elif _MSC_VER <= 1500 // Visual Studio 2008 and lower + + #include + #include + + #define US_HASH_FUNCTION_BEGIN(type) \ + template<> \ + inline std::size_t hash_value(const type& arg) { + + #define US_HASH_FUNCTION_END } + + #define US_HASH_FUNCTION(type, arg) hash_value(arg) + #define US_HASH_FUNCTION_FRIEND(type) friend std::size_t stdext::hash_value(const type&) + + #define US_UNORDERED_MAP_TYPE ::stdext::hash_map + #define US_UNORDERED_SET_TYPE ::stdext::hash_set + + #define US_HASH_FUNCTION_NAMESPACE ::stdext + #define US_HASH_FUNCTION_NAMESPACE_BEGIN namespace stdext { + #define US_HASH_FUNCTION_NAMESPACE_END } + +#endif + + +//------------------------------------------------------------------- +// Threading Configuration +//------------------------------------------------------------------- + +#ifdef US_ENABLE_THREADING_SUPPORT + #define US_DEFAULT_THREADING US_PREPEND_NAMESPACE(MultiThreaded) +#else + #define US_DEFAULT_THREADING US_PREPEND_NAMESPACE(SingleThreaded) +#endif + +//------------------------------------------------------------------- +// Header Availability +//------------------------------------------------------------------- + +#cmakedefine HAVE_STDINT + +#endif // USCONFIG_H