From 52394f3ad1ffd9f0939033d87233e6623c2a5770 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 12 May 2015 10:07:55 -0400 Subject: [PATCH 001/412] Updating version for 0.10.0 development Change-Id: Icadcd96d35a77b53452b3d794c607130d72fd0d6 --- Version.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Version.cmake b/Version.cmake index 375a62a36..62ba68739 100644 --- a/Version.cmake +++ b/Version.cmake @@ -9,7 +9,7 @@ # Version info set(SimpleITK_VERSION_MAJOR 0) -set(SimpleITK_VERSION_MINOR 9) +set(SimpleITK_VERSION_MINOR 10) set(SimpleITK_VERSION_PATCH 0) #set(SimpleITK_VERSION_TWEAK "") From f163378b0a9ebb6f339c6fe01a1e4d1b0de805cf Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 13 May 2015 08:23:41 -0400 Subject: [PATCH 002/412] Update SimpleITKExamples version Change-Id: I464ea2ddef8f8a43171dd6c22419d89d10a10e5c --- SuperBuild/External_SimpleITKExamples.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_SimpleITKExamples.cmake b/SuperBuild/External_SimpleITKExamples.cmake index 4cfd21e1f..be8c2db66 100644 --- a/SuperBuild/External_SimpleITKExamples.cmake +++ b/SuperBuild/External_SimpleITKExamples.cmake @@ -20,7 +20,7 @@ if (${BUILD_EXAMPLES} ) --no-warn-unused-cli -C "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" ${ep_common_args} - -DSimpleITK_DIR:PATH=${CMAKE_CURRENT_BINARY_DIR}/lib/cmake/SimpleITK-0.9/ + -DSimpleITK_DIR:PATH=${CMAKE_CURRENT_BINARY_DIR}/lib/cmake/SimpleITK-0.10/ -DCMAKE_SKIP_RPATH:BOOL=ON -DCMAKE_INSTALL_PREFIX:PATH= BUILD_COMMAND ${BUILD_COMMAND_STRING} From b3a46b08cf29b65fc9168c68d56ad02308504526 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 14 May 2015 14:54:50 -0400 Subject: [PATCH 003/412] Adding SimpleITK 0.9.0 Download URLs to doxygen Change-Id: I0ccfad14fb64c819cc6c8efda5b9e4934eb5897f --- Documentation/Doxygen/PythonDownloads.dox | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Documentation/Doxygen/PythonDownloads.dox b/Documentation/Doxygen/PythonDownloads.dox index 3de3fe696..bf7c3cc20 100644 --- a/Documentation/Doxygen/PythonDownloads.dox +++ b/Documentation/Doxygen/PythonDownloads.dox @@ -10,6 +10,25 @@ $ easy_install SimpleITK \endcode +\section v090 SimpleITK 0.9.0 + + \liSimpleITK-0.9.0-py2.6-linux-i686.egg + \liSimpleITK-0.9.0-py2.6-linux-x86_64.egg + \liSimpleITK-0.9.0-py2.6-macosx-10.6-universal.egg + \liSimpleITK-0.9.0-py2.7-linux-i686.egg + \liSimpleITK-0.9.0-py2.7-linux-x86_64.egg + \liSimpleITK-0.9.0-py2.7-macosx-10.6-intel.egg + \liSimpleITK-0.9.0-py2.7-win32.egg + \liSimpleITK-0.9.0-py2.7-win-amd64.egg + \liSimpleITK-0.9.0-py3.3-linux-i686.egg + \liSimpleITK-0.9.0-py3.3-linux-x86_64.egg + \liSimpleITK-0.9.0-py3.3-win32.egg + \liSimpleITK-0.9.0-py3.3-win-amd64.egg + \liSimpleITK-0.9.0-py3.4-linux-i686.egg + \liSimpleITK-0.9.0-py3.4-linux-x86_64.egg + \liSimpleITK-0.9.0-py3.4-win32.egg + \liSimpleITK-0.9.0-py3.4-win-amd64.egg + \section v081 SimpleITK 0.8.1 \liSimpleITK-0.8.1-py2.6-linux-i686.egg From a55f6b064bba5faabe6db2e7d796b92c05bbc4de Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 20 May 2015 14:06:09 -0400 Subject: [PATCH 004/412] Improve exception when unable to create ImageIO Add check for the file to exist and test if it can be opened for reading. Change-Id: I7fe1e732483cc216d4b6d86e3e099127c9e878b3 --- Code/IO/src/sitkImageReaderBase.cxx | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/Code/IO/src/sitkImageReaderBase.cxx b/Code/IO/src/sitkImageReaderBase.cxx index 986a7350a..92f687e75 100644 --- a/Code/IO/src/sitkImageReaderBase.cxx +++ b/Code/IO/src/sitkImageReaderBase.cxx @@ -20,6 +20,7 @@ #include "sitkMacro.h" #include "sitkExceptionObject.h" +#include // Include the Transform IO here, so that the IO factory registration // will occour. @@ -62,9 +63,20 @@ ::GetImageIOBase(const std::string &fileName) itk::ImageIOBase::Pointer iobase = itk::ImageIOFactory::CreateImageIO( fileName.c_str(), itk::ImageIOFactory::ReadMode); - if ( iobase.IsNull() ) - { - sitkExceptionMacro( "Unable to determine ImageIO reader for \"" << fileName << "\"" ); + + if ( iobase.IsNull() ) + { + if ( !itksys::SystemTools::FileExists( fileName.c_str() ) ) + { + sitkExceptionMacro( "The file \"" << fileName << "\" does not exist." ); + } + + if ( !bool(std::ifstream( fileName.c_str() )) ) + { + sitkExceptionMacro( "Unable to open \"" << fileName << "\" for reading." ); + } + + sitkExceptionMacro( "Unable to determine ImageIO reader for \"" << fileName << "\"" ); } // Read the image information From 13c0d411c92d7dca96cdf336a058c6e717b5e75e Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 20 May 2015 14:26:28 -0400 Subject: [PATCH 005/412] GetGitRevisionDescription: Fix issue referencing project source This commit fixes the module by consistently using PROJECT_SOURCE_DIR and PROJECT_BINARY_DIR variable. Thanks to Jean-Christophe Fillion-Robin for contributing this patch to the BRAINSTools project. --- CMake/GetGitRevisionDescription.cmake | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/CMake/GetGitRevisionDescription.cmake b/CMake/GetGitRevisionDescription.cmake index 53a0a41c5..cc02a99de 100644 --- a/CMake/GetGitRevisionDescription.cmake +++ b/CMake/GetGitRevisionDescription.cmake @@ -47,15 +47,19 @@ function(get_git_head_revision _refvar _hashvar) set(${_hashvar} "GIT-NOTFOUND" PARENT_SCOPE) return() endif() + + set(src_dir ${PROJECT_SOURCE_DIR}) + set(bin_dir ${PROJECT_BINARY_DIR}) + execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse --git-dir - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + WORKING_DIRECTORY ${src_dir} OUTPUT_VARIABLE GIT_DIR ERROR_VARIABLE error RESULT_VARIABLE failed OUTPUT_STRIP_TRAILING_WHITESPACE ) if(NOT IS_ABSOLUTE "${GIT_DIR}") - set(GIT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/${GIT_DIR}") + set(GIT_DIR "${src_dir}/${GIT_DIR}") endif() if(failed OR NOT EXISTS "${GIT_DIR}/HEAD") # not in git @@ -63,7 +67,7 @@ function(get_git_head_revision _refvar _hashvar) set(${_hashvar} "GITDIR-NOTFOUND" PARENT_SCOPE) return() endif() - set(GIT_DATA "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/git-data") + set(GIT_DATA "${bin_dir}/CMakeFiles/git-data") if(NOT EXISTS "${GIT_DATA}") file(MAKE_DIRECTORY "${GIT_DATA}") endif() @@ -79,7 +83,7 @@ function(get_git_head_revision _refvar _hashvar) set(HEAD_REF "") endif() execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse HEAD - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + WORKING_DIRECTORY ${src_dir} OUTPUT_VARIABLE HEAD_HASH OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_VARIABLE error RESULT_VARIABLE failed) @@ -94,8 +98,10 @@ endfunction() function(git_commits_since file _commits ) get_git_head_revision(ref head) + set(src_dir ${PROJECT_SOURCE_DIR}) + execute_process(COMMAND ${GIT_EXECUTABLE} rev-list ${head} -n 1 -- ${file} - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + WORKING_DIRECTORY ${src_dir} OUTPUT_VARIABLE tag OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_VARIABLE error RESULT_VARIABLE failed @@ -105,7 +111,7 @@ function(git_commits_since file _commits ) endif() execute_process(COMMAND ${GIT_EXECUTABLE} rev-list ${tag}..${head} - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + WORKING_DIRECTORY ${src_dir} OUTPUT_VARIABLE rev_list OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_VARIABLE error RESULT_VARIABLE failed @@ -132,6 +138,8 @@ function(git_describe _var) return() endif() + set(src_dir ${PROJECT_SOURCE_DIR}) + # TODO sanitize #if((${ARGN}" MATCHES "&&") OR # (ARGN MATCHES "||") OR @@ -143,7 +151,7 @@ function(git_describe _var) #message(STATUS "Arguments to execute_process: ${ARGN}") execute_process(COMMAND "${GIT_EXECUTABLE}" describe ${hash} ${ARGN} - WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" + WORKING_DIRECTORY "${src_dir}" RESULT_VARIABLE res OUTPUT_VARIABLE out ERROR_QUIET From fd06d0bdece7ca29c45fe4e81ab1d83c9136c3d5 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 20 May 2015 14:31:14 -0400 Subject: [PATCH 006/412] Replace tabs with spaces. Change-Id: Ic79c883050515991b7f18e32e737cce3a45ebd4e --- CMake/GetGitRevisionDescription.cmake | 172 +++++++++++++------------- 1 file changed, 86 insertions(+), 86 deletions(-) diff --git a/CMake/GetGitRevisionDescription.cmake b/CMake/GetGitRevisionDescription.cmake index cc02a99de..0b7a6308e 100644 --- a/CMake/GetGitRevisionDescription.cmake +++ b/CMake/GetGitRevisionDescription.cmake @@ -31,7 +31,7 @@ # http://www.boost.org/LICENSE_1_0.txt) if(__get_git_revision_description) - return() + return() endif() set(__get_git_revision_description YES) @@ -42,56 +42,56 @@ get_filename_component(_gitdescmoddir ${CMAKE_CURRENT_LIST_FILE} PATH) find_package(Git QUIET) function(get_git_head_revision _refvar _hashvar) - if(NOT GIT_EXECUTABLE) - set(${_refvar} "GIT-NOTFOUND" PARENT_SCOPE) - set(${_hashvar} "GIT-NOTFOUND" PARENT_SCOPE) - return() - endif() - - set(src_dir ${PROJECT_SOURCE_DIR}) - set(bin_dir ${PROJECT_BINARY_DIR}) - - execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse --git-dir - WORKING_DIRECTORY ${src_dir} - OUTPUT_VARIABLE GIT_DIR - ERROR_VARIABLE error - RESULT_VARIABLE failed - OUTPUT_STRIP_TRAILING_WHITESPACE - ) - if(NOT IS_ABSOLUTE "${GIT_DIR}") - set(GIT_DIR "${src_dir}/${GIT_DIR}") - endif() - if(failed OR NOT EXISTS "${GIT_DIR}/HEAD") - # not in git - set(${_refvar} "GITDIR-NOTFOUND" PARENT_SCOPE) - set(${_hashvar} "GITDIR-NOTFOUND" PARENT_SCOPE) - return() - endif() - set(GIT_DATA "${bin_dir}/CMakeFiles/git-data") - if(NOT EXISTS "${GIT_DATA}") - file(MAKE_DIRECTORY "${GIT_DATA}") - endif() - configure_file("${GIT_DIR}/HEAD" "${GIT_DATA}/HEAD" COPYONLY) - - file(STRINGS "${GIT_DIR}/HEAD" head LIMIT_COUNT 1 LIMIT_INPUT 1024) - if("${head}" MATCHES "^ref: (.*)$") - set(HEAD_REF "${CMAKE_MATCH_1}") - if(EXISTS "${GIT_DIR}/${HEAD_REF}") - configure_file("${GIT_DIR}/${HEAD_REF}" "${GIT_DATA}/HEAD-REF" COPYONLY) - endif() - else() - set(HEAD_REF "") - endif() - execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse HEAD - WORKING_DIRECTORY ${src_dir} - OUTPUT_VARIABLE HEAD_HASH OUTPUT_STRIP_TRAILING_WHITESPACE - ERROR_VARIABLE error - RESULT_VARIABLE failed) - if(failed) - set(HEAD_HASH "HEAD-HASH-NOTFOUND") - endif() - set(${_refvar} "${HEAD_REF}" PARENT_SCOPE) - set(${_hashvar} "${HEAD_HASH}" PARENT_SCOPE) + if(NOT GIT_EXECUTABLE) + set(${_refvar} "GIT-NOTFOUND" PARENT_SCOPE) + set(${_hashvar} "GIT-NOTFOUND" PARENT_SCOPE) + return() + endif() + + set(src_dir ${PROJECT_SOURCE_DIR}) + set(bin_dir ${PROJECT_BINARY_DIR}) + + execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse --git-dir + WORKING_DIRECTORY ${src_dir} + OUTPUT_VARIABLE GIT_DIR + ERROR_VARIABLE error + RESULT_VARIABLE failed + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + if(NOT IS_ABSOLUTE "${GIT_DIR}") + set(GIT_DIR "${src_dir}/${GIT_DIR}") + endif() + if(failed OR NOT EXISTS "${GIT_DIR}/HEAD") + # not in git + set(${_refvar} "GITDIR-NOTFOUND" PARENT_SCOPE) + set(${_hashvar} "GITDIR-NOTFOUND" PARENT_SCOPE) + return() + endif() + set(GIT_DATA "${bin_dir}/CMakeFiles/git-data") + if(NOT EXISTS "${GIT_DATA}") + file(MAKE_DIRECTORY "${GIT_DATA}") + endif() + configure_file("${GIT_DIR}/HEAD" "${GIT_DATA}/HEAD" COPYONLY) + + file(STRINGS "${GIT_DIR}/HEAD" head LIMIT_COUNT 1 LIMIT_INPUT 1024) + if("${head}" MATCHES "^ref: (.*)$") + set(HEAD_REF "${CMAKE_MATCH_1}") + if(EXISTS "${GIT_DIR}/${HEAD_REF}") + configure_file("${GIT_DIR}/${HEAD_REF}" "${GIT_DATA}/HEAD-REF" COPYONLY) + endif() + else() + set(HEAD_REF "") + endif() + execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse HEAD + WORKING_DIRECTORY ${src_dir} + OUTPUT_VARIABLE HEAD_HASH OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_VARIABLE error + RESULT_VARIABLE failed) + if(failed) + set(HEAD_HASH "HEAD-HASH-NOTFOUND") + endif() + set(${_refvar} "${HEAD_REF}" PARENT_SCOPE) + set(${_hashvar} "${HEAD_HASH}" PARENT_SCOPE) endfunction() # get the number of commits since the file has last been modified @@ -128,42 +128,42 @@ function(git_commits_since file _commits ) endfunction() function(git_describe _var) - get_git_head_revision(refspec hash) - if(NOT GIT_FOUND) - set(${_var} "GIT-NOTFOUND" PARENT_SCOPE) - return() - endif() - if(NOT hash) - set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE) - return() - endif() - - set(src_dir ${PROJECT_SOURCE_DIR}) - - # TODO sanitize - #if((${ARGN}" MATCHES "&&") OR - # (ARGN MATCHES "||") OR - # (ARGN MATCHES "\\;")) - # message("Please report the following error to the project!") - # message(FATAL_ERROR "Looks like someone's doing something nefarious with git_describe! Passed arguments ${ARGN}") - #endif() - - #message(STATUS "Arguments to execute_process: ${ARGN}") - - execute_process(COMMAND "${GIT_EXECUTABLE}" describe ${hash} ${ARGN} - WORKING_DIRECTORY "${src_dir}" - RESULT_VARIABLE res - OUTPUT_VARIABLE out - ERROR_QUIET - OUTPUT_STRIP_TRAILING_WHITESPACE) - if(NOT res EQUAL 0) - set(out "${out}-${res}-NOTFOUND") - endif() - - set(${_var} "${out}" PARENT_SCOPE) + get_git_head_revision(refspec hash) + if(NOT GIT_FOUND) + set(${_var} "GIT-NOTFOUND" PARENT_SCOPE) + return() + endif() + if(NOT hash) + set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE) + return() + endif() + + set(src_dir ${PROJECT_SOURCE_DIR}) + + # TODO sanitize + #if((${ARGN}" MATCHES "&&") OR + # (ARGN MATCHES "||") OR + # (ARGN MATCHES "\\;")) + # message("Please report the following error to the project!") + # message(FATAL_ERROR "Looks like someone's doing something nefarious with git_describe! Passed arguments ${ARGN}") + #endif() + + #message(STATUS "Arguments to execute_process: ${ARGN}") + + execute_process(COMMAND "${GIT_EXECUTABLE}" describe ${hash} ${ARGN} + WORKING_DIRECTORY "${src_dir}" + RESULT_VARIABLE res + OUTPUT_VARIABLE out + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + if(NOT res EQUAL 0) + set(out "${out}-${res}-NOTFOUND") + endif() + + set(${_var} "${out}" PARENT_SCOPE) endfunction() function(git_get_exact_tag _var) - git_describe(out --exact-match ${ARGN}) - set(${_var} "${out}" PARENT_SCOPE) + git_describe(out --exact-match ${ARGN}) + set(${_var} "${out}" PARENT_SCOPE) endfunction() From 859f231fb684728382dbbeb3e6f30eeb155be26f Mon Sep 17 00:00:00 2001 From: Ziv Yaniv Date: Wed, 27 May 2015 10:52:18 -0400 Subject: [PATCH 007/412] STYLE: change SetOptimizerAsLBFGSB parameter name to match other methods. Changed the parameter name from maximumNumberOfIterations to numberOfIterations, which is this parameter's name in all other methods. Change-Id: I50c04c377301a8287b26e88b2872a57b91e9a571 --- Code/Registration/include/sitkImageRegistrationMethod.h | 2 +- Code/Registration/src/sitkImageRegistrationMethod.cxx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Registration/include/sitkImageRegistrationMethod.h b/Code/Registration/include/sitkImageRegistrationMethod.h index d04a926bc..8f3f11496 100644 --- a/Code/Registration/include/sitkImageRegistrationMethod.h +++ b/Code/Registration/include/sitkImageRegistrationMethod.h @@ -280,7 +280,7 @@ namespace simple * \sa itk::LBFGSBOptimizerv4 */ Self& SetOptimizerAsLBFGSB(double gradientConvergenceTolerance = 1e-5, - unsigned int maximumNumberOfIterations = 500, + unsigned int numberOfIterations = 500, unsigned int maximumNumberOfCorrections = 5, unsigned int maximumNumberOfFunctionEvaluations = 2000, double costFunctionConvergenceFactor = 1e+7, diff --git a/Code/Registration/src/sitkImageRegistrationMethod.cxx b/Code/Registration/src/sitkImageRegistrationMethod.cxx index c727036a4..cdc546123 100644 --- a/Code/Registration/src/sitkImageRegistrationMethod.cxx +++ b/Code/Registration/src/sitkImageRegistrationMethod.cxx @@ -274,7 +274,7 @@ ImageRegistrationMethod::SetOptimizerAsGradientDescentLineSearch( double learnin ImageRegistrationMethod::Self& ImageRegistrationMethod::SetOptimizerAsLBFGSB( double gradientConvergenceTolerance, - unsigned int maximumNumberOfIterations, + unsigned int numberOfIterations, unsigned int maximumNumberOfCorrections, unsigned int maximumNumberOfFunctionEvaluations, double costFunctionConvergenceFactor, @@ -284,7 +284,7 @@ ImageRegistrationMethod::SetOptimizerAsLBFGSB( double gradientConvergenceToleran { m_OptimizerType = LBFGSB; m_OptimizerGradientConvergenceTolerance = gradientConvergenceTolerance; - m_OptimizerNumberOfIterations = maximumNumberOfIterations; + m_OptimizerNumberOfIterations = numberOfIterations; m_OptimizerMaximumNumberOfCorrections = maximumNumberOfCorrections; m_OptimizerMaximumNumberOfFunctionEvaluations = maximumNumberOfFunctionEvaluations; m_OptimizerCostFunctionConvergenceFactor = costFunctionConvergenceFactor; From ce43c831aa6bf137bcc6cf14b33c447520e8d2b9 Mon Sep 17 00:00:00 2001 From: Ziv Yaniv Date: Thu, 28 May 2015 11:35:07 -0400 Subject: [PATCH 008/412] Modified example to match parameter name change in SetOptimizerAsLBFGSB. Change-Id: I53db4e6e6c2edc2672c702121a0ea5b5e0dab217 --- Examples/ImageRegistrationMethodBSpline1.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/ImageRegistrationMethodBSpline1.py b/Examples/ImageRegistrationMethodBSpline1.py index e0b4bddbd..49d4a2444 100755 --- a/Examples/ImageRegistrationMethodBSpline1.py +++ b/Examples/ImageRegistrationMethodBSpline1.py @@ -48,7 +48,7 @@ def command_iteration(method) : R.SetMetricAsCorrelation() R.SetOptimizerAsLBFGSB(gradientConvergenceTolerance=1e-5, - maximumNumberOfIterations=100, + numberOfIterations=100, maximumNumberOfCorrections=5, maximumNumberOfFunctionEvaluations=1000, costFunctionConvergenceFactor=1e+7) From 0f53f1cb9fb981af636fdda62e2fd27c6e464a2a Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 1 Jun 2015 11:21:33 -0400 Subject: [PATCH 009/412] Adding ITK version information to the SimpleITK version info. Change-Id: I156fcca41fbb1333e76e23ec36a803f35971b884 --- Code/Common/include/sitkVersion.h | 6 ++++++ Code/Common/src/sitkVersion.cxx | 22 +++++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/Code/Common/include/sitkVersion.h b/Code/Common/include/sitkVersion.h index c4d2fcb5d..02ff2ad41 100644 --- a/Code/Common/include/sitkVersion.h +++ b/Code/Common/include/sitkVersion.h @@ -39,6 +39,12 @@ namespace simple static const std::string &VersionString(); static const std::string &BuildDate(); + + static unsigned int ITKMajorVersion(); + static unsigned int ITKMinorVersion(); + static unsigned int ITKPatchVersion(); + static const std::string &ITKVersionString(); + static const std::string &ExtendedVersionString(); std::string ToString() { return Version::ExtendedVersionString(); } }; diff --git a/Code/Common/src/sitkVersion.cxx b/Code/Common/src/sitkVersion.cxx index aca5f970f..ef8a25877 100644 --- a/Code/Common/src/sitkVersion.cxx +++ b/Code/Common/src/sitkVersion.cxx @@ -18,17 +18,21 @@ #include "sitkVersion.h" #include "sitkVersionConfig.h" +#include "itkConfigure.h" + namespace { std::string MakeExtendedVersionString() { std::ostringstream v; - v << "SimpleITK Version: " << itk::simple::Version::VersionString() << std::endl + v << "SimpleITK Version: " << itk::simple::Version::VersionString() + << " (ITK " << ITK_VERSION_STRING << ")" << std::endl << "Compiled: " << itk::simple::Version::BuildDate() << std::endl; return v.str(); } + static const std::string extendedVersionString = MakeExtendedVersionString(); } @@ -64,6 +68,22 @@ namespace itk static const std::string v( __DATE__ " " __TIME__ ); return v; } + unsigned int Version::ITKMajorVersion() + { + return ITK_VERSION_MAJOR; + } + unsigned int Version::ITKMinorVersion() + { + return ITK_VERSION_MINOR; + } + unsigned int Version::ITKPatchVersion() + { + return ITK_VERSION_PATCH; + } + const std::string &Version::ITKVersionString() + { + return std::string(ITK_VERSION_STRING); + } const std::string &Version::ExtendedVersionString() { return extendedVersionString; From f1e1ac3775415143c9afe7517f9d08fe6dee5c5e Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 1 Jun 2015 11:53:51 -0400 Subject: [PATCH 010/412] Update PCRE to 9.37 in Superbuild Change-Id: Ieb990467954266381f8771075c6a981c913cd979 --- SuperBuild/External_PCRE.cmake | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SuperBuild/External_PCRE.cmake b/SuperBuild/External_PCRE.cmake index f4a266122..3044cb937 100644 --- a/SuperBuild/External_PCRE.cmake +++ b/SuperBuild/External_PCRE.cmake @@ -19,8 +19,8 @@ if(NOT PCRE_DIR) # PCRE (Perl Compatible Regular Expressions) # - set(PCRE_TARGET_VERSION 8.36) - set(PCRE_DOWNLOAD_SOURCE_HASH "ff7b4bb14e355f04885cf18ff4125c98") + set(PCRE_TARGET_VERSION 8.37) + set(PCRE_DOWNLOAD_SOURCE_HASH "6e0cc6d1bdac7a4308151f9b3571b86e") # follow the standard EP_PREFIX locations set(pcre_binary_dir ${CMAKE_CURRENT_BINARY_DIR}/PCRE-prefix/src/PCRE-build) From d19375e0a0825a736ebd9354d288038d0a6169d9 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 1 Jun 2015 15:50:49 -0400 Subject: [PATCH 011/412] WIP: Adding local transform fixes Change-Id: I9477057ab88a4282667e7dea8a5988015ecf65a0 --- Code/Common/include/sitkBSplineTransform.h | 2 +- .../include/sitkDisplacementFieldTransform.h | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/Code/Common/include/sitkBSplineTransform.h b/Code/Common/include/sitkBSplineTransform.h index 52c03e38c..0920f2c57 100644 --- a/Code/Common/include/sitkBSplineTransform.h +++ b/Code/Common/include/sitkBSplineTransform.h @@ -38,7 +38,7 @@ class SITKCommon_EXPORT BSplineTransform typedef BSplineTransform Self; typedef Transform Superclass; - BSplineTransform(unsigned int dimensions, unsigned int order=3); + explicit BSplineTransform(unsigned int dimensions, unsigned int order=3); BSplineTransform( const BSplineTransform & ); diff --git a/Code/Common/include/sitkDisplacementFieldTransform.h b/Code/Common/include/sitkDisplacementFieldTransform.h index bd95b1c00..253373c4a 100644 --- a/Code/Common/include/sitkDisplacementFieldTransform.h +++ b/Code/Common/include/sitkDisplacementFieldTransform.h @@ -39,12 +39,22 @@ class SITKCommon_EXPORT DisplacementFieldTransform typedef DisplacementFieldTransform Self; typedef Transform Superclass; - DisplacementFieldTransform( unsigned int dimensions ); - DisplacementFieldTransform( Image &); + explicit DisplacementFieldTransform( unsigned int dimensions ); + + /** \brief Consume an image to construct a displacement field transform. + * + * \warning The input displacement image is transferred to the + * constructed transform object. The input image is modified to be a + * default constructed Image object. + * + * Image must be of sitkVectorFloat64 pixel type with the number of + * components equal to the image dimension. + * + */ + explicit DisplacementFieldTransform( Image &); DisplacementFieldTransform( const DisplacementFieldTransform & ); - explicit DisplacementFieldTransform( const Transform & ); DisplacementFieldTransform &operator=( const DisplacementFieldTransform & ); @@ -55,7 +65,7 @@ class SITKCommon_EXPORT DisplacementFieldTransform /** parameters */ // set displacement methods take ownership for the image and remove it Self &SetDisplacementField(Image &); - /** \todo The returned image is should not directly modify the + /** \todo The returned image should not directly modify the * internal displacement field. */ Image GetDisplacementField() const; From 71dd96fd25e9666803c5179868c96ece003112c5 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 2 Jun 2015 09:54:43 -0400 Subject: [PATCH 012/412] Using local static for itk version string This patch address compilation warnings about returning a reference to temporary. Change-Id: I91e05d6bb0df6838926200869a50f819409bfb88 --- Code/Common/src/sitkVersion.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Common/src/sitkVersion.cxx b/Code/Common/src/sitkVersion.cxx index ef8a25877..f39f9b098 100644 --- a/Code/Common/src/sitkVersion.cxx +++ b/Code/Common/src/sitkVersion.cxx @@ -32,7 +32,7 @@ std::string MakeExtendedVersionString() return v.str(); } - +static const std::string itkVersionString = ITK_VERSION_STRING; static const std::string extendedVersionString = MakeExtendedVersionString(); } @@ -82,7 +82,7 @@ namespace itk } const std::string &Version::ITKVersionString() { - return std::string(ITK_VERSION_STRING); + return itkVersionString; } const std::string &Version::ExtendedVersionString() { From b3ddca3198a2e57c3ea6786023f8c03a162cb92e Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Tue, 2 Jun 2015 10:30:51 -0400 Subject: [PATCH 013/412] Regenerate filters.csv for SimpleITK 0.9.0 The table comparing SimpleITK filters to ITK filters, filters.csv, has been regenerated for the latest version of SimpleITK, 0.9.0. Change-Id: I0e43203fa1d0158dafafe585243ad3328de7acff --- Utilities/filters.csv | 53 ++++++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 28 deletions(-) diff --git a/Utilities/filters.csv b/Utilities/filters.csv index a34f8b6e0..922debeef 100644 --- a/Utilities/filters.csv +++ b/Utilities/filters.csv @@ -5,13 +5,12 @@ AccumulateImageFilter,True,False,Duplicate of Projection filters,False AcosImageFilter,True,True,,False AdaptiveHistogramEqualizationImageFilter,True,True,,True AddImageFilter,True,True,,False +AdditiveGaussianNoiseImageFilter,True,True,,False AndImageFilter,True,True,,False AnisotropicDiffusionImageFilter,True,False,base class,False AnisotropicFourthOrderLevelSetImageFilter,True,False,,True AntiAliasBinaryImageFilter,True,True,,True ApproximateSignedDistanceMapImageFilter,True,True,,False -AreaClosingImageFilter,True,False,,True -AreaOpeningImageFilter,True,False,,True AsinImageFilter,True,True,,False Atan2ImageFilter,True,True,,False AtanImageFilter,True,True,,False @@ -52,8 +51,8 @@ BlackTopHatImageFilter,True,True,,False BlockMatchingImageFilter,True,False,,False BoundedReciprocalImageFilter,True,True,,False BoxImageFilter,True,False,base class,False -BoxMeanImageFilter,True,True,,False -BoxSigmaImageFilter,True,True,,False +BoxMeanImageFilter,False,True,,False +BoxSigmaImageFilter,False,True,,False CannyEdgeDetectionImageFilter,True,True,,False CannySegmentationLevelSetImageFilter,True,False,This filter has a large number of parameters,True CastImageFilter,True,True,,False @@ -62,8 +61,9 @@ ChangeLabelImageFilter,True,True,,True CheckerBoardImageFilter,True,True,,False ClampImageFilter,True,True,,True ClosingByReconstructionImageFilter,True,True,,False -CollidingFrontsImageFilter,True,False,,True +CollidingFrontsImageFilter,True,True,,True ComparisonImageFilter,True,False,,False +ComplexToComplexFFTImageFilter,True,False,,False ComplexToImaginaryImageFilter,True,True,,False ComplexToModulusImageFilter,True,True,,False ComplexToPhaseImageFilter,True,True,,False @@ -76,7 +76,6 @@ ConstantPadImageFilter,True,True,,False ConstrainedValueAdditionImageFilter,True,False,,True ConstrainedValueDifferenceImageFilter,True,False,,True ContourDirectedMeanDistanceImageFilter,True,False,,True -ContourExtractor2DImageFilter,True,False,,True ContourMeanDistanceImageFilter,True,False,,True ConvolutionImageFilter,True,True,,False CosImageFilter,True,True,,False @@ -90,9 +89,8 @@ DenseFiniteDifferenceImageFilter,True,False,base class,False DerivativeImageFilter,True,True,,False DifferenceOfGaussiansGradientImageFilter,True,False,,True DilateObjectMorphologyImageFilter,True,True,,False -DirectFourierReconstructionImageToImageFilter,True,False,,True DirectedHausdorffDistanceImageFilter,True,False,,True -DiscreteGaussianDerivativeImageFilter,True,True,,True +DiscreteGaussianDerivativeImageFilter,False,True,,True DiscreteGaussianImageFilter,True,True,,False DivideFloorImageFilter,False,True,,False DivideImageFilter,True,True,,False @@ -106,15 +104,15 @@ ExpImageFilter,True,True,,False ExpNegativeImageFilter,True,True,,False ExpandImageFilter,True,True,,True ExtractImageFilter,True,True,,False -FFTComplexToComplexImageFilter,True,False,,True FFTConvolutionImageFilter,True,True,,False FFTNormalizedCorrelationImageFilter,False,True,,False FFTShiftImageFilter,True,True,,False -FastApproximateRankImageFilter,True,True,,True +FastApproximateRankImageFilter,False,True,,True FastChamferDistanceImageFilter,True,False,,True +FastMarchingBaseImageFilter,False,True,,False FastMarchingExtensionImageFilter,True,False,,True FastMarchingImageFilter,True,True,,False -FastMarchingUpwindGradientImageFilter,True,False,,True +FastMarchingUpwindGradientImageFilter,True,True,,True FiniteDifferenceImageFilter,True,False,base class,False FlipImageFilter,True,True,,False ForwardFFTImageFilter,True,True,,False @@ -144,7 +142,6 @@ GrayscaleMorphologicalClosingImageFilter,True,True,,False GrayscaleMorphologicalOpeningImageFilter,True,True,,False GreaterEqualImageFilter,False,True,,False GreaterImageFilter,False,True,,False -GridForwardWarpImageFilter,True,False,,True GridImageSource,True,False,,False HConcaveImageFilter,True,True,,False HConvexImageFilter,True,True,,False @@ -157,7 +154,6 @@ HashImageFilter,False,True,,False HausdorffDistanceImageFilter,True,True,,False Hessian3DToVesselnessMeasureImageFilter,True,False,,True HessianRecursiveGaussianImageFilter,True,False,,True -HessianToObjectnessMeasureImageFilter,True,False,,True HistogramMatchingImageFilter,True,True,,False HistogramThresholdImageFilter,True,False,base class,False HistogramToEntropyImageFilter,True,False,Requires ITK histogram,False @@ -174,7 +170,9 @@ IntensityWindowingImageFilter,True,True,,False IntermodesThresholdImageFilter,True,True,,False InterpolateImageFilter,True,False,,True InverseDeconvolutionImageFilter,True,True,,False +InverseDisplacementFieldImageFilter,False,True,,False InverseFFTImageFilter,True,True,,False +InvertDisplacementFieldImageFilter,False,True,,False InvertIntensityImageFilter,True,True,,False IsoContourDistanceImageFilter,True,True,,False IsoDataThresholdImageFilter,True,True,,False @@ -183,11 +181,9 @@ IsolatedWatershedImageFilter,True,True,,False IsotropicFourthOrderLevelSetImageFilter,True,False,,True IterativeDeconvolutionImageFilter,True,False,,False JoinSeriesImageFilter,True,True,,False -KappaSigmaThresholdImageFilter,True,False,,True KernelImageFilter,True,False,base class?,False KittlerIllingworthThresholdImageFilter,True,True,,False LabelContourImageFilter,True,True,,False -LabelGeometryImageFilter,True,False,Duplicate with LabelMaps?,False LabelMapContourOverlayImageFilter,True,True,,True LabelMapMaskImageFilter,True,True,,False LabelMapOverlayImageFilter,True,True,,False @@ -198,6 +194,7 @@ LabelOverlapMeasuresImageFilter,False,True,,False LabelOverlayImageFilter,True,True,,False LabelShapeKeepNObjectsImageFilter,True,False,,True LabelShapeOpeningImageFilter,True,False,,True +LabelShapeStatisticsImageFilter,False,True,,False LabelStatisticsImageFilter,True,True,,False LabelStatisticsKeepNObjectsImageFilter,True,False,,True LabelStatisticsOpeningImageFilter,True,False,,True @@ -217,7 +214,6 @@ MagnitudeAndPhaseToComplexImageFilter,True,True,,False MaskImageFilter,True,True,,False MaskNegatedImageFilter,True,True,,False MaskedFFTNormalizedCorrelationImageFilter,True,True,,False -MaskedRankImageFilter,True,False,,True MaximumEntropyThresholdImageFilter,True,True,,False MaximumImageFilter,True,True,,False MaximumProjectionImageFilter,True,True,,False @@ -233,10 +229,9 @@ MirrorPadImageFilter,True,True,,False ModulusImageFilter,True,True,,False MomentsThresholdImageFilter,True,True,,False MorphologicalGradientImageFilter,True,True,,False -MorphologicalWatershedFromMarkersImageFilter,True,True,,True -MorphologicalWatershedImageFilter,True,True,,True +MorphologicalWatershedFromMarkersImageFilter,False,True,,True +MorphologicalWatershedImageFilter,False,True,,True MultiResolutionPyramidImageFilter,True,False,How can the multiple output be delt with?,False -MultiScaleHessianBasedMeasureImageFilter,True,False,,False MultiplyImageFilter,True,True,,False N4BiasFieldCorrectionImageFilter,False,True,,False NarrowBandCurvesLevelSetImageFilter,True,False,,True @@ -245,6 +240,7 @@ NarrowBandThresholdSegmentationLevelSetImageFilter,True,False,,True NaryAddImageFilter,True,True,,True NaryMaximumImageFilter,True,True,,True NeighborhoodConnectedImageFilter,True,True,,False +NoiseBaseImageFilter,True,False,,False NoiseImageFilter,True,True,,False NormalizeImageFilter,True,True,,False NormalizeToConstantImageFilter,True,True,,False @@ -268,7 +264,7 @@ ProjectedLandweberDeconvolutionImageFilter,True,True,,False PyImageFilter,True,False,,False RGBToLuminanceImageFilter,True,False,,True RandomImageSource,True,False,in itk::Testing namespace,False -RankImageFilter,True,True,,True +RankImageFilter,False,True,,True RealAndImaginaryToComplexImageFilter,False,True,,False RealToHalfHermitianForwardFFTImageFilter,True,True,,True ReconstructionByDilationImageFilter,True,True,,True @@ -277,19 +273,18 @@ RecursiveGaussianImageFilter,True,True,,False RecursiveMultiResolutionPyramidImageFilter,True,False,How can the multiple output be delt with?,False RecursiveSeparableImageFilter,True,False,base class,False RegionOfInterestImageFilter,True,True,,False -RegionalMaximaImageFilter,True,True,,True -RegionalMinimaImageFilter,True,True,,True +RegionalMaximaImageFilter,False,True,,True +RegionalMinimaImageFilter,False,True,,True ReinitializeLevelSetImageFilter,True,False,,True RelabelComponentImageFilter,True,True,,False RenyiEntropyThresholdImageFilter,True,True,,False ResampleImageFilter,True,True,,False RescaleIntensityImageFilter,True,True,,False RichardsonLucyDeconvolutionImageFilter,True,True,,False -RobustAutomaticThresholdImageFilter,True,False,,True RoundImageFilter,True,False,,False STAPLEImageFilter,True,True,,True -ScalarChanAndVeseDenseLevelSetImageFilter,True,True,,True -ScalarChanAndVeseSparseLevelSetImageFilter,True,False,,True +SaltAndPepperNoiseImageFilter,True,True,,False +ScalarChanAndVeseDenseLevelSetImageFilter,False,True,,True ScalarConnectedComponentImageFilter,True,True,,False ScalarImageKmeansImageFilter,True,True,,False ScalarToRGBColormapImageFilter,True,True,,False @@ -299,6 +294,7 @@ ShapeDetectionLevelSetImageFilter,True,True,,False ShapePriorSegmentationLevelSetImageFilter,True,False,,True ShapeRelabelImageFilter,True,False,,True ShiftScaleImageFilter,True,True,,False +ShotNoiseImageFilter,True,True,,False ShrinkImageFilter,True,True,,False SigmoidImageFilter,True,True,,False SignedDanielssonDistanceMapImageFilter,True,True,,False @@ -313,13 +309,13 @@ SobelEdgeDetectionImageFilter,True,True,,False SparseFieldFourthOrderLevelSetImageFilter,True,False,,True SparseFieldLevelSetImageFilter,True,False,base class?,False SpatialObjectToImageFilter,True,False,A solution is needed for spacial object input,False +SpeckleNoiseImageFilter,True,True,,False SqrtImageFilter,True,True,,False SquareImageFilter,True,True,,False SquaredDifferenceImageFilter,True,True,,False StandardDeviationProjectionImageFilter,True,True,,False StatisticsImageFilter,True,True,,False StatisticsRelabelImageFilter,True,False,,True -StochasticFractalDimensionImageFilter,True,False,,True StreamingImageFilter,True,False,This is for pipelines,False SubtractImageFilter,True,True,,False SumProjectionImageFilter,True,True,,False @@ -337,8 +333,8 @@ TobogganImageFilter,True,False,,True TriangleThresholdImageFilter,True,True,,False UnaryMinusImageFilter,False,True,,False UnsharpMaskLevelSetImageFilter,True,False,,True -ValuedRegionalMaximaImageFilter,True,True,,True -ValuedRegionalMinimaImageFilter,True,True,,True +ValuedRegionalMaximaImageFilter,False,True,,True +ValuedRegionalMinimaImageFilter,False,True,,True VectorCastImageFilter,True,False,Already integrated into the Cast image filter,False VectorConfidenceConnectedImageFilter,True,True,,True VectorConnectedComponentImageFilter,True,True,,False @@ -351,6 +347,7 @@ VectorMagnitudeImageFilter,True,True,,False VectorResampleImageFilter,True,False,Same functionality exists in ResampleImageFilter,False VectorRescaleIntensityImageFilter,True,False,,True VectorThresholdSegmentationLevelSetImageFilter,True,False,,True +VnlComplexToComplexFFTImageFilter,True,False,,False VnlForwardFFTImageFilter,True,False,Internal FFT filter,False VnlHalfHermitianToRealInverseFFTImageFilter,True,False,Internal FFT filter,False VnlInverseFFTImageFilter,True,False,Internal FFT filter,False From 720d8ba02418decd0d21a9321eb4f92acbfa0f64 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Tue, 2 Jun 2015 14:14:22 -0400 Subject: [PATCH 014/412] Re-regenerated filters.csv The previously filters.csv was generated incorrectly. The version of ITK it was built against did not have the review module enabled. Change-Id: I1ee74306925daa513a94b0d77f4f984f54bbb491 --- Utilities/filters.csv | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/Utilities/filters.csv b/Utilities/filters.csv index 922debeef..1bbeb5c71 100644 --- a/Utilities/filters.csv +++ b/Utilities/filters.csv @@ -11,6 +11,8 @@ AnisotropicDiffusionImageFilter,True,False,base class,False AnisotropicFourthOrderLevelSetImageFilter,True,False,,True AntiAliasBinaryImageFilter,True,True,,True ApproximateSignedDistanceMapImageFilter,True,True,,False +AreaClosingImageFilter,True,False,,True +AreaOpeningImageFilter,True,False,,True AsinImageFilter,True,True,,False Atan2ImageFilter,True,True,,False AtanImageFilter,True,True,,False @@ -51,8 +53,8 @@ BlackTopHatImageFilter,True,True,,False BlockMatchingImageFilter,True,False,,False BoundedReciprocalImageFilter,True,True,,False BoxImageFilter,True,False,base class,False -BoxMeanImageFilter,False,True,,False -BoxSigmaImageFilter,False,True,,False +BoxMeanImageFilter,True,True,,False +BoxSigmaImageFilter,True,True,,False CannyEdgeDetectionImageFilter,True,True,,False CannySegmentationLevelSetImageFilter,True,False,This filter has a large number of parameters,True CastImageFilter,True,True,,False @@ -76,6 +78,7 @@ ConstantPadImageFilter,True,True,,False ConstrainedValueAdditionImageFilter,True,False,,True ConstrainedValueDifferenceImageFilter,True,False,,True ContourDirectedMeanDistanceImageFilter,True,False,,True +ContourExtractor2DImageFilter,True,False,,True ContourMeanDistanceImageFilter,True,False,,True ConvolutionImageFilter,True,True,,False CosImageFilter,True,True,,False @@ -89,8 +92,9 @@ DenseFiniteDifferenceImageFilter,True,False,base class,False DerivativeImageFilter,True,True,,False DifferenceOfGaussiansGradientImageFilter,True,False,,True DilateObjectMorphologyImageFilter,True,True,,False +DirectFourierReconstructionImageToImageFilter,True,False,,True DirectedHausdorffDistanceImageFilter,True,False,,True -DiscreteGaussianDerivativeImageFilter,False,True,,True +DiscreteGaussianDerivativeImageFilter,True,True,,True DiscreteGaussianImageFilter,True,True,,False DivideFloorImageFilter,False,True,,False DivideImageFilter,True,True,,False @@ -106,8 +110,9 @@ ExpandImageFilter,True,True,,True ExtractImageFilter,True,True,,False FFTConvolutionImageFilter,True,True,,False FFTNormalizedCorrelationImageFilter,False,True,,False +FFTPadImageFilter,True,False,,False FFTShiftImageFilter,True,True,,False -FastApproximateRankImageFilter,False,True,,True +FastApproximateRankImageFilter,True,True,,True FastChamferDistanceImageFilter,True,False,,True FastMarchingBaseImageFilter,False,True,,False FastMarchingExtensionImageFilter,True,False,,True @@ -142,6 +147,7 @@ GrayscaleMorphologicalClosingImageFilter,True,True,,False GrayscaleMorphologicalOpeningImageFilter,True,True,,False GreaterEqualImageFilter,False,True,,False GreaterImageFilter,False,True,,False +GridForwardWarpImageFilter,True,False,,True GridImageSource,True,False,,False HConcaveImageFilter,True,True,,False HConvexImageFilter,True,True,,False @@ -154,6 +160,7 @@ HashImageFilter,False,True,,False HausdorffDistanceImageFilter,True,True,,False Hessian3DToVesselnessMeasureImageFilter,True,False,,True HessianRecursiveGaussianImageFilter,True,False,,True +HessianToObjectnessMeasureImageFilter,True,False,,True HistogramMatchingImageFilter,True,True,,False HistogramThresholdImageFilter,True,False,base class,False HistogramToEntropyImageFilter,True,False,Requires ITK histogram,False @@ -181,9 +188,11 @@ IsolatedWatershedImageFilter,True,True,,False IsotropicFourthOrderLevelSetImageFilter,True,False,,True IterativeDeconvolutionImageFilter,True,False,,False JoinSeriesImageFilter,True,True,,False +KappaSigmaThresholdImageFilter,True,False,,True KernelImageFilter,True,False,base class?,False KittlerIllingworthThresholdImageFilter,True,True,,False LabelContourImageFilter,True,True,,False +LabelGeometryImageFilter,True,False,Duplicate with LabelMaps?,False LabelMapContourOverlayImageFilter,True,True,,True LabelMapMaskImageFilter,True,True,,False LabelMapOverlayImageFilter,True,True,,False @@ -214,6 +223,7 @@ MagnitudeAndPhaseToComplexImageFilter,True,True,,False MaskImageFilter,True,True,,False MaskNegatedImageFilter,True,True,,False MaskedFFTNormalizedCorrelationImageFilter,True,True,,False +MaskedRankImageFilter,True,False,,True MaximumEntropyThresholdImageFilter,True,True,,False MaximumImageFilter,True,True,,False MaximumProjectionImageFilter,True,True,,False @@ -229,9 +239,10 @@ MirrorPadImageFilter,True,True,,False ModulusImageFilter,True,True,,False MomentsThresholdImageFilter,True,True,,False MorphologicalGradientImageFilter,True,True,,False -MorphologicalWatershedFromMarkersImageFilter,False,True,,True -MorphologicalWatershedImageFilter,False,True,,True +MorphologicalWatershedFromMarkersImageFilter,True,True,,True +MorphologicalWatershedImageFilter,True,True,,True MultiResolutionPyramidImageFilter,True,False,How can the multiple output be delt with?,False +MultiScaleHessianBasedMeasureImageFilter,True,False,,False MultiplyImageFilter,True,True,,False N4BiasFieldCorrectionImageFilter,False,True,,False NarrowBandCurvesLevelSetImageFilter,True,False,,True @@ -264,7 +275,7 @@ ProjectedLandweberDeconvolutionImageFilter,True,True,,False PyImageFilter,True,False,,False RGBToLuminanceImageFilter,True,False,,True RandomImageSource,True,False,in itk::Testing namespace,False -RankImageFilter,False,True,,True +RankImageFilter,True,True,,True RealAndImaginaryToComplexImageFilter,False,True,,False RealToHalfHermitianForwardFFTImageFilter,True,True,,True ReconstructionByDilationImageFilter,True,True,,True @@ -273,18 +284,20 @@ RecursiveGaussianImageFilter,True,True,,False RecursiveMultiResolutionPyramidImageFilter,True,False,How can the multiple output be delt with?,False RecursiveSeparableImageFilter,True,False,base class,False RegionOfInterestImageFilter,True,True,,False -RegionalMaximaImageFilter,False,True,,True -RegionalMinimaImageFilter,False,True,,True +RegionalMaximaImageFilter,True,True,,True +RegionalMinimaImageFilter,True,True,,True ReinitializeLevelSetImageFilter,True,False,,True RelabelComponentImageFilter,True,True,,False RenyiEntropyThresholdImageFilter,True,True,,False ResampleImageFilter,True,True,,False RescaleIntensityImageFilter,True,True,,False RichardsonLucyDeconvolutionImageFilter,True,True,,False +RobustAutomaticThresholdImageFilter,True,False,,True RoundImageFilter,True,False,,False STAPLEImageFilter,True,True,,True SaltAndPepperNoiseImageFilter,True,True,,False -ScalarChanAndVeseDenseLevelSetImageFilter,False,True,,True +ScalarChanAndVeseDenseLevelSetImageFilter,True,True,,True +ScalarChanAndVeseSparseLevelSetImageFilter,True,False,,True ScalarConnectedComponentImageFilter,True,True,,False ScalarImageKmeansImageFilter,True,True,,False ScalarToRGBColormapImageFilter,True,True,,False @@ -316,6 +329,7 @@ SquaredDifferenceImageFilter,True,True,,False StandardDeviationProjectionImageFilter,True,True,,False StatisticsImageFilter,True,True,,False StatisticsRelabelImageFilter,True,False,,True +StochasticFractalDimensionImageFilter,True,False,,True StreamingImageFilter,True,False,This is for pipelines,False SubtractImageFilter,True,True,,False SumProjectionImageFilter,True,True,,False @@ -333,8 +347,8 @@ TobogganImageFilter,True,False,,True TriangleThresholdImageFilter,True,True,,False UnaryMinusImageFilter,False,True,,False UnsharpMaskLevelSetImageFilter,True,False,,True -ValuedRegionalMaximaImageFilter,False,True,,True -ValuedRegionalMinimaImageFilter,False,True,,True +ValuedRegionalMaximaImageFilter,True,True,,True +ValuedRegionalMinimaImageFilter,True,True,,True VectorCastImageFilter,True,False,Already integrated into the Cast image filter,False VectorConfidenceConnectedImageFilter,True,True,,True VectorConnectedComponentImageFilter,True,True,,False From 84c212ff0c4082b13614c04fbd8874497071aedb Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 3 Jun 2015 10:53:29 -0400 Subject: [PATCH 015/412] Adding forbid download CMake option Change-Id: I69db8e96c184bb3f712b83b736abfe093b846e1b --- CMakeLists.txt | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2c22637e0..283d5f023 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -120,6 +120,20 @@ option( SITK_4D_IMAGES "Add Image and I/O support for four spatial dimensions." mark_as_advanced( SITK_4D_IMAGES ) +#----------------------------------------------------------------------------- +# Forbid downloading resources from the network during a build. This helps +# when building on systems without network connectivity to determine which +# resources much be obtained manually and made available to the build. +option(SITK_FORBID_DOWNLOADS "Do not download source code or data from the network" OFF) +mark_as_advanced(SITK_FORBID_DOWNLOADS) +macro(sitk_enforce_forbid_downloads _name) + if(SITK_FORBID_DOWNLOADS) + message(SEND_ERROR "Attempted to download ${_name} when SITK_FORBID_DOWNLOADS is ON") + endif() +endmacro() + + + # Setup build locations. if(NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin) From d53dc4b6fdc4d5d375a613d063a0bebdad9c69d7 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 3 Jun 2015 10:53:50 -0400 Subject: [PATCH 016/412] Forbid downloading data with option Change-Id: Id8bf72b51f9505540cd77815beb238d8f87d6e90 --- CMake/sitkExternalData.cmake | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/CMake/sitkExternalData.cmake b/CMake/sitkExternalData.cmake index 6ee692dfb..b50d89fad 100644 --- a/CMake/sitkExternalData.cmake +++ b/CMake/sitkExternalData.cmake @@ -33,15 +33,16 @@ set(ExternalData_URL_TEMPLATES "" CACHE STRING "Additional URL templates for the ExternalData CMake script to look for testing data. E.g. file:///var/bigharddrive/%(algo)/%(hash)") mark_as_advanced(ExternalData_URL_TEMPLATES) -list(APPEND ExternalData_URL_TEMPLATES - # Data published by MIDAS - "http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=%(hash)&algorithm=%(algo)" - "https://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=%(hash)&algorithm=%(algo)" - - # Data published by developers using git-gerrit-push. - "http://www.itk.org/files/ExternalData/%(algo)/%(hash)" - ) - +if(NOT SITK_FORBID_DOWNLOADS) + list(APPEND ExternalData_URL_TEMPLATES + # Data published by MIDAS + "http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=%(hash)&algorithm=%(algo)" + "https://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=%(hash)&algorithm=%(algo)" + + # Data published by developers using git-gerrit-push. + "http://www.itk.org/files/ExternalData/%(algo)/%(hash)" + ) +endif() # Tell ExternalData commands not to transform raw files to content links. #set(ExternalData_LINK_CONTENT MD5) From 4d0f97872133af1a8122b80959c60caeed937de0 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 3 Jun 2015 13:53:55 -0400 Subject: [PATCH 017/412] ADD SITK_PYTHON_USE_VIRTUAL_ENV option Make using python virtual environment optional, by adding support for using the system python for testing. The PATHONPATH is automatically added for testing. Using the virtual env requires that SITK_FORBID_DOWNLOADS is not enables as downloads may be required for installing required packages, as a result the "dist.Python" target used for packaging wheels and eggs is not created when forbid downloads is enabled. Change-Id: Iaf3a1aef1ad77b04be34e0b06cb3928632e1459d --- CMake/sitkAddTest.cmake | 8 +- Testing/Unit/SimpleITKTestHarnessPaths.h.in | 4 +- .../Unit/sitkImageFilterTestTemplate.cxx.in | 7 ++ Wrapping/CMakeLists.txt | 81 +++++++++++-------- Wrapping/dist/CMakeLists.txt | 20 +++-- 5 files changed, 75 insertions(+), 45 deletions(-) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index 727aef7f1..b83ab9f93 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -49,7 +49,7 @@ function(sitk_add_python_test name) return() endif() - set(command "${VIRTUAL_PYTHON_EXECUTABLE}") + set(command "${TEST_PYTHON_EXECUTABLE}") # add extra command which may be needed on some systems if(CMAKE_OSX_ARCHITECTURES) @@ -63,6 +63,12 @@ function(sitk_add_python_test name) ${command} ${ARGN} ) + if (NOT SITK_PYTHON_USE_VIRTUALENV) + set_property(TEST Python.${name} + PROPERTY ENVIRONMENT PYTHONPATH=${SimpleITK_BINARY_DIR}/Wrapping + ) + endif() + endfunction() diff --git a/Testing/Unit/SimpleITKTestHarnessPaths.h.in b/Testing/Unit/SimpleITKTestHarnessPaths.h.in index 9ff4a226d..196cb3ecc 100644 --- a/Testing/Unit/SimpleITKTestHarnessPaths.h.in +++ b/Testing/Unit/SimpleITKTestHarnessPaths.h.in @@ -31,7 +31,7 @@ #define SIMPLEITK_BINARY_DIR "@SimpleITK_BINARY_DIR@" #define TEST_HARNESS_TEMP_DIRECTORY "@TEST_HARNESS_TEMP_DIRECTORY@" #define TEST_HARNESS_DATA_DIRECTORY "@TEST_HARNESS_DATA_DIRECTORY@" -#define PYTHON_EXECUTABLE_PATH "@VIRTUAL_PYTHON_EXECUTABLE@" +#define PYTHON_EXECUTABLE_PATH "@TEST_PYTHON_EXECUTABLE@" #define RSCRIPT_EXECUTABLE_PATH "@RSCRIPT_EXECUTABLE@" #define R_EXECUTABLE_PATH "@R_COMMAND@" #define JAVA_EXECUTABLE_PATH "@Java_JAVA_EXECUTABLE@" @@ -43,6 +43,8 @@ #define OSX_ARCHITECTURES "@CMAKE_OSX_ARCHITECTURES@" +#cmakedefine SITK_PYTHON_USE_VIRTUALENV + #cmakedefine WRAP_LUA #cmakedefine WRAP_PYTHON #cmakedefine WRAP_JAVA diff --git a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in index 662314e10..01546651c 100644 --- a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in +++ b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in @@ -402,6 +402,13 @@ TEST_F(Python,${name}) { ]] end) + #ifndef SITK_PYTHON_USE_VIRTUALENV + // Set-up the R enviroment to include the SimpleITK R library in the + // build directory. + SetEnvironment ( "PYTHONPATH", dataFinder.GetBuildDirectory()+"/Wrapping" ); + #endif + + std::string Script = dataFinder.GetBuildDirectory() + "/Testing/Unit/PythonTests/${name}Test.py"; $(foreach tests { diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index a27cd9dcc..986679c24 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -163,46 +163,57 @@ if ( WRAP_PYTHON ) "${CMAKE_CURRENT_BINARY_DIR}/__init__.py" COPYONLY ) + option(SITK_PYTHON_USE_VIRTUALENV "Create a Python Virtual Environment for testing." ON) + mark_as_advanced(SITK_PYTHON_USE_VIRTUALENV) + + if (SITK_PYTHON_USE_VIRTUALENV) + sitk_enforce_forbid_downloads( SITK_PYTHON_USE_VIRTUALENV ) + # + # Setup Python Virtual Enviroment for testing and packaging + # + set( PythonVirtualenvHome "${SimpleITK_BINARY_DIR}/Testing/Installation/PythonVirtualenv" ) + + # virtualenv places the python executable in different + # locations. Also note than on windows installations where python is + # installed only for a single user the may be a missing dll issue. + if( WIN32 ) + set( VIRTUAL_PYTHON_EXECUTABLE + "${PythonVirtualenvHome}/Scripts/python") + else( ) + set( VIRTUAL_PYTHON_EXECUTABLE "${PythonVirtualenvHome}/bin/python" ) + endif() + set(TEST_PYTHON_EXECUTABLE "${VIRTUAL_PYTHON_EXECUTABLE}" + CACHE INTERNAL "Python executable for testing." FORCE ) - # - # Setup Python Virtual Enviroment for testing and packaging - # - set( PythonVirtualenvHome "${SimpleITK_BINARY_DIR}/Testing/Installation/PythonVirtualenv" ) - - # virtualenv places the python executable in different - # locations. Also note than on windows installations where python is - # installed only for a single user the may be a missing dll issue. - if( WIN32 ) - set( VIRTUAL_PYTHON_EXECUTABLE "${PythonVirtualenvHome}/Scripts/python" CACHE INTERNAL "Python executable in virtual enviroment" FORCE ) - else( ) - set( VIRTUAL_PYTHON_EXECUTABLE "${PythonVirtualenvHome}/bin/python" CACHE INTERNAL "Python executable in virtual enviroment" FORCE ) - endif() + # configure a scripts which creates the virtualenv and installs numpy + configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/PythonVirtualEnvInstall.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/PythonVirtualEnvInstall.cmake" + @ONLY ) - # configure a scripts which creates the virtualenv and installs numpy - configure_file( - "${CMAKE_CURRENT_SOURCE_DIR}/PythonVirtualEnvInstall.cmake.in" - "${CMAKE_CURRENT_BINARY_DIR}/PythonVirtualEnvInstall.cmake" - @ONLY ) + set( PythonVirtualEnv_ALL "" ) + if ( BUILD_TESTING ) + set( PythonVirtualEnv_ALL "ALL" ) + endif() - set( PythonVirtualEnv_ALL "" ) - if ( BUILD_TESTING ) - set( PythonVirtualEnv_ALL "ALL" ) + add_custom_target( PythonVirtualEnv ${PythonVirtualEnv_ALL} + DEPENDS "${VIRTUAL_PYTHON_EXECUTABLE}" + SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/PythonVirtualEnvInstall.cmake.in ) + + add_custom_command( OUTPUT "${VIRTUAL_PYTHON_EXECUTABLE}" + COMMAND ${CMAKE_COMMAND} -P "${CMAKE_CURRENT_BINARY_DIR}/PythonVirtualEnvInstall.cmake" + DEPENDS + "${SWIG_MODULE_SimpleITKPython_TARGET_NAME}" + "${CMAKE_CURRENT_BINARY_DIR}/PythonVirtualEnvInstall.cmake" + ConfigureFileBuildtime + "${CMAKE_CURRENT_BINARY_DIR}/PythonPackage/ez_setup.py" + COMMENT "Creating python virtual enviroment..." + ) + else() + set(TEST_PYTHON_EXECUTABLE "${PYTHON_EXECUTABLE}" + CACHE INTERNAL "Python executable for testing." FORCE ) endif() - add_custom_target( PythonVirtualEnv ${PythonVirtualEnv_ALL} - DEPENDS "${VIRTUAL_PYTHON_EXECUTABLE}" - SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/PythonVirtualEnvInstall.cmake.in ) - - add_custom_command( OUTPUT "${VIRTUAL_PYTHON_EXECUTABLE}" - COMMAND ${CMAKE_COMMAND} -P "${CMAKE_CURRENT_BINARY_DIR}/PythonVirtualEnvInstall.cmake" - DEPENDS - "${SWIG_MODULE_SimpleITKPython_TARGET_NAME}" - "${CMAKE_CURRENT_BINARY_DIR}/PythonVirtualEnvInstall.cmake" - ConfigureFileBuildtime - "${CMAKE_CURRENT_BINARY_DIR}/PythonPackage/ez_setup.py" - COMMENT "Creating python virtual enviroment..." - ) - endif() # diff --git a/Wrapping/dist/CMakeLists.txt b/Wrapping/dist/CMakeLists.txt index 6a6095e4b..e2c44e252 100644 --- a/Wrapping/dist/CMakeLists.txt +++ b/Wrapping/dist/CMakeLists.txt @@ -13,14 +13,18 @@ if( WRAP_PYTHON ) set(bdist_commands ${bdist_commands} bdist_wheel) endif() - add_custom_target( dist.Python - ${VIRTUAL_PYTHON_EXECUTABLE} ${SimpleITK_BINARY_DIR}/Wrapping/PythonPackage/setupegg.py ${bdist_commands} - WORKING_DIRECTORY ${SimpleITK_BINARY_DIR}/Wrapping - DEPENDS ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} - COMMENT "Creating Python binary distribution" ) - - add_dependencies( dist.Python PythonVirtualEnv) - add_dependencies( dist dist.Python ) + if(SITK_PYTHON_USE_VIRTUALENV) + add_custom_target( dist.Python + ${VIRTUAL_PYTHON_EXECUTABLE} ${SimpleITK_BINARY_DIR}/Wrapping/PythonPackage/setupegg.py ${bdist_commands} + WORKING_DIRECTORY ${SimpleITK_BINARY_DIR}/Wrapping + DEPENDS ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} + COMMENT "Creating Python binary distribution" ) + + add_dependencies( dist.Python PythonVirtualEnv) + add_dependencies( dist dist.Python ) + elseif() + message( STATUS "Not creating dist.Python target since SITK_FORBID_DOWNLOADS is enabled" ) + endif() endif() From 078ec23eb7a16aba0f2c5c10f5c987fed90f99b9 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 4 Jun 2015 15:12:09 -0400 Subject: [PATCH 018/412] Create separate source and data tar-balls for distribution. This follows suit from ITK and VTK with work done by: Matt McCormick Brad King The source and data tarballs are split, and the data can be extracted in the source tree. BUILD_TESTING is OFF by default in the source tarball when the testing data is not present. Change-Id: I45c64b6b00b398a9140e53b8f8910b768693592c --- .ExternalData/README.rst | 6 +++ CMakeLists.txt | 10 +++++ Utilities/Maintenance/SourceTarball.bash | 48 +++++++++++++++++------- 3 files changed, 50 insertions(+), 14 deletions(-) create mode 100644 .ExternalData/README.rst diff --git a/.ExternalData/README.rst b/.ExternalData/README.rst new file mode 100644 index 000000000..b3b0f593d --- /dev/null +++ b/.ExternalData/README.rst @@ -0,0 +1,6 @@ +.ExternalData +============= + +The ITK ``.ExternalData`` directory is an object store for the +CMake ExternalData module that ITK uses to manage test input +and baseline data. diff --git a/CMakeLists.txt b/CMakeLists.txt index 2c22637e0..b5d4cc631 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -381,6 +381,16 @@ include(sitkLanguageOptions) # Ensure that development strips have been setup include(sitkCheckSourceTree) +#----------------------------------------------------------------------------- +if(NOT EXISTS "${ITK_SOURCE_DIR}/.ExternalData/README.rst") + # This file is always present in version-controlled source trees + # so we must have been extracted from a source tarball with no + # data objects needed for testing. Turn off tests by default + # since enabling them requires network access or manual data + # store configuration. + option(BUILD_TESTING "Build the testing tree." OFF) +endif() + #------------------------------------------------------------------------------ # set things up for testing, this configuration needs to occour before # we enter the sub-directories diff --git a/Utilities/Maintenance/SourceTarball.bash b/Utilities/Maintenance/SourceTarball.bash index 7975afb27..4ba97ab57 100755 --- a/Utilities/Maintenance/SourceTarball.bash +++ b/Utilities/Maintenance/SourceTarball.bash @@ -120,14 +120,21 @@ index_submodule_objects() { } load_data_objects() { - find_data_objects "$1" | + find_data_objects "$@" | index_data_objects return_pipe_status } +load_data_files() { + git ls-tree -r "$1" -- '.ExternalData' | + git update-index --index-info + return_pipe_status +} + git_archive_tgz() { out="$2.tar.gz" && tmp="$out.tmp$$" && - git -c core.autocrlf=false archive $verbose --format=tar --prefix=$2/ $1 | + if test -n "$3"; then prefix="$3"; else prefix="$2"; fi && + git -c core.autocrlf=false archive $verbose --format=tar --prefix=$prefix/ $1 | gzip -9 > "$tmp" && mv "$tmp" "$out" && info "Wrote $out" @@ -135,7 +142,8 @@ git_archive_tgz() { git_archive_txz() { out="$2.tar.xz" && tmp="$out.tmp$$" && - git -c core.autocrlf=false archive $verbose --format=tar --prefix=$2/ $1 | + if test -n "$3"; then prefix="$3"; else prefix="$2"; fi && + git -c core.autocrlf=false archive $verbose --format=tar --prefix=$prefix/ $1 | xz -9 > "$tmp" && mv "$tmp" "$out" && info "Wrote $out" @@ -143,7 +151,8 @@ git_archive_txz() { git_archive_zip() { out="$2.zip" && tmp="$out.tmp$$" && - git -c core.autocrlf=true archive $verbose --format=zip --prefix=$2/ $1 > "$tmp" && + if test -n "$3"; then prefix="$3"; else prefix="$2"; fi && + git -c core.autocrlf=true archive $verbose --format=zip --prefix=$prefix/ $1 > "$tmp" && mv "$tmp" "$out" && info "Wrote $out" } @@ -197,24 +206,35 @@ fi # Create temporary git index to construct source tree export GIT_INDEX_FILE="$(pwd)/tmp-$$-index" && -trap "rm -rf '$GIT_INDEX_FILE'" EXIT && +trap "rm -f '$GIT_INDEX_FILE'" EXIT && + -info "Loading tree from $commit..." && +result=0 && + + +info "Loading source tree from $commit..." && +rm -f "$GIT_INDEX_FILE" && git read-tree -m -i $commit && +git rm -rf -q --cached '.ExternalData' && +tree=$(git write-tree) && -info "Loading data for $commit..." && -load_data_objects $commit && index_additional_object "${build_dir}/sitkSourceVersionVars.cmake" "CMake" && -info "Loading data submodule" && -index_submodule_objects && - +info "Generating source archive(s)..." && +for fmt in $formats; do + git_archive_$fmt $tree "SimpleITK-$version" || result=1 +done && -info "Generating source archive..." && +info "Loading data for $commit..." && +rm -f "$GIT_INDEX_FILE" && +load_data_objects $commit && +load_data_files $commit && tree=$(git write-tree) && -result=0 && + + +info "Generating data archive(s)..." && for fmt in $formats; do - git_archive_$fmt $tree "SimpleITK-$version" || result=1 + git_archive_$fmt $tree "SimpleITKData-$version" "SimpleITK-$version" || result=1 done && exit $result From afd69651cd6878b5c10a4b37aaa1c049f01ed12d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 11 Jun 2015 09:12:59 -0400 Subject: [PATCH 019/412] Fix checking SimpleITK source directory for External data file Change-Id: If42728b11187fe4437395cc5e9906108b722a69e --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b5d4cc631..1d0605dc4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -382,7 +382,7 @@ include(sitkLanguageOptions) include(sitkCheckSourceTree) #----------------------------------------------------------------------------- -if(NOT EXISTS "${ITK_SOURCE_DIR}/.ExternalData/README.rst") +if(NOT EXISTS "${SimpleITK_SOURCE_DIR}/.ExternalData/README.rst") # This file is always present in version-controlled source trees # so we must have been extracted from a source tarball with no # data objects needed for testing. Turn off tests by default From ba5ff12318f4ee003d4c2dad417b99559d4b8abe Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 10 Jun 2015 15:28:16 -0400 Subject: [PATCH 020/412] Add CMake find package module for the Lua interpreter. Change-Id: I4019b94381fa2d4098ed5be52778237da567b7ca --- CMake/FindLuaInterp.cmake | 45 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 CMake/FindLuaInterp.cmake diff --git a/CMake/FindLuaInterp.cmake b/CMake/FindLuaInterp.cmake new file mode 100644 index 000000000..ddb610db7 --- /dev/null +++ b/CMake/FindLuaInterp.cmake @@ -0,0 +1,45 @@ +#.rst: +# FindLuaInterp +# -------- +# +# Find Lua Interpreter +# +# :: +# +# LUA_EXECUTABLE - the full path to lua +# LUA_EXECUTABLE_FOUND - If false, don't attempt to use lua +# LUA_EXECUTABLE_VERSION_STRING - version of lua found + +find_program(LUA_EXECUTABLE + NAMES lua + ) + +if(LUA_EXECUTABLE) + ### LUA_VERSION + execute_process( + COMMAND ${LUA_EXECUTABLE} -v + OUTPUT_VARIABLE + LUA_EXECUTABLE_VERSION_STRING + ERROR_VARIABLE + LUA_EXECUTABLE_VERSION_STRING + RESULT_VARIABLE + LUA_VERSION_RESULT_VARIABLE + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_STRIP_TRAILING_WHITESPACE + ) + if (NOT LUA_VERSION_RESULT_VARIABLE) + string( REGEX MATCH "([0-9]*)([.])([0-9]*)([.]*)([0-9]*)" + LUA_EXECUTABLE_VERSION + ${LUA_EXECUTABLE_VERSION_STRING} ) + endif() +endif() + + +# handle the QUIETLY and REQUIRED arguments and set LUA_FOUND to TRUE if +# all listed variables are TRUE +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(Lua + REQUIRED_VARS LUA_EXECUTABLE + VERSION_VAR LUA_VERSION_STRING) + +mark_as_advanced(LUA_EXECUTABLE) From 7815975d026e5a6c452cc04618234982629ded92 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 10 Jun 2015 15:29:27 -0400 Subject: [PATCH 021/412] Use SITK_LUA_EXECUTABLE for code generation This variable replaces the "lua" CMake target name that was used previously. Change-Id: I53adf96677d52e7945486fabbdb938edbc93a9f4 --- CMake/generate_filter_source.cmake | 40 ++++++++++++++++++++++++++++-- Testing/Unit/CMakeLists.txt | 16 ++++++------ 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/CMake/generate_filter_source.cmake b/CMake/generate_filter_source.cmake index 8cac3d73e..54f76c3e6 100644 --- a/CMake/generate_filter_source.cmake +++ b/CMake/generate_filter_source.cmake @@ -1,3 +1,39 @@ + +find_package( LuaInterp REQUIRED 5.1 ) + +if ( NOT ${SITK_LUA_EXECUTABLE} ) + find_package( LuaInterp REQUIRED 5.1 ) + set( SITK_LUA_EXECUTABLE ${LUA_EXECUTABLE} CACHE PATH "Lua executable used for code generation." ) + unset( LUA_EXECUTABLE CACHE ) +endif() + +execute_process( + COMMAND ${SITK_LUA_EXECUTABLE} -v + OUTPUT_VARIABLE + SITK_LUA_EXECUTABLE_VERSION_STRING + ERROR_VARIABLE + SITK_LUA_EXECUTABLE_VERSION_STRING + RESULT_VARIABLE + SITK_LUA_VERSION_RESULT_VARIABLE + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_STRIP_TRAILING_WHITESPACE + ) + +if( NOT SITK_LUA_VERSION_RESULT_VARIABLE ) + string( REGEX MATCH "([0-9]*)([.])([0-9]*)([.]*)([0-9]*)" + SITK_LUA_EXECUTABLE_VERSION + ${SITK_LUA_EXECUTABLE_VERSION_STRING} ) +endif() + +if( SITK_LUA_VERSION_RESULT_VARIABLE + OR + NOT ${SITK_LUA_EXECUTABLE_VERSION} VERSION_GREATER "5.1" + OR + NOT ${SITK_LUA_EXECUTABLE_VERSION} VERSION_LESS "5.2" ) + message(SEND_ERROR "Lua version 5.1 is required for SITK_LUA_EXECUTABLE_VERSION.") +endif() + + ############################################################################### # This macro returns the list of template components used by a specific # template file @@ -81,14 +117,14 @@ macro( expand_template FILENAME input_dir output_dir library_name ) add_custom_command ( OUTPUT "${output_h}" COMMAND ${CMAKE_COMMAND} -E remove -f ${output_h} - COMMAND lua ${expand_template_script} code ${input_json_file} ${input_dir}/templates/sitk ${template_include_dir} Template.h.in ${output_h} + COMMAND ${SITK_LUA_EXECUTABLE} ${expand_template_script} code ${input_json_file} ${input_dir}/templates/sitk ${template_include_dir} Template.h.in ${output_h} DEPENDS ${input_json_file} ${template_deps} ${template_file_h} ) # impl add_custom_command ( OUTPUT "${output_cxx}" COMMAND ${CMAKE_COMMAND} -E remove -f ${output_cxx} - COMMAND lua ${expand_template_script} code ${input_json_file} ${input_dir}/templates/sitk ${template_include_dir} Template.cxx.in ${output_cxx} + COMMAND ${SITK_LUA_EXECUTABLE} ${expand_template_script} code ${input_json_file} ${input_dir}/templates/sitk ${template_include_dir} Template.cxx.in ${output_cxx} DEPENDS ${input_json_file} ${template_deps} ${template_file_cxx} ) diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index 8975f818b..d73348b77 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -107,7 +107,7 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) add_custom_command ( OUTPUT ${OUTPUT_TEST_FILENAME} COMMAND ${CMAKE_COMMAND} -E remove -f "${OUTPUT_TEST_FILENAME}" - COMMAND lua ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/sitk ${template_include_dir} TestTemplate.cxx.in "${OUTPUT_TEST_FILENAME}" + COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/sitk ${template_include_dir} TestTemplate.cxx.in "${OUTPUT_TEST_FILENAME}" DEPENDS ${filter_json_file} ${CXX_TEMPLATE_FILES} ) add_test( NAME BasicFilters.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=BasicFilters.${FILTERNAME}:BasicFilters.${FILTERNAME}_* ) @@ -118,7 +118,7 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) add_custom_command ( OUTPUT "${OUTPUT_TEST_FILENAME}" COMMAND ${CMAKE_COMMAND} -E remove -f "${OUTPUT_TEST_FILENAME}" - COMMAND lua ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Lua ${template_include_dir} TestTemplate.lua.in "${OUTPUT_TEST_FILENAME}" + COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Lua ${template_include_dir} TestTemplate.lua.in "${OUTPUT_TEST_FILENAME}" DEPENDS ${filter_json_file} ${LUA_TEMPLATE_FILES} ) add_test( NAME Lua.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=Lua.${FILTERNAME} ) @@ -130,7 +130,7 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) add_custom_command ( OUTPUT "${OUTPUT_TEST_FILENAME}" COMMAND ${CMAKE_COMMAND} -E remove -f "${OUTPUT_TEST_FILENAME}" - COMMAND lua ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Python ${template_include_dir} TestTemplate.py.in "${OUTPUT_TEST_FILENAME}" + COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Python ${template_include_dir} TestTemplate.py.in "${OUTPUT_TEST_FILENAME}" DEPENDS ${filter_json_file} ${PYTHON_TEMPLATE_FILES} ) add_test( NAME Python.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=Python.${FILTERNAME} ) @@ -142,7 +142,7 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) add_custom_command ( OUTPUT "${OUTPUT_TEST_FILENAME}" COMMAND ${CMAKE_COMMAND} -E remove -f "${OUTPUT_TEST_FILENAME}" - COMMAND lua ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Tcl ${template_include_dir} TestTemplate.tcl.in "${OUTPUT_TEST_FILENAME}" + COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Tcl ${template_include_dir} TestTemplate.tcl.in "${OUTPUT_TEST_FILENAME}" DEPENDS ${filter_json_file} ${TCL_TEMPLATE_FILES} ) add_test( NAME Tcl.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=Tcl.${FILTERNAME} ) @@ -154,7 +154,7 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) add_custom_command ( OUTPUT "${OUTPUT_TEST_FILENAME}" COMMAND ${CMAKE_COMMAND} -E remove -f "${OUTPUT_TEST_FILENAME}" - COMMAND lua ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/R ${template_include_dir} TestTemplate.R.in "${OUTPUT_TEST_FILENAME}" + COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/R ${template_include_dir} TestTemplate.R.in "${OUTPUT_TEST_FILENAME}" DEPENDS ${filter_json_file} ${R_TEMPLATE_FILES} ) add_test( NAME R.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=R.${FILTERNAME} ) @@ -166,7 +166,7 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) add_custom_command ( OUTPUT "${OUTPUT_TEST_FILENAME}" COMMAND ${CMAKE_COMMAND} -E remove -f "${OUTPUT_TEST_FILENAME}" - COMMAND lua ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Ruby ${template_include_dir} TestTemplate.rb.in "${OUTPUT_TEST_FILENAME}" + COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Ruby ${template_include_dir} TestTemplate.rb.in "${OUTPUT_TEST_FILENAME}" DEPENDS ${filter_json_file} ${RUBY_TEMPLATE_FILES} ) add_test( NAME Ruby.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=Ruby.${FILTERNAME} ) @@ -179,7 +179,7 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) add_custom_command ( OUTPUT "${OUTPUT_TEST_FILENAME}" COMMAND ${CMAKE_COMMAND} -E remove -f "${OUTPUT_TEST_FILENAME}" - COMMAND lua ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Java ${template_include_dir} TestTemplate.java.in "${OUTPUT_TEST_FILENAME}" + COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Java ${template_include_dir} TestTemplate.java.in "${OUTPUT_TEST_FILENAME}" COMMAND ${Java_JAVAC_EXECUTABLE} -classpath ${SimpleITK_BINARY_DIR}/Wrapping/${JAR_FILE} ${SimpleITK_BINARY_DIR}/Testing/Unit/JavaTests/org/itk/simple/testing/${FILTERNAME}Test.java DEPENDS ${filter_json_file} ${JAVA_TEMPLATE_FILES} ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} ) @@ -198,7 +198,7 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) add_custom_command ( OUTPUT "${OUTPUT_TEST_FILENAME}" COMMAND ${CMAKE_COMMAND} -E remove -f "${OUTPUT_TEST_FILENAME}" - COMMAND lua ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/CSharp ${template_include_dir} TestTemplate.cs.in "${OUTPUT_TEST_FILENAME}" + COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/CSharp ${template_include_dir} TestTemplate.cs.in "${OUTPUT_TEST_FILENAME}" COMMAND ${CSHARP_COMPILER} /t:exe /platform:${CSHARP_PLATFORM} /lib:${CSHARP_BINARY_DIRECTORY} /reference:System.dll /reference:SimpleITKCSharpManaged.dll From be668be4ae2c88bd523ea4a058e51679042e58bf Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 10 Jun 2015 15:30:27 -0400 Subject: [PATCH 022/412] Use CMake find_package for finding Lua libraries and include Change-Id: I75591f193c2b4c3ecbde8751879e49f9120d63c6 --- CMake/sitkLanguageOptions.cmake | 26 +++++++++++++++++++++++++- Wrapping/CMakeLists.txt | 11 ++++------- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/CMake/sitkLanguageOptions.cmake b/CMake/sitkLanguageOptions.cmake index d3348f5d3..2d4defa61 100644 --- a/CMake/sitkLanguageOptions.cmake +++ b/CMake/sitkLanguageOptions.cmake @@ -23,7 +23,31 @@ endmacro() # # Setup the option for each language # -option ( WRAP_LUA "Wrap Lua" ON ) +if (NOT WRAP_LUA) + set(_QUIET "QUIET") +endif() +if (CMAKE_VERSION VERSION_LESS "3") + find_package ( Lua51 ${_QUIET} ) + if ( NOT LUA_FOUND ) + find_package ( Lua50 ${_QUIET} ) + endif() +else() + find_package ( Lua ${_QUIET} ) +endif() +if ( LUA_FOUND ) + set( WRAP_LUA_DEFAULT ON ) +else() + set( WRAP_LUA_DEFAULT OFF ) +endif() + +option ( WRAP_LUA "Wrap Lua" ${WRAP_LUA_DEFAULT} ) + +list( APPEND SITK_LANGUAGES_VARS + LUA_LIBRARIES + LUA_INCLUDE_DIR + LUA_VERSION_STRING + ) + find_package ( PythonInterp QUIET) diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index 986679c24..c8cc19069 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -44,16 +44,13 @@ endif() # lua SWIG configuration # if ( WRAP_LUA ) - option ( USE_SYSTEM_LUA "Use a system provided lua" OFF ) - if ( USE_SYSTEM_LUA ) + if (CMAKE_VERSION VERSION_LESS "3") find_package ( Lua51 REQUIRED ) - include_directories ( ${LUA_INCLUDE_DIR} ) - set ( LUA_LIB ${LUA_LIBRARIES} ) else() - set ( LUA_LIB lua5 ) - include_directories ( ${SimpleITK_SOURCE_DIR}/Utilities/lua-5.1.5/src ) + find_package ( Lua REQUIRED ) endif() + include_directories ( ${LUA_INCLUDE_DIR} ) # Run swig set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_GLOBAL_FLAGS}) @@ -65,7 +62,7 @@ if ( WRAP_LUA ) set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/SimpleITKLUA_wrap.cxx PROPERTIES COMPILE_FLAGS "-w" ) add_executable ( SimpleITKLua SimpleITKLuaMain.cxx SimpleITKLUA_wrap.cxx ) - target_link_libraries ( SimpleITKLua ${SimpleITK_LIBRARIES} ${LUA_LIB} ) + target_link_libraries ( SimpleITKLua ${SimpleITK_LIBRARIES} ${LUA_LIBRARIES} ) sitk_strip_target( SimpleITKLua ) endif() From 280601d3ed6e40a121201dee2a4f114181f9d26d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 10 Jun 2015 15:36:32 -0400 Subject: [PATCH 023/412] Add Lua Superbuild support Download Lua source ball form the midas server. Create minimal custom CMake file to copy into the Lua build directory to perform configuration, compilation step and installation of the executable. The created binary is passed to the actual SimpleITK project. Or the system Lua interpreter could be used. It is not supported compiling SimpleITKLua from the Superbuild Lua. Change-Id: I335184e249a1362210660001e4aa26422e71fdac --- SuperBuild/External_Lua.cmake | 35 +++++++++++++++++ SuperBuild/SuperBuild.cmake | 19 ++++++++- SuperBuild/lua.cmake | 73 +++++++++++++++++++++++++++++++++++ 3 files changed, 125 insertions(+), 2 deletions(-) create mode 100644 SuperBuild/External_Lua.cmake create mode 100644 SuperBuild/lua.cmake diff --git a/SuperBuild/External_Lua.cmake b/SuperBuild/External_Lua.cmake new file mode 100644 index 000000000..a59ac738d --- /dev/null +++ b/SuperBuild/External_Lua.cmake @@ -0,0 +1,35 @@ +# Make sure this file is included only once +get_filename_component(CMAKE_CURRENT_LIST_FILENAME ${CMAKE_CURRENT_LIST_FILE} NAME_WE) +if(${CMAKE_CURRENT_LIST_FILENAME}_FILE_INCLUDED) + return() +endif() +set(${CMAKE_CURRENT_LIST_FILENAME}_FILE_INCLUDED 1) + +set(proj Lua) + +# follow the standard EP_PREFIX locations +set(lua_binary_dir ${CMAKE_CURRENT_BINARY_DIR}/${proj}-prefix/src/${proj}-build) +set(lua_source_dir ${CMAKE_CURRENT_BINARY_DIR}/${proj}-prefix/src/${proj}) +set(lua_install_dir ${CMAKE_CURRENT_BINARY_DIR}/${proj}) + + +file(WRITE "${lua_binary_dir}/CMakeCacheInit.txt" "${ep_common_cache}" ) + +set(lua_PATCH_COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${CMAKE_CURRENT_SOURCE_DIR}/lua.cmake + ${lua_source_dir}/CMakeLists.txt +) + +ExternalProject_Add(Lua + URL http://www.lua.org/ftp/lua-5.1.5.tar.gz + URL_MD5 2e115fe26e435e33b0d5c022e4490567 + PATCH_COMMAND ${lua_PATCH_COMMAND} + CMAKE_GENERATOR ${gen} + CMAKE_ARGS + --no-warn-unused-cli + -C "${lua_binary_dir}/CMakeCacheInit.txt" + ${ep_common_args} + -D BUILD_SHARED_LIBS:BOOL=OFF + -D CMAKE_INSTALL_PREFIX:PATH=${lua_install_dir} +) +set(SITK_LUA_EXECUTABLE "${lua_install_dir}/bin/lua") diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 867cd4ec1..28f6a298c 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -246,6 +246,22 @@ include(sitkLanguageOptions) #$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ include(ExternalProject) + +#------------------------------------------------------------------------------ +# Lua +#------------------------------------------------------------------------------ +option ( USE_SYSTEM_LUA "Use a pre-compiled version of LUA 5.1 previously configured for your system" OFF ) +mark_as_advanced(USE_SYSTEM_LUA) +if ( USE_SYSTEM_LUA ) + find_package( LuaInterp REQUIRED 5.1 ) + set( SITK_LUA_EXECUTABLE ${LUA_EXECUTABLE} CACHE PATH "Lua executable used for code generation." ) + unset( LUA_EXECUTABLE CACHE ) +else() + include(External_Lua) + list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES Lua) + set( SITK_LUA_EXECUTABLE ${SITK_LUA_EXECUTABLE} CACHE PATH "Lua executable used for code generation." ) +endif() + #------------------------------------------------------------------------------ # Swig #------------------------------------------------------------------------------ @@ -317,7 +333,6 @@ ExternalProject_Add(${proj} -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY:PATH=/lib -DCMAKE_RUNTIME_OUTPUT_DIRECTORY:PATH=/bin -DCMAKE_BUNDLE_OUTPUT_DIRECTORY:PATH=/bin - -DSITK_4D_IMAGES:BOOL=${SITK_4D_IMAGES} ${ep_languages_args} # ITK -DITK_DIR:PATH=${ITK_DIR} @@ -358,7 +373,7 @@ include(External_SimpleITKExamples) #------------------------------------------------------------------------------ # List of external projects #------------------------------------------------------------------------------ -set(external_project_list ITK Swig SimpleITKExamples PCRE ${CMAKE_PROJECT_NAME}) +set(external_project_list ITK Swig SimpleITKExamples PCRE Lua ${CMAKE_PROJECT_NAME}) #----------------------------------------------------------------------------- # Dump external project dependencies diff --git a/SuperBuild/lua.cmake b/SuperBuild/lua.cmake new file mode 100644 index 000000000..a4d3fa0b3 --- /dev/null +++ b/SuperBuild/lua.cmake @@ -0,0 +1,73 @@ +cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) + +project (LUA C) + +# Setup build locations. +if(NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin) +endif() +if(NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/lib) +endif() +if(NOT CMAKE_ARCHIVE_OUTPUT_DIRECTORY) + set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/lib) +endif() + + + +#------------------------------------------------------------------------------ +# Variables for use in install rules: + +if(NOT LUA_INSTALL_RUNTIME_DIR) + set(LUA_INSTALL_RUNTIME_DIR "bin") +endif() +if(NOT LUA_INSTALL_LIBRARY_DIR) + set(LUA_INSTALL_LIBRARY_DIR "lib") +endif() +if(NOT LUA_INSTALL_ARCHIVE_DIR) + set(LUA_INSTALL_ARCHIVE_DIR "lib") +endif() +if(NOT LUA_INSTALL_INCLUDE_DIR) + set(LUA_INSTALL_INCLUDE_DIR "include") +endif() + + +if( MSVC ) + # suppress warning in Visual Studio about the securtiy of methods + add_definitions (-D_CRT_SECURE_NO_WARNINGS) + + # suppress warning: + # '<<' : result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift intended?) + SET( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4334" ) +endif() + + +# define the lua core source files +set (LUA_CORE_SRCS src/lapi.c src/lcode.c src/ldebug.c src/ldo.c src/ldump.c + src/lfunc.c src/lgc.c src/llex.c src/lmem.c src/lobject.c src/lopcodes.c + src/lparser.c src/lstate.c src/lstring.c src/ltable.c src/ltm.c src/lundump.c + src/lvm.c src/lzio.c) + +# define the lua lib source files +set (LUA_LIB_SRCS src/lauxlib.c src/lbaselib.c src/ldblib.c src/liolib.c + src/lmathlib.c src/loslib.c src/ltablib.c src/lstrlib.c src/loadlib.c src/linit.c) + +# create the library +add_library (lua ${LUA_LIB_SRCS} ${LUA_CORE_SRCS}) + +# create the lue executable and link it to the lib +add_executable (luaexec src/lua.c) +target_link_libraries (luaexec lua) + +# name the executable lua just like the library +set_target_properties(luaexec PROPERTIES OUTPUT_NAME lua) + +if ( UNIX ) + target_link_libraries ( luaexec m ) +endif() + +install ( TARGETS luaexec + RUNTIME DESTINATION ${LUA_INSTALL_RUNTIME_DIR} + LIBRARY DESTINATION ${LUA_INSTALL_LIBRARY_DIR} + ARCHIVE DESTINATION ${LUA_INSTALL_ARCHIVE_DIR} + ) From a902f91eac1deaeb468e64056a3e136ba830335a Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 10 Jun 2015 15:39:37 -0400 Subject: [PATCH 024/412] Pass all variable beginning with SITK_ to the SimpleITK build. Change-Id: I9f6408483e7d4317051a48d043ec77a26a13c3b3 --- SuperBuild/SuperBuild.cmake | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 28f6a298c..3c9dc80df 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -300,9 +300,11 @@ endif() get_cmake_property( _varNames VARIABLES ) foreach (_varName ${_varNames}) - if(_varName MATCHES "^SimpleITK_" ) - message( STATUS "Passing variable \"${_varName}=${${_varName}}\" to SimpleITK external project.") - list(APPEND SimpleITKITK_VARS ${_varName}) + if(_varName MATCHES "^SimpleITK_" OR _varName MATCHES "^SITK_" ) + if (NOT _varName MATCHES "^SITK_LANGUAGES_VARS") + message( STATUS "Passing variable \"${_varName}=${${_varName}}\" to SimpleITK external project.") + list(APPEND SimpleITKITK_VARS ${_varName}) + endif() endif() endforeach() From b4e9805eceb5373d020f6f095bb1ba22d8b24db8 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 11 Jun 2015 09:13:10 -0400 Subject: [PATCH 025/412] Removing integrated lua source code Change-Id: I28f701f07be9ba43ea486a76f561eb5dac0d1e2f --- Utilities/CMakeLists.txt | 2 +- Utilities/lua-5.1.5/CMakeLists.txt | 20 - Utilities/lua-5.1.5/COPYRIGHT | 34 - Utilities/lua-5.1.5/HISTORY | 183 ---- Utilities/lua-5.1.5/INSTALL | 99 -- Utilities/lua-5.1.5/Makefile | 128 --- Utilities/lua-5.1.5/README | 37 - Utilities/lua-5.1.5/src/Makefile | 182 ---- Utilities/lua-5.1.5/src/lapi.c | 1087 ---------------------- Utilities/lua-5.1.5/src/lapi.h | 16 - Utilities/lua-5.1.5/src/lauxlib.c | 653 -------------- Utilities/lua-5.1.5/src/lauxlib.h | 174 ---- Utilities/lua-5.1.5/src/lbaselib.c | 653 -------------- Utilities/lua-5.1.5/src/lcode.c | 831 ----------------- Utilities/lua-5.1.5/src/lcode.h | 76 -- Utilities/lua-5.1.5/src/ldblib.c | 398 --------- Utilities/lua-5.1.5/src/ldebug.c | 638 ------------- Utilities/lua-5.1.5/src/ldebug.h | 33 - Utilities/lua-5.1.5/src/ldo.c | 519 ----------- Utilities/lua-5.1.5/src/ldo.h | 57 -- Utilities/lua-5.1.5/src/ldump.c | 164 ---- Utilities/lua-5.1.5/src/lfunc.c | 174 ---- Utilities/lua-5.1.5/src/lfunc.h | 34 - Utilities/lua-5.1.5/src/lgc.c | 710 --------------- Utilities/lua-5.1.5/src/lgc.h | 110 --- Utilities/lua-5.1.5/src/linit.c | 38 - Utilities/lua-5.1.5/src/liolib.c | 556 ------------ Utilities/lua-5.1.5/src/llex.c | 463 ---------- Utilities/lua-5.1.5/src/llex.h | 81 -- Utilities/lua-5.1.5/src/llimits.h | 128 --- Utilities/lua-5.1.5/src/lmathlib.c | 263 ------ Utilities/lua-5.1.5/src/lmem.c | 86 -- Utilities/lua-5.1.5/src/lmem.h | 49 - Utilities/lua-5.1.5/src/loadlib.c | 666 -------------- Utilities/lua-5.1.5/src/lobject.c | 214 ----- Utilities/lua-5.1.5/src/lobject.h | 381 -------- Utilities/lua-5.1.5/src/lopcodes.c | 102 --- Utilities/lua-5.1.5/src/lopcodes.h | 268 ------ Utilities/lua-5.1.5/src/loslib.c | 243 ----- Utilities/lua-5.1.5/src/lparser.c | 1339 ---------------------------- Utilities/lua-5.1.5/src/lparser.h | 82 -- Utilities/lua-5.1.5/src/lstate.c | 214 ----- Utilities/lua-5.1.5/src/lstate.h | 169 ---- Utilities/lua-5.1.5/src/lstring.c | 111 --- Utilities/lua-5.1.5/src/lstring.h | 31 - Utilities/lua-5.1.5/src/lstrlib.c | 871 ------------------ Utilities/lua-5.1.5/src/ltable.c | 588 ------------ Utilities/lua-5.1.5/src/ltable.h | 40 - Utilities/lua-5.1.5/src/ltablib.c | 287 ------ Utilities/lua-5.1.5/src/ltm.c | 75 -- Utilities/lua-5.1.5/src/ltm.h | 54 -- Utilities/lua-5.1.5/src/lua.c | 392 -------- Utilities/lua-5.1.5/src/lua.h | 388 -------- Utilities/lua-5.1.5/src/luaconf.h | 763 ---------------- Utilities/lua-5.1.5/src/lualib.h | 53 -- Utilities/lua-5.1.5/src/lundump.c | 227 ----- Utilities/lua-5.1.5/src/lundump.h | 36 - Utilities/lua-5.1.5/src/lvm.c | 767 ---------------- Utilities/lua-5.1.5/src/lvm.h | 36 - Utilities/lua-5.1.5/src/lzio.c | 82 -- Utilities/lua-5.1.5/src/lzio.h | 67 -- Utilities/lua-5.1.5/src/print.c | 227 ----- 62 files changed, 1 insertion(+), 17448 deletions(-) delete mode 100644 Utilities/lua-5.1.5/CMakeLists.txt delete mode 100644 Utilities/lua-5.1.5/COPYRIGHT delete mode 100644 Utilities/lua-5.1.5/HISTORY delete mode 100644 Utilities/lua-5.1.5/INSTALL delete mode 100644 Utilities/lua-5.1.5/Makefile delete mode 100644 Utilities/lua-5.1.5/README delete mode 100644 Utilities/lua-5.1.5/src/Makefile delete mode 100644 Utilities/lua-5.1.5/src/lapi.c delete mode 100644 Utilities/lua-5.1.5/src/lapi.h delete mode 100644 Utilities/lua-5.1.5/src/lauxlib.c delete mode 100644 Utilities/lua-5.1.5/src/lauxlib.h delete mode 100644 Utilities/lua-5.1.5/src/lbaselib.c delete mode 100644 Utilities/lua-5.1.5/src/lcode.c delete mode 100644 Utilities/lua-5.1.5/src/lcode.h delete mode 100644 Utilities/lua-5.1.5/src/ldblib.c delete mode 100644 Utilities/lua-5.1.5/src/ldebug.c delete mode 100644 Utilities/lua-5.1.5/src/ldebug.h delete mode 100644 Utilities/lua-5.1.5/src/ldo.c delete mode 100644 Utilities/lua-5.1.5/src/ldo.h delete mode 100644 Utilities/lua-5.1.5/src/ldump.c delete mode 100644 Utilities/lua-5.1.5/src/lfunc.c delete mode 100644 Utilities/lua-5.1.5/src/lfunc.h delete mode 100644 Utilities/lua-5.1.5/src/lgc.c delete mode 100644 Utilities/lua-5.1.5/src/lgc.h delete mode 100644 Utilities/lua-5.1.5/src/linit.c delete mode 100644 Utilities/lua-5.1.5/src/liolib.c delete mode 100644 Utilities/lua-5.1.5/src/llex.c delete mode 100644 Utilities/lua-5.1.5/src/llex.h delete mode 100644 Utilities/lua-5.1.5/src/llimits.h delete mode 100644 Utilities/lua-5.1.5/src/lmathlib.c delete mode 100644 Utilities/lua-5.1.5/src/lmem.c delete mode 100644 Utilities/lua-5.1.5/src/lmem.h delete mode 100644 Utilities/lua-5.1.5/src/loadlib.c delete mode 100644 Utilities/lua-5.1.5/src/lobject.c delete mode 100644 Utilities/lua-5.1.5/src/lobject.h delete mode 100644 Utilities/lua-5.1.5/src/lopcodes.c delete mode 100644 Utilities/lua-5.1.5/src/lopcodes.h delete mode 100644 Utilities/lua-5.1.5/src/loslib.c delete mode 100644 Utilities/lua-5.1.5/src/lparser.c delete mode 100644 Utilities/lua-5.1.5/src/lparser.h delete mode 100644 Utilities/lua-5.1.5/src/lstate.c delete mode 100644 Utilities/lua-5.1.5/src/lstate.h delete mode 100644 Utilities/lua-5.1.5/src/lstring.c delete mode 100644 Utilities/lua-5.1.5/src/lstring.h delete mode 100644 Utilities/lua-5.1.5/src/lstrlib.c delete mode 100644 Utilities/lua-5.1.5/src/ltable.c delete mode 100644 Utilities/lua-5.1.5/src/ltable.h delete mode 100644 Utilities/lua-5.1.5/src/ltablib.c delete mode 100644 Utilities/lua-5.1.5/src/ltm.c delete mode 100644 Utilities/lua-5.1.5/src/ltm.h delete mode 100644 Utilities/lua-5.1.5/src/lua.c delete mode 100644 Utilities/lua-5.1.5/src/lua.h delete mode 100644 Utilities/lua-5.1.5/src/luaconf.h delete mode 100644 Utilities/lua-5.1.5/src/lualib.h delete mode 100644 Utilities/lua-5.1.5/src/lundump.c delete mode 100644 Utilities/lua-5.1.5/src/lundump.h delete mode 100644 Utilities/lua-5.1.5/src/lvm.c delete mode 100644 Utilities/lua-5.1.5/src/lvm.h delete mode 100644 Utilities/lua-5.1.5/src/lzio.c delete mode 100644 Utilities/lua-5.1.5/src/lzio.h delete mode 100644 Utilities/lua-5.1.5/src/print.c diff --git a/Utilities/CMakeLists.txt b/Utilities/CMakeLists.txt index 236614918..8b1378917 100644 --- a/Utilities/CMakeLists.txt +++ b/Utilities/CMakeLists.txt @@ -1 +1 @@ -add_subdirectory( lua-5.1.5 ) + diff --git a/Utilities/lua-5.1.5/CMakeLists.txt b/Utilities/lua-5.1.5/CMakeLists.txt deleted file mode 100644 index 53da60da2..000000000 --- a/Utilities/lua-5.1.5/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -if( MSVC ) - # suppress warning in Visual Studio about the securtiy of methods - add_definitions (-D_CRT_SECURE_NO_WARNINGS) - - # suppress warning: - # '<<' : result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift intended?) - SET( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4334" ) -endif() - -file ( GLOB LUA_LIB_SOURCE src/*.c ) -list ( REMOVE_ITEM LUA_LIB_SOURCE src/lua.c ) -add_library ( lua5 STATIC ${LUA_LIB_SOURCE} ) - -set ( LUA_SOURCE src/lua.c ) -add_executable ( lua ${LUA_SOURCE} ) -target_link_libraries ( lua lua5 ) - -if ( UNIX ) - target_link_libraries ( lua m ) -endif() diff --git a/Utilities/lua-5.1.5/COPYRIGHT b/Utilities/lua-5.1.5/COPYRIGHT deleted file mode 100644 index a86026803..000000000 --- a/Utilities/lua-5.1.5/COPYRIGHT +++ /dev/null @@ -1,34 +0,0 @@ -Lua License ------------ - -Lua is licensed under the terms of the MIT license reproduced below. -This means that Lua is free software and can be used for both academic -and commercial purposes at absolutely no cost. - -For details and rationale, see http://www.lua.org/license.html . - -=============================================================================== - -Copyright (C) 1994-2012 Lua.org, PUC-Rio. - -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 of COPYRIGHT) diff --git a/Utilities/lua-5.1.5/HISTORY b/Utilities/lua-5.1.5/HISTORY deleted file mode 100644 index ce0c95bc6..000000000 --- a/Utilities/lua-5.1.5/HISTORY +++ /dev/null @@ -1,183 +0,0 @@ -HISTORY for Lua 5.1 - -* Changes from version 5.0 to 5.1 - ------------------------------- - Language: - + new module system. - + new semantics for control variables of fors. - + new semantics for setn/getn. - + new syntax/semantics for varargs. - + new long strings and comments. - + new `mod' operator (`%') - + new length operator #t - + metatables for all types - API: - + new functions: lua_createtable, lua_get(set)field, lua_push(to)integer. - + user supplies memory allocator (lua_open becomes lua_newstate). - + luaopen_* functions must be called through Lua. - Implementation: - + new configuration scheme via luaconf.h. - + incremental garbage collection. - + better handling of end-of-line in the lexer. - + fully reentrant parser (new Lua function `load') - + better support for 64-bit machines. - + native loadlib support for Mac OS X. - + standard distribution in only one library (lualib.a merged into lua.a) - -* Changes from version 4.0 to 5.0 - ------------------------------- - Language: - + lexical scoping. - + Lua coroutines. - + standard libraries now packaged in tables. - + tags replaced by metatables and tag methods replaced by metamethods, - stored in metatables. - + proper tail calls. - + each function can have its own global table, which can be shared. - + new __newindex metamethod, called when we insert a new key into a table. - + new block comments: --[[ ... ]]. - + new generic for. - + new weak tables. - + new boolean type. - + new syntax "local function". - + (f()) returns the first value returned by f. - + {f()} fills a table with all values returned by f. - + \n ignored in [[\n . - + fixed and-or priorities. - + more general syntax for function definition (e.g. function a.x.y:f()...end). - + more general syntax for function calls (e.g. (print or write)(9)). - + new functions (time/date, tmpfile, unpack, require, load*, etc.). - API: - + chunks are loaded by using lua_load; new luaL_loadfile and luaL_loadbuffer. - + introduced lightweight userdata, a simple "void*" without a metatable. - + new error handling protocol: the core no longer prints error messages; - all errors are reported to the caller on the stack. - + new lua_atpanic for host cleanup. - + new, signal-safe, hook scheme. - Implementation: - + new license: MIT. - + new, faster, register-based virtual machine. - + support for external multithreading and coroutines. - + new and consistent error message format. - + the core no longer needs "stdio.h" for anything (except for a single - use of sprintf to convert numbers to strings). - + lua.c now runs the environment variable LUA_INIT, if present. It can - be "@filename", to run a file, or the chunk itself. - + support for user extensions in lua.c. - sample implementation given for command line editing. - + new dynamic loading library, active by default on several platforms. - + safe garbage-collector metamethods. - + precompiled bytecodes checked for integrity (secure binary dostring). - + strings are fully aligned. - + position capture in string.find. - + read('*l') can read lines with embedded zeros. - -* Changes from version 3.2 to 4.0 - ------------------------------- - Language: - + new "break" and "for" statements (both numerical and for tables). - + uniform treatment of globals: globals are now stored in a Lua table. - + improved error messages. - + no more '$debug': full speed *and* full debug information. - + new read form: read(N) for next N bytes. - + general read patterns now deprecated. - (still available with -DCOMPAT_READPATTERNS.) - + all return values are passed as arguments for the last function - (old semantics still available with -DLUA_COMPAT_ARGRET) - + garbage collection tag methods for tables now deprecated. - + there is now only one tag method for order. - API: - + New API: fully re-entrant, simpler, and more efficient. - + New debug API. - Implementation: - + faster than ever: cleaner virtual machine and new hashing algorithm. - + non-recursive garbage-collector algorithm. - + reduced memory usage for programs with many strings. - + improved treatment for memory allocation errors. - + improved support for 16-bit machines (we hope). - + code now compiles unmodified as both ANSI C and C++. - + numbers in bases other than 10 are converted using strtoul. - + new -f option in Lua to support #! scripts. - + luac can now combine text and binaries. - -* Changes from version 3.1 to 3.2 - ------------------------------- - + redirected all output in Lua's core to _ERRORMESSAGE and _ALERT. - + increased limit on the number of constants and globals per function - (from 2^16 to 2^24). - + debugging info (lua_debug and hooks) moved into lua_state and new API - functions provided to get and set this info. - + new debug lib gives full debugging access within Lua. - + new table functions "foreachi", "sort", "tinsert", "tremove", "getn". - + new io functions "flush", "seek". - -* Changes from version 3.0 to 3.1 - ------------------------------- - + NEW FEATURE: anonymous functions with closures (via "upvalues"). - + new syntax: - - local variables in chunks. - - better scope control with DO block END. - - constructors can now be also written: { record-part; list-part }. - - more general syntax for function calls and lvalues, e.g.: - f(x).y=1 - o:f(x,y):g(z) - f"string" is sugar for f("string") - + strings may now contain arbitrary binary data (e.g., embedded zeros). - + major code re-organization and clean-up; reduced module interdependecies. - + no arbitrary limits on the total number of constants and globals. - + support for multiple global contexts. - + better syntax error messages. - + new traversal functions "foreach" and "foreachvar". - + the default for numbers is now double. - changing it to use floats or longs is easy. - + complete debug information stored in pre-compiled chunks. - + sample interpreter now prompts user when run interactively, and also - handles control-C interruptions gracefully. - -* Changes from version 2.5 to 3.0 - ------------------------------- - + NEW CONCEPT: "tag methods". - Tag methods replace fallbacks as the meta-mechanism for extending the - semantics of Lua. Whereas fallbacks had a global nature, tag methods - work on objects having the same tag (e.g., groups of tables). - Existing code that uses fallbacks should work without change. - + new, general syntax for constructors {[exp] = exp, ... }. - + support for handling variable number of arguments in functions (varargs). - + support for conditional compilation ($if ... $else ... $end). - + cleaner semantics in API simplifies host code. - + better support for writing libraries (auxlib.h). - + better type checking and error messages in the standard library. - + luac can now also undump. - -* Changes from version 2.4 to 2.5 - ------------------------------- - + io and string libraries are now based on pattern matching; - the old libraries are still available for compatibility - + dofile and dostring can now return values (via return statement) - + better support for 16- and 64-bit machines - + expanded documentation, with more examples - -* Changes from version 2.2 to 2.4 - ------------------------------- - + external compiler creates portable binary files that can be loaded faster - + interface for debugging and profiling - + new "getglobal" fallback - + new functions for handling references to Lua objects - + new functions in standard lib - + only one copy of each string is stored - + expanded documentation, with more examples - -* Changes from version 2.1 to 2.2 - ------------------------------- - + functions now may be declared with any "lvalue" as a name - + garbage collection of functions - + support for pipes - -* Changes from version 1.1 to 2.1 - ------------------------------- - + object-oriented support - + fallbacks - + simplified syntax for tables - + many internal improvements - -(end of HISTORY) diff --git a/Utilities/lua-5.1.5/INSTALL b/Utilities/lua-5.1.5/INSTALL deleted file mode 100644 index 17eb8aee8..000000000 --- a/Utilities/lua-5.1.5/INSTALL +++ /dev/null @@ -1,99 +0,0 @@ -INSTALL for Lua 5.1 - -* Building Lua - ------------ - Lua is built in the src directory, but the build process can be - controlled from the top-level Makefile. - - Building Lua on Unix systems should be very easy. First do "make" and - see if your platform is listed. If so, just do "make xxx", where xxx - is your platform name. The platforms currently supported are: - aix ansi bsd freebsd generic linux macosx mingw posix solaris - - If your platform is not listed, try the closest one or posix, generic, - ansi, in this order. - - See below for customization instructions and for instructions on how - to build with other Windows compilers. - - If you want to check that Lua has been built correctly, do "make test" - after building Lua. Also, have a look at the example programs in test. - -* Installing Lua - -------------- - Once you have built Lua, you may want to install it in an official - place in your system. In this case, do "make install". The official - place and the way to install files are defined in Makefile. You must - have the right permissions to install files. - - If you want to build and install Lua in one step, do "make xxx install", - where xxx is your platform name. - - If you want to install Lua locally, then do "make local". This will - create directories bin, include, lib, man, and install Lua there as - follows: - - bin: lua luac - include: lua.h luaconf.h lualib.h lauxlib.h lua.hpp - lib: liblua.a - man/man1: lua.1 luac.1 - - These are the only directories you need for development. - - There are man pages for lua and luac, in both nroff and html, and a - reference manual in html in doc, some sample code in test, and some - useful stuff in etc. You don't need these directories for development. - - If you want to install Lua locally, but in some other directory, do - "make install INSTALL_TOP=xxx", where xxx is your chosen directory. - - See below for instructions for Windows and other systems. - -* Customization - ------------- - Three things can be customized by editing a file: - - Where and how to install Lua -- edit Makefile. - - How to build Lua -- edit src/Makefile. - - Lua features -- edit src/luaconf.h. - - You don't actually need to edit the Makefiles because you may set the - relevant variables when invoking make. - - On the other hand, if you need to select some Lua features, you'll need - to edit src/luaconf.h. The edited file will be the one installed, and - it will be used by any Lua clients that you build, to ensure consistency. - - We strongly recommend that you enable dynamic loading. This is done - automatically for all platforms listed above that have this feature - (and also Windows). See src/luaconf.h and also src/Makefile. - -* Building Lua on Windows and other systems - ----------------------------------------- - If you're not using the usual Unix tools, then the instructions for - building Lua depend on the compiler you use. You'll need to create - projects (or whatever your compiler uses) for building the library, - the interpreter, and the compiler, as follows: - - library: lapi.c lcode.c ldebug.c ldo.c ldump.c lfunc.c lgc.c llex.c - lmem.c lobject.c lopcodes.c lparser.c lstate.c lstring.c - ltable.c ltm.c lundump.c lvm.c lzio.c - lauxlib.c lbaselib.c ldblib.c liolib.c lmathlib.c loslib.c - ltablib.c lstrlib.c loadlib.c linit.c - - interpreter: library, lua.c - - compiler: library, luac.c print.c - - If you use Visual Studio .NET, you can use etc/luavs.bat in its - "Command Prompt". - - If all you want is to build the Lua interpreter, you may put all .c files - in a single project, except for luac.c and print.c. Or just use etc/all.c. - - To use Lua as a library in your own programs, you'll need to know how to - create and use libraries with your compiler. - - As mentioned above, you may edit luaconf.h to select some features before - building Lua. - -(end of INSTALL) diff --git a/Utilities/lua-5.1.5/Makefile b/Utilities/lua-5.1.5/Makefile deleted file mode 100644 index 209a13244..000000000 --- a/Utilities/lua-5.1.5/Makefile +++ /dev/null @@ -1,128 +0,0 @@ -# makefile for installing Lua -# see INSTALL for installation instructions -# see src/Makefile and src/luaconf.h for further customization - -# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT ======================= - -# Your platform. See PLATS for possible values. -PLAT= none - -# Where to install. The installation starts in the src and doc directories, -# so take care if INSTALL_TOP is not an absolute path. -INSTALL_TOP= /usr/local -INSTALL_BIN= $(INSTALL_TOP)/bin -INSTALL_INC= $(INSTALL_TOP)/include -INSTALL_LIB= $(INSTALL_TOP)/lib -INSTALL_MAN= $(INSTALL_TOP)/man/man1 -# -# You probably want to make INSTALL_LMOD and INSTALL_CMOD consistent with -# LUA_ROOT, LUA_LDIR, and LUA_CDIR in luaconf.h (and also with etc/lua.pc). -INSTALL_LMOD= $(INSTALL_TOP)/share/lua/$V -INSTALL_CMOD= $(INSTALL_TOP)/lib/lua/$V - -# How to install. If your install program does not support "-p", then you -# may have to run ranlib on the installed liblua.a (do "make ranlib"). -INSTALL= install -p -INSTALL_EXEC= $(INSTALL) -m 0755 -INSTALL_DATA= $(INSTALL) -m 0644 -# -# If you don't have install you can use cp instead. -# INSTALL= cp -p -# INSTALL_EXEC= $(INSTALL) -# INSTALL_DATA= $(INSTALL) - -# Utilities. -MKDIR= mkdir -p -RANLIB= ranlib - -# == END OF USER SETTINGS. NO NEED TO CHANGE ANYTHING BELOW THIS LINE ========= - -# Convenience platforms targets. -PLATS= aix ansi bsd freebsd generic linux macosx mingw posix solaris - -# What to install. -TO_BIN= lua luac -TO_INC= lua.h luaconf.h lualib.h lauxlib.h ../etc/lua.hpp -TO_LIB= liblua.a -TO_MAN= lua.1 luac.1 - -# Lua version and release. -V= 5.1 -R= 5.1.5 - -all: $(PLAT) - -$(PLATS) clean: - cd src && $(MAKE) $@ - -test: dummy - src/lua test/hello.lua - -install: dummy - cd src && $(MKDIR) $(INSTALL_BIN) $(INSTALL_INC) $(INSTALL_LIB) $(INSTALL_MAN) $(INSTALL_LMOD) $(INSTALL_CMOD) - cd src && $(INSTALL_EXEC) $(TO_BIN) $(INSTALL_BIN) - cd src && $(INSTALL_DATA) $(TO_INC) $(INSTALL_INC) - cd src && $(INSTALL_DATA) $(TO_LIB) $(INSTALL_LIB) - cd doc && $(INSTALL_DATA) $(TO_MAN) $(INSTALL_MAN) - -ranlib: - cd src && cd $(INSTALL_LIB) && $(RANLIB) $(TO_LIB) - -local: - $(MAKE) install INSTALL_TOP=.. - -none: - @echo "Please do" - @echo " make PLATFORM" - @echo "where PLATFORM is one of these:" - @echo " $(PLATS)" - @echo "See INSTALL for complete instructions." - -# make may get confused with test/ and INSTALL in a case-insensitive OS -dummy: - -# echo config parameters -echo: - @echo "" - @echo "These are the parameters currently set in src/Makefile to build Lua $R:" - @echo "" - @cd src && $(MAKE) -s echo - @echo "" - @echo "These are the parameters currently set in Makefile to install Lua $R:" - @echo "" - @echo "PLAT = $(PLAT)" - @echo "INSTALL_TOP = $(INSTALL_TOP)" - @echo "INSTALL_BIN = $(INSTALL_BIN)" - @echo "INSTALL_INC = $(INSTALL_INC)" - @echo "INSTALL_LIB = $(INSTALL_LIB)" - @echo "INSTALL_MAN = $(INSTALL_MAN)" - @echo "INSTALL_LMOD = $(INSTALL_LMOD)" - @echo "INSTALL_CMOD = $(INSTALL_CMOD)" - @echo "INSTALL_EXEC = $(INSTALL_EXEC)" - @echo "INSTALL_DATA = $(INSTALL_DATA)" - @echo "" - @echo "See also src/luaconf.h ." - @echo "" - -# echo private config parameters -pecho: - @echo "V = $(V)" - @echo "R = $(R)" - @echo "TO_BIN = $(TO_BIN)" - @echo "TO_INC = $(TO_INC)" - @echo "TO_LIB = $(TO_LIB)" - @echo "TO_MAN = $(TO_MAN)" - -# echo config parameters as Lua code -# uncomment the last sed expression if you want nil instead of empty strings -lecho: - @echo "-- installation parameters for Lua $R" - @echo "VERSION = '$V'" - @echo "RELEASE = '$R'" - @$(MAKE) echo | grep = | sed -e 's/= /= "/' -e 's/$$/"/' #-e 's/""/nil/' - @echo "-- EOF" - -# list targets that do not create files (but not all makes understand .PHONY) -.PHONY: all $(PLATS) clean test install local none dummy echo pecho lecho - -# (end of Makefile) diff --git a/Utilities/lua-5.1.5/README b/Utilities/lua-5.1.5/README deleted file mode 100644 index 11b4dff70..000000000 --- a/Utilities/lua-5.1.5/README +++ /dev/null @@ -1,37 +0,0 @@ -README for Lua 5.1 - -See INSTALL for installation instructions. -See HISTORY for a summary of changes since the last released version. - -* What is Lua? - ------------ - Lua is a powerful, light-weight programming language designed for extending - applications. Lua is also frequently used as a general-purpose, stand-alone - language. Lua is free software. - - For complete information, visit Lua's web site at http://www.lua.org/ . - For an executive summary, see http://www.lua.org/about.html . - - Lua has been used in many different projects around the world. - For a short list, see http://www.lua.org/uses.html . - -* Availability - ------------ - Lua is freely available for both academic and commercial purposes. - See COPYRIGHT and http://www.lua.org/license.html for details. - Lua can be downloaded at http://www.lua.org/download.html . - -* Installation - ------------ - Lua is implemented in pure ANSI C, and compiles unmodified in all known - platforms that have an ANSI C compiler. In most Unix-like platforms, simply - do "make" with a suitable target. See INSTALL for detailed instructions. - -* Origin - ------ - Lua is developed at Lua.org, a laboratory of the Department of Computer - Science of PUC-Rio (the Pontifical Catholic University of Rio de Janeiro - in Brazil). - For more information about the authors, see http://www.lua.org/authors.html . - -(end of README) diff --git a/Utilities/lua-5.1.5/src/Makefile b/Utilities/lua-5.1.5/src/Makefile deleted file mode 100644 index e0d4c9fa6..000000000 --- a/Utilities/lua-5.1.5/src/Makefile +++ /dev/null @@ -1,182 +0,0 @@ -# makefile for building Lua -# see ../INSTALL for installation instructions -# see ../Makefile and luaconf.h for further customization - -# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT ======================= - -# Your platform. See PLATS for possible values. -PLAT= none - -CC= gcc -CFLAGS= -O2 -Wall $(MYCFLAGS) -AR= ar rcu -RANLIB= ranlib -RM= rm -f -LIBS= -lm $(MYLIBS) - -MYCFLAGS= -MYLDFLAGS= -MYLIBS= - -# == END OF USER SETTINGS. NO NEED TO CHANGE ANYTHING BELOW THIS LINE ========= - -PLATS= aix ansi bsd freebsd generic linux macosx mingw posix solaris - -LUA_A= liblua.a -CORE_O= lapi.o lcode.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o \ - lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o \ - lundump.o lvm.o lzio.o -LIB_O= lauxlib.o lbaselib.o ldblib.o liolib.o lmathlib.o loslib.o ltablib.o \ - lstrlib.o loadlib.o linit.o - -LUA_T= lua -LUA_O= lua.o - -LUAC_T= luac -LUAC_O= luac.o print.o - -ALL_O= $(CORE_O) $(LIB_O) $(LUA_O) $(LUAC_O) -ALL_T= $(LUA_A) $(LUA_T) $(LUAC_T) -ALL_A= $(LUA_A) - -default: $(PLAT) - -all: $(ALL_T) - -o: $(ALL_O) - -a: $(ALL_A) - -$(LUA_A): $(CORE_O) $(LIB_O) - $(AR) $@ $(CORE_O) $(LIB_O) # DLL needs all object files - $(RANLIB) $@ - -$(LUA_T): $(LUA_O) $(LUA_A) - $(CC) -o $@ $(MYLDFLAGS) $(LUA_O) $(LUA_A) $(LIBS) - -$(LUAC_T): $(LUAC_O) $(LUA_A) - $(CC) -o $@ $(MYLDFLAGS) $(LUAC_O) $(LUA_A) $(LIBS) - -clean: - $(RM) $(ALL_T) $(ALL_O) - -depend: - @$(CC) $(CFLAGS) -MM l*.c print.c - -echo: - @echo "PLAT = $(PLAT)" - @echo "CC = $(CC)" - @echo "CFLAGS = $(CFLAGS)" - @echo "AR = $(AR)" - @echo "RANLIB = $(RANLIB)" - @echo "RM = $(RM)" - @echo "MYCFLAGS = $(MYCFLAGS)" - @echo "MYLDFLAGS = $(MYLDFLAGS)" - @echo "MYLIBS = $(MYLIBS)" - -# convenience targets for popular platforms - -none: - @echo "Please choose a platform:" - @echo " $(PLATS)" - -aix: - $(MAKE) all CC="xlc" CFLAGS="-O2 -DLUA_USE_POSIX -DLUA_USE_DLOPEN" MYLIBS="-ldl" MYLDFLAGS="-brtl -bexpall" - -ansi: - $(MAKE) all MYCFLAGS=-DLUA_ANSI - -bsd: - $(MAKE) all MYCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" MYLIBS="-Wl,-E" - -freebsd: - $(MAKE) all MYCFLAGS="-DLUA_USE_LINUX" MYLIBS="-Wl,-E -lreadline" - -generic: - $(MAKE) all MYCFLAGS= - -linux: - $(MAKE) all MYCFLAGS=-DLUA_USE_LINUX MYLIBS="-Wl,-E -ldl -lreadline -lhistory -lncurses" - -macosx: - $(MAKE) all MYCFLAGS=-DLUA_USE_LINUX MYLIBS="-lreadline" -# use this on Mac OS X 10.3- -# $(MAKE) all MYCFLAGS=-DLUA_USE_MACOSX - -mingw: - $(MAKE) "LUA_A=lua51.dll" "LUA_T=lua.exe" \ - "AR=$(CC) -shared -o" "RANLIB=strip --strip-unneeded" \ - "MYCFLAGS=-DLUA_BUILD_AS_DLL" "MYLIBS=" "MYLDFLAGS=-s" lua.exe - $(MAKE) "LUAC_T=luac.exe" luac.exe - -posix: - $(MAKE) all MYCFLAGS=-DLUA_USE_POSIX - -solaris: - $(MAKE) all MYCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" MYLIBS="-ldl" - -# list targets that do not create files (but not all makes understand .PHONY) -.PHONY: all $(PLATS) default o a clean depend echo none - -# DO NOT DELETE - -lapi.o: lapi.c lua.h luaconf.h lapi.h lobject.h llimits.h ldebug.h \ - lstate.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h \ - lundump.h lvm.h -lauxlib.o: lauxlib.c lua.h luaconf.h lauxlib.h -lbaselib.o: lbaselib.c lua.h luaconf.h lauxlib.h lualib.h -lcode.o: lcode.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \ - lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h lgc.h \ - ltable.h -ldblib.o: ldblib.c lua.h luaconf.h lauxlib.h lualib.h -ldebug.o: ldebug.c lua.h luaconf.h lapi.h lobject.h llimits.h lcode.h \ - llex.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h \ - lfunc.h lstring.h lgc.h ltable.h lvm.h -ldo.o: ldo.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \ - lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lparser.h lstring.h \ - ltable.h lundump.h lvm.h -ldump.o: ldump.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h \ - lzio.h lmem.h lundump.h -lfunc.o: lfunc.c lua.h luaconf.h lfunc.h lobject.h llimits.h lgc.h lmem.h \ - lstate.h ltm.h lzio.h -lgc.o: lgc.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \ - lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h -linit.o: linit.c lua.h luaconf.h lualib.h lauxlib.h -liolib.o: liolib.c lua.h luaconf.h lauxlib.h lualib.h -llex.o: llex.c lua.h luaconf.h ldo.h lobject.h llimits.h lstate.h ltm.h \ - lzio.h lmem.h llex.h lparser.h lstring.h lgc.h ltable.h -lmathlib.o: lmathlib.c lua.h luaconf.h lauxlib.h lualib.h -lmem.o: lmem.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \ - ltm.h lzio.h lmem.h ldo.h -loadlib.o: loadlib.c lua.h luaconf.h lauxlib.h lualib.h -lobject.o: lobject.c lua.h luaconf.h ldo.h lobject.h llimits.h lstate.h \ - ltm.h lzio.h lmem.h lstring.h lgc.h lvm.h -lopcodes.o: lopcodes.c lopcodes.h llimits.h lua.h luaconf.h -loslib.o: loslib.c lua.h luaconf.h lauxlib.h lualib.h -lparser.o: lparser.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \ - lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h \ - lfunc.h lstring.h lgc.h ltable.h -lstate.o: lstate.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \ - ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h llex.h lstring.h ltable.h -lstring.o: lstring.c lua.h luaconf.h lmem.h llimits.h lobject.h lstate.h \ - ltm.h lzio.h lstring.h lgc.h -lstrlib.o: lstrlib.c lua.h luaconf.h lauxlib.h lualib.h -ltable.o: ltable.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \ - ltm.h lzio.h lmem.h ldo.h lgc.h ltable.h -ltablib.o: ltablib.c lua.h luaconf.h lauxlib.h lualib.h -ltm.o: ltm.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h lzio.h \ - lmem.h lstring.h lgc.h ltable.h -lua.o: lua.c lua.h luaconf.h lauxlib.h lualib.h -luac.o: luac.c lua.h luaconf.h lauxlib.h ldo.h lobject.h llimits.h \ - lstate.h ltm.h lzio.h lmem.h lfunc.h lopcodes.h lstring.h lgc.h \ - lundump.h -lundump.o: lundump.c lua.h luaconf.h ldebug.h lstate.h lobject.h \ - llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h lundump.h -lvm.o: lvm.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \ - lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h ltable.h lvm.h -lzio.o: lzio.c lua.h luaconf.h llimits.h lmem.h lstate.h lobject.h ltm.h \ - lzio.h -print.o: print.c ldebug.h lstate.h lua.h luaconf.h lobject.h llimits.h \ - ltm.h lzio.h lmem.h lopcodes.h lundump.h - -# (end of Makefile) diff --git a/Utilities/lua-5.1.5/src/lapi.c b/Utilities/lua-5.1.5/src/lapi.c deleted file mode 100644 index 5d5145d2e..000000000 --- a/Utilities/lua-5.1.5/src/lapi.c +++ /dev/null @@ -1,1087 +0,0 @@ -/* -** $Id: lapi.c,v 2.55.1.5 2008/07/04 18:41:18 roberto Exp $ -** Lua API -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include -#include - -#define lapi_c -#define LUA_CORE - -#include "lua.h" - -#include "lapi.h" -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lgc.h" -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" -#include "lundump.h" -#include "lvm.h" - - - -const char lua_ident[] = - "$Lua: " LUA_RELEASE " " LUA_COPYRIGHT " $\n" - "$Authors: " LUA_AUTHORS " $\n" - "$URL: www.lua.org $\n"; - - - -#define api_checknelems(L, n) api_check(L, (n) <= (L->top - L->base)) - -#define api_checkvalidindex(L, i) api_check(L, (i) != luaO_nilobject) - -#define api_incr_top(L) {api_check(L, L->top < L->ci->top); L->top++;} - - - -static TValue *index2adr (lua_State *L, int idx) { - if (idx > 0) { - TValue *o = L->base + (idx - 1); - api_check(L, idx <= L->ci->top - L->base); - if (o >= L->top) return cast(TValue *, luaO_nilobject); - else return o; - } - else if (idx > LUA_REGISTRYINDEX) { - api_check(L, idx != 0 && -idx <= L->top - L->base); - return L->top + idx; - } - else switch (idx) { /* pseudo-indices */ - case LUA_REGISTRYINDEX: return registry(L); - case LUA_ENVIRONINDEX: { - Closure *func = curr_func(L); - sethvalue(L, &L->env, func->c.env); - return &L->env; - } - case LUA_GLOBALSINDEX: return gt(L); - default: { - Closure *func = curr_func(L); - idx = LUA_GLOBALSINDEX - idx; - return (idx <= func->c.nupvalues) - ? &func->c.upvalue[idx-1] - : cast(TValue *, luaO_nilobject); - } - } -} - - -static Table *getcurrenv (lua_State *L) { - if (L->ci == L->base_ci) /* no enclosing function? */ - return hvalue(gt(L)); /* use global table as environment */ - else { - Closure *func = curr_func(L); - return func->c.env; - } -} - - -void luaA_pushobject (lua_State *L, const TValue *o) { - setobj2s(L, L->top, o); - api_incr_top(L); -} - - -LUA_API int lua_checkstack (lua_State *L, int size) { - int res = 1; - lua_lock(L); - if (size > LUAI_MAXCSTACK || (L->top - L->base + size) > LUAI_MAXCSTACK) - res = 0; /* stack overflow */ - else if (size > 0) { - luaD_checkstack(L, size); - if (L->ci->top < L->top + size) - L->ci->top = L->top + size; - } - lua_unlock(L); - return res; -} - - -LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) { - int i; - if (from == to) return; - lua_lock(to); - api_checknelems(from, n); - api_check(from, G(from) == G(to)); - api_check(from, to->ci->top - to->top >= n); - from->top -= n; - for (i = 0; i < n; i++) { - setobj2s(to, to->top++, from->top + i); - } - lua_unlock(to); -} - - -LUA_API void lua_setlevel (lua_State *from, lua_State *to) { - to->nCcalls = from->nCcalls; -} - - -LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) { - lua_CFunction old; - lua_lock(L); - old = G(L)->panic; - G(L)->panic = panicf; - lua_unlock(L); - return old; -} - - -LUA_API lua_State *lua_newthread (lua_State *L) { - lua_State *L1; - lua_lock(L); - luaC_checkGC(L); - L1 = luaE_newthread(L); - setthvalue(L, L->top, L1); - api_incr_top(L); - lua_unlock(L); - luai_userstatethread(L, L1); - return L1; -} - - - -/* -** basic stack manipulation -*/ - - -LUA_API int lua_gettop (lua_State *L) { - return cast_int(L->top - L->base); -} - - -LUA_API void lua_settop (lua_State *L, int idx) { - lua_lock(L); - if (idx >= 0) { - api_check(L, idx <= L->stack_last - L->base); - while (L->top < L->base + idx) - setnilvalue(L->top++); - L->top = L->base + idx; - } - else { - api_check(L, -(idx+1) <= (L->top - L->base)); - L->top += idx+1; /* `subtract' index (index is negative) */ - } - lua_unlock(L); -} - - -LUA_API void lua_remove (lua_State *L, int idx) { - StkId p; - lua_lock(L); - p = index2adr(L, idx); - api_checkvalidindex(L, p); - while (++p < L->top) setobjs2s(L, p-1, p); - L->top--; - lua_unlock(L); -} - - -LUA_API void lua_insert (lua_State *L, int idx) { - StkId p; - StkId q; - lua_lock(L); - p = index2adr(L, idx); - api_checkvalidindex(L, p); - for (q = L->top; q>p; q--) setobjs2s(L, q, q-1); - setobjs2s(L, p, L->top); - lua_unlock(L); -} - - -LUA_API void lua_replace (lua_State *L, int idx) { - StkId o; - lua_lock(L); - /* explicit test for incompatible code */ - if (idx == LUA_ENVIRONINDEX && L->ci == L->base_ci) - luaG_runerror(L, "no calling environment"); - api_checknelems(L, 1); - o = index2adr(L, idx); - api_checkvalidindex(L, o); - if (idx == LUA_ENVIRONINDEX) { - Closure *func = curr_func(L); - api_check(L, ttistable(L->top - 1)); - func->c.env = hvalue(L->top - 1); - luaC_barrier(L, func, L->top - 1); - } - else { - setobj(L, o, L->top - 1); - if (idx < LUA_GLOBALSINDEX) /* function upvalue? */ - luaC_barrier(L, curr_func(L), L->top - 1); - } - L->top--; - lua_unlock(L); -} - - -LUA_API void lua_pushvalue (lua_State *L, int idx) { - lua_lock(L); - setobj2s(L, L->top, index2adr(L, idx)); - api_incr_top(L); - lua_unlock(L); -} - - - -/* -** access functions (stack -> C) -*/ - - -LUA_API int lua_type (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - return (o == luaO_nilobject) ? LUA_TNONE : ttype(o); -} - - -LUA_API const char *lua_typename (lua_State *L, int t) { - UNUSED(L); - return (t == LUA_TNONE) ? "no value" : luaT_typenames[t]; -} - - -LUA_API int lua_iscfunction (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - return iscfunction(o); -} - - -LUA_API int lua_isnumber (lua_State *L, int idx) { - TValue n; - const TValue *o = index2adr(L, idx); - return tonumber(o, &n); -} - - -LUA_API int lua_isstring (lua_State *L, int idx) { - int t = lua_type(L, idx); - return (t == LUA_TSTRING || t == LUA_TNUMBER); -} - - -LUA_API int lua_isuserdata (lua_State *L, int idx) { - const TValue *o = index2adr(L, idx); - return (ttisuserdata(o) || ttislightuserdata(o)); -} - - -LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { - StkId o1 = index2adr(L, index1); - StkId o2 = index2adr(L, index2); - return (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 - : luaO_rawequalObj(o1, o2); -} - - -LUA_API int lua_equal (lua_State *L, int index1, int index2) { - StkId o1, o2; - int i; - lua_lock(L); /* may call tag method */ - o1 = index2adr(L, index1); - o2 = index2adr(L, index2); - i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : equalobj(L, o1, o2); - lua_unlock(L); - return i; -} - - -LUA_API int lua_lessthan (lua_State *L, int index1, int index2) { - StkId o1, o2; - int i; - lua_lock(L); /* may call tag method */ - o1 = index2adr(L, index1); - o2 = index2adr(L, index2); - i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 - : luaV_lessthan(L, o1, o2); - lua_unlock(L); - return i; -} - - - -LUA_API lua_Number lua_tonumber (lua_State *L, int idx) { - TValue n; - const TValue *o = index2adr(L, idx); - if (tonumber(o, &n)) - return nvalue(o); - else - return 0; -} - - -LUA_API lua_Integer lua_tointeger (lua_State *L, int idx) { - TValue n; - const TValue *o = index2adr(L, idx); - if (tonumber(o, &n)) { - lua_Integer res; - lua_Number num = nvalue(o); - lua_number2integer(res, num); - return res; - } - else - return 0; -} - - -LUA_API int lua_toboolean (lua_State *L, int idx) { - const TValue *o = index2adr(L, idx); - return !l_isfalse(o); -} - - -LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { - StkId o = index2adr(L, idx); - if (!ttisstring(o)) { - lua_lock(L); /* `luaV_tostring' may create a new string */ - if (!luaV_tostring(L, o)) { /* conversion failed? */ - if (len != NULL) *len = 0; - lua_unlock(L); - return NULL; - } - luaC_checkGC(L); - o = index2adr(L, idx); /* previous call may reallocate the stack */ - lua_unlock(L); - } - if (len != NULL) *len = tsvalue(o)->len; - return svalue(o); -} - - -LUA_API size_t lua_objlen (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - switch (ttype(o)) { - case LUA_TSTRING: return tsvalue(o)->len; - case LUA_TUSERDATA: return uvalue(o)->len; - case LUA_TTABLE: return luaH_getn(hvalue(o)); - case LUA_TNUMBER: { - size_t l; - lua_lock(L); /* `luaV_tostring' may create a new string */ - l = (luaV_tostring(L, o) ? tsvalue(o)->len : 0); - lua_unlock(L); - return l; - } - default: return 0; - } -} - - -LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - return (!iscfunction(o)) ? NULL : clvalue(o)->c.f; -} - - -LUA_API void *lua_touserdata (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - switch (ttype(o)) { - case LUA_TUSERDATA: return (rawuvalue(o) + 1); - case LUA_TLIGHTUSERDATA: return pvalue(o); - default: return NULL; - } -} - - -LUA_API lua_State *lua_tothread (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - return (!ttisthread(o)) ? NULL : thvalue(o); -} - - -LUA_API const void *lua_topointer (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - switch (ttype(o)) { - case LUA_TTABLE: return hvalue(o); - case LUA_TFUNCTION: return clvalue(o); - case LUA_TTHREAD: return thvalue(o); - case LUA_TUSERDATA: - case LUA_TLIGHTUSERDATA: - return lua_touserdata(L, idx); - default: return NULL; - } -} - - - -/* -** push functions (C -> stack) -*/ - - -LUA_API void lua_pushnil (lua_State *L) { - lua_lock(L); - setnilvalue(L->top); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { - lua_lock(L); - setnvalue(L->top, n); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) { - lua_lock(L); - setnvalue(L->top, cast_num(n)); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t len) { - lua_lock(L); - luaC_checkGC(L); - setsvalue2s(L, L->top, luaS_newlstr(L, s, len)); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_pushstring (lua_State *L, const char *s) { - if (s == NULL) - lua_pushnil(L); - else - lua_pushlstring(L, s, strlen(s)); -} - - -LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt, - va_list argp) { - const char *ret; - lua_lock(L); - luaC_checkGC(L); - ret = luaO_pushvfstring(L, fmt, argp); - lua_unlock(L); - return ret; -} - - -LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) { - const char *ret; - va_list argp; - lua_lock(L); - luaC_checkGC(L); - va_start(argp, fmt); - ret = luaO_pushvfstring(L, fmt, argp); - va_end(argp); - lua_unlock(L); - return ret; -} - - -LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { - Closure *cl; - lua_lock(L); - luaC_checkGC(L); - api_checknelems(L, n); - cl = luaF_newCclosure(L, n, getcurrenv(L)); - cl->c.f = fn; - L->top -= n; - while (n--) - setobj2n(L, &cl->c.upvalue[n], L->top+n); - setclvalue(L, L->top, cl); - lua_assert(iswhite(obj2gco(cl))); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_pushboolean (lua_State *L, int b) { - lua_lock(L); - setbvalue(L->top, (b != 0)); /* ensure that true is 1 */ - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_pushlightuserdata (lua_State *L, void *p) { - lua_lock(L); - setpvalue(L->top, p); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API int lua_pushthread (lua_State *L) { - lua_lock(L); - setthvalue(L, L->top, L); - api_incr_top(L); - lua_unlock(L); - return (G(L)->mainthread == L); -} - - - -/* -** get functions (Lua -> stack) -*/ - - -LUA_API void lua_gettable (lua_State *L, int idx) { - StkId t; - lua_lock(L); - t = index2adr(L, idx); - api_checkvalidindex(L, t); - luaV_gettable(L, t, L->top - 1, L->top - 1); - lua_unlock(L); -} - - -LUA_API void lua_getfield (lua_State *L, int idx, const char *k) { - StkId t; - TValue key; - lua_lock(L); - t = index2adr(L, idx); - api_checkvalidindex(L, t); - setsvalue(L, &key, luaS_new(L, k)); - luaV_gettable(L, t, &key, L->top); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_rawget (lua_State *L, int idx) { - StkId t; - lua_lock(L); - t = index2adr(L, idx); - api_check(L, ttistable(t)); - setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1)); - lua_unlock(L); -} - - -LUA_API void lua_rawgeti (lua_State *L, int idx, int n) { - StkId o; - lua_lock(L); - o = index2adr(L, idx); - api_check(L, ttistable(o)); - setobj2s(L, L->top, luaH_getnum(hvalue(o), n)); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_createtable (lua_State *L, int narray, int nrec) { - lua_lock(L); - luaC_checkGC(L); - sethvalue(L, L->top, luaH_new(L, narray, nrec)); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API int lua_getmetatable (lua_State *L, int objindex) { - const TValue *obj; - Table *mt = NULL; - int res; - lua_lock(L); - obj = index2adr(L, objindex); - switch (ttype(obj)) { - case LUA_TTABLE: - mt = hvalue(obj)->metatable; - break; - case LUA_TUSERDATA: - mt = uvalue(obj)->metatable; - break; - default: - mt = G(L)->mt[ttype(obj)]; - break; - } - if (mt == NULL) - res = 0; - else { - sethvalue(L, L->top, mt); - api_incr_top(L); - res = 1; - } - lua_unlock(L); - return res; -} - - -LUA_API void lua_getfenv (lua_State *L, int idx) { - StkId o; - lua_lock(L); - o = index2adr(L, idx); - api_checkvalidindex(L, o); - switch (ttype(o)) { - case LUA_TFUNCTION: - sethvalue(L, L->top, clvalue(o)->c.env); - break; - case LUA_TUSERDATA: - sethvalue(L, L->top, uvalue(o)->env); - break; - case LUA_TTHREAD: - setobj2s(L, L->top, gt(thvalue(o))); - break; - default: - setnilvalue(L->top); - break; - } - api_incr_top(L); - lua_unlock(L); -} - - -/* -** set functions (stack -> Lua) -*/ - - -LUA_API void lua_settable (lua_State *L, int idx) { - StkId t; - lua_lock(L); - api_checknelems(L, 2); - t = index2adr(L, idx); - api_checkvalidindex(L, t); - luaV_settable(L, t, L->top - 2, L->top - 1); - L->top -= 2; /* pop index and value */ - lua_unlock(L); -} - - -LUA_API void lua_setfield (lua_State *L, int idx, const char *k) { - StkId t; - TValue key; - lua_lock(L); - api_checknelems(L, 1); - t = index2adr(L, idx); - api_checkvalidindex(L, t); - setsvalue(L, &key, luaS_new(L, k)); - luaV_settable(L, t, &key, L->top - 1); - L->top--; /* pop value */ - lua_unlock(L); -} - - -LUA_API void lua_rawset (lua_State *L, int idx) { - StkId t; - lua_lock(L); - api_checknelems(L, 2); - t = index2adr(L, idx); - api_check(L, ttistable(t)); - setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1); - luaC_barriert(L, hvalue(t), L->top-1); - L->top -= 2; - lua_unlock(L); -} - - -LUA_API void lua_rawseti (lua_State *L, int idx, int n) { - StkId o; - lua_lock(L); - api_checknelems(L, 1); - o = index2adr(L, idx); - api_check(L, ttistable(o)); - setobj2t(L, luaH_setnum(L, hvalue(o), n), L->top-1); - luaC_barriert(L, hvalue(o), L->top-1); - L->top--; - lua_unlock(L); -} - - -LUA_API int lua_setmetatable (lua_State *L, int objindex) { - TValue *obj; - Table *mt; - lua_lock(L); - api_checknelems(L, 1); - obj = index2adr(L, objindex); - api_checkvalidindex(L, obj); - if (ttisnil(L->top - 1)) - mt = NULL; - else { - api_check(L, ttistable(L->top - 1)); - mt = hvalue(L->top - 1); - } - switch (ttype(obj)) { - case LUA_TTABLE: { - hvalue(obj)->metatable = mt; - if (mt) - luaC_objbarriert(L, hvalue(obj), mt); - break; - } - case LUA_TUSERDATA: { - uvalue(obj)->metatable = mt; - if (mt) - luaC_objbarrier(L, rawuvalue(obj), mt); - break; - } - default: { - G(L)->mt[ttype(obj)] = mt; - break; - } - } - L->top--; - lua_unlock(L); - return 1; -} - - -LUA_API int lua_setfenv (lua_State *L, int idx) { - StkId o; - int res = 1; - lua_lock(L); - api_checknelems(L, 1); - o = index2adr(L, idx); - api_checkvalidindex(L, o); - api_check(L, ttistable(L->top - 1)); - switch (ttype(o)) { - case LUA_TFUNCTION: - clvalue(o)->c.env = hvalue(L->top - 1); - break; - case LUA_TUSERDATA: - uvalue(o)->env = hvalue(L->top - 1); - break; - case LUA_TTHREAD: - sethvalue(L, gt(thvalue(o)), hvalue(L->top - 1)); - break; - default: - res = 0; - break; - } - if (res) luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1)); - L->top--; - lua_unlock(L); - return res; -} - - -/* -** `load' and `call' functions (run Lua code) -*/ - - -#define adjustresults(L,nres) \ - { if (nres == LUA_MULTRET && L->top >= L->ci->top) L->ci->top = L->top; } - - -#define checkresults(L,na,nr) \ - api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na))) - - -LUA_API void lua_call (lua_State *L, int nargs, int nresults) { - StkId func; - lua_lock(L); - api_checknelems(L, nargs+1); - checkresults(L, nargs, nresults); - func = L->top - (nargs+1); - luaD_call(L, func, nresults); - adjustresults(L, nresults); - lua_unlock(L); -} - - - -/* -** Execute a protected call. -*/ -struct CallS { /* data to `f_call' */ - StkId func; - int nresults; -}; - - -static void f_call (lua_State *L, void *ud) { - struct CallS *c = cast(struct CallS *, ud); - luaD_call(L, c->func, c->nresults); -} - - - -LUA_API int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc) { - struct CallS c; - int status; - ptrdiff_t func; - lua_lock(L); - api_checknelems(L, nargs+1); - checkresults(L, nargs, nresults); - if (errfunc == 0) - func = 0; - else { - StkId o = index2adr(L, errfunc); - api_checkvalidindex(L, o); - func = savestack(L, o); - } - c.func = L->top - (nargs+1); /* function to be called */ - c.nresults = nresults; - status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func); - adjustresults(L, nresults); - lua_unlock(L); - return status; -} - - -/* -** Execute a protected C call. -*/ -struct CCallS { /* data to `f_Ccall' */ - lua_CFunction func; - void *ud; -}; - - -static void f_Ccall (lua_State *L, void *ud) { - struct CCallS *c = cast(struct CCallS *, ud); - Closure *cl; - cl = luaF_newCclosure(L, 0, getcurrenv(L)); - cl->c.f = c->func; - setclvalue(L, L->top, cl); /* push function */ - api_incr_top(L); - setpvalue(L->top, c->ud); /* push only argument */ - api_incr_top(L); - luaD_call(L, L->top - 2, 0); -} - - -LUA_API int lua_cpcall (lua_State *L, lua_CFunction func, void *ud) { - struct CCallS c; - int status; - lua_lock(L); - c.func = func; - c.ud = ud; - status = luaD_pcall(L, f_Ccall, &c, savestack(L, L->top), 0); - lua_unlock(L); - return status; -} - - -LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, - const char *chunkname) { - ZIO z; - int status; - lua_lock(L); - if (!chunkname) chunkname = "?"; - luaZ_init(L, &z, reader, data); - status = luaD_protectedparser(L, &z, chunkname); - lua_unlock(L); - return status; -} - - -LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) { - int status; - TValue *o; - lua_lock(L); - api_checknelems(L, 1); - o = L->top - 1; - if (isLfunction(o)) - status = luaU_dump(L, clvalue(o)->l.p, writer, data, 0); - else - status = 1; - lua_unlock(L); - return status; -} - - -LUA_API int lua_status (lua_State *L) { - return L->status; -} - - -/* -** Garbage-collection function -*/ - -LUA_API int lua_gc (lua_State *L, int what, int data) { - int res = 0; - global_State *g; - lua_lock(L); - g = G(L); - switch (what) { - case LUA_GCSTOP: { - g->GCthreshold = MAX_LUMEM; - break; - } - case LUA_GCRESTART: { - g->GCthreshold = g->totalbytes; - break; - } - case LUA_GCCOLLECT: { - luaC_fullgc(L); - break; - } - case LUA_GCCOUNT: { - /* GC values are expressed in Kbytes: #bytes/2^10 */ - res = cast_int(g->totalbytes >> 10); - break; - } - case LUA_GCCOUNTB: { - res = cast_int(g->totalbytes & 0x3ff); - break; - } - case LUA_GCSTEP: { - lu_mem a = (cast(lu_mem, data) << 10); - if (a <= g->totalbytes) - g->GCthreshold = g->totalbytes - a; - else - g->GCthreshold = 0; - while (g->GCthreshold <= g->totalbytes) { - luaC_step(L); - if (g->gcstate == GCSpause) { /* end of cycle? */ - res = 1; /* signal it */ - break; - } - } - break; - } - case LUA_GCSETPAUSE: { - res = g->gcpause; - g->gcpause = data; - break; - } - case LUA_GCSETSTEPMUL: { - res = g->gcstepmul; - g->gcstepmul = data; - break; - } - default: res = -1; /* invalid option */ - } - lua_unlock(L); - return res; -} - - - -/* -** miscellaneous functions -*/ - - -LUA_API int lua_error (lua_State *L) { - lua_lock(L); - api_checknelems(L, 1); - luaG_errormsg(L); - lua_unlock(L); - return 0; /* to avoid warnings */ -} - - -LUA_API int lua_next (lua_State *L, int idx) { - StkId t; - int more; - lua_lock(L); - t = index2adr(L, idx); - api_check(L, ttistable(t)); - more = luaH_next(L, hvalue(t), L->top - 1); - if (more) { - api_incr_top(L); - } - else /* no more elements */ - L->top -= 1; /* remove key */ - lua_unlock(L); - return more; -} - - -LUA_API void lua_concat (lua_State *L, int n) { - lua_lock(L); - api_checknelems(L, n); - if (n >= 2) { - luaC_checkGC(L); - luaV_concat(L, n, cast_int(L->top - L->base) - 1); - L->top -= (n-1); - } - else if (n == 0) { /* push empty string */ - setsvalue2s(L, L->top, luaS_newlstr(L, "", 0)); - api_incr_top(L); - } - /* else n == 1; nothing to do */ - lua_unlock(L); -} - - -LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) { - lua_Alloc f; - lua_lock(L); - if (ud) *ud = G(L)->ud; - f = G(L)->frealloc; - lua_unlock(L); - return f; -} - - -LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) { - lua_lock(L); - G(L)->ud = ud; - G(L)->frealloc = f; - lua_unlock(L); -} - - -LUA_API void *lua_newuserdata (lua_State *L, size_t size) { - Udata *u; - lua_lock(L); - luaC_checkGC(L); - u = luaS_newudata(L, size, getcurrenv(L)); - setuvalue(L, L->top, u); - api_incr_top(L); - lua_unlock(L); - return u + 1; -} - - - - -static const char *aux_upvalue (StkId fi, int n, TValue **val) { - Closure *f; - if (!ttisfunction(fi)) return NULL; - f = clvalue(fi); - if (f->c.isC) { - if (!(1 <= n && n <= f->c.nupvalues)) return NULL; - *val = &f->c.upvalue[n-1]; - return ""; - } - else { - Proto *p = f->l.p; - if (!(1 <= n && n <= p->sizeupvalues)) return NULL; - *val = f->l.upvals[n-1]->v; - return getstr(p->upvalues[n-1]); - } -} - - -LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { - const char *name; - TValue *val; - lua_lock(L); - name = aux_upvalue(index2adr(L, funcindex), n, &val); - if (name) { - setobj2s(L, L->top, val); - api_incr_top(L); - } - lua_unlock(L); - return name; -} - - -LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) { - const char *name; - TValue *val; - StkId fi; - lua_lock(L); - fi = index2adr(L, funcindex); - api_checknelems(L, 1); - name = aux_upvalue(fi, n, &val); - if (name) { - L->top--; - setobj(L, val, L->top); - luaC_barrier(L, clvalue(fi), L->top); - } - lua_unlock(L); - return name; -} - diff --git a/Utilities/lua-5.1.5/src/lapi.h b/Utilities/lua-5.1.5/src/lapi.h deleted file mode 100644 index 2c3fab244..000000000 --- a/Utilities/lua-5.1.5/src/lapi.h +++ /dev/null @@ -1,16 +0,0 @@ -/* -** $Id: lapi.h,v 2.2.1.1 2007/12/27 13:02:25 roberto Exp $ -** Auxiliary functions from Lua API -** See Copyright Notice in lua.h -*/ - -#ifndef lapi_h -#define lapi_h - - -#include "lobject.h" - - -LUAI_FUNC void luaA_pushobject (lua_State *L, const TValue *o); - -#endif diff --git a/Utilities/lua-5.1.5/src/lauxlib.c b/Utilities/lua-5.1.5/src/lauxlib.c deleted file mode 100644 index fda8652ce..000000000 --- a/Utilities/lua-5.1.5/src/lauxlib.c +++ /dev/null @@ -1,653 +0,0 @@ -/* -** $Id: lauxlib.c,v 1.159.1.3 2008/01/21 13:20:51 roberto Exp $ -** Auxiliary functions for building Lua libraries -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include -#include -#include -#include - - -/* This file uses only the official API of Lua. -** Any function declared here could be written as an application function. -*/ - -#define lauxlib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" - - -#define FREELIST_REF 0 /* free list of references */ - - -/* convert a stack index to positive */ -#define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \ - lua_gettop(L) + (i) + 1) - - -/* -** {====================================================== -** Error-report functions -** ======================================================= -*/ - - -LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) { - lua_Debug ar; - if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ - return luaL_error(L, "bad argument #%d (%s)", narg, extramsg); - lua_getinfo(L, "n", &ar); - if (strcmp(ar.namewhat, "method") == 0) { - narg--; /* do not count `self' */ - if (narg == 0) /* error is in the self argument itself? */ - return luaL_error(L, "calling " LUA_QS " on bad self (%s)", - ar.name, extramsg); - } - if (ar.name == NULL) - ar.name = "?"; - return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)", - narg, ar.name, extramsg); -} - - -LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) { - const char *msg = lua_pushfstring(L, "%s expected, got %s", - tname, luaL_typename(L, narg)); - return luaL_argerror(L, narg, msg); -} - - -static void tag_error (lua_State *L, int narg, int tag) { - luaL_typerror(L, narg, lua_typename(L, tag)); -} - - -LUALIB_API void luaL_where (lua_State *L, int level) { - lua_Debug ar; - if (lua_getstack(L, level, &ar)) { /* check function at level */ - lua_getinfo(L, "Sl", &ar); /* get info about it */ - if (ar.currentline > 0) { /* is there info? */ - lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline); - return; - } - } - lua_pushliteral(L, ""); /* else, no information available... */ -} - - -LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) { - va_list argp; - va_start(argp, fmt); - luaL_where(L, 1); - lua_pushvfstring(L, fmt, argp); - va_end(argp); - lua_concat(L, 2); - return lua_error(L); -} - -/* }====================================================== */ - - -LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def, - const char *const lst[]) { - const char *name = (def) ? luaL_optstring(L, narg, def) : - luaL_checkstring(L, narg); - int i; - for (i=0; lst[i]; i++) - if (strcmp(lst[i], name) == 0) - return i; - return luaL_argerror(L, narg, - lua_pushfstring(L, "invalid option " LUA_QS, name)); -} - - -LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { - lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */ - if (!lua_isnil(L, -1)) /* name already in use? */ - return 0; /* leave previous value on top, but return 0 */ - lua_pop(L, 1); - lua_newtable(L); /* create metatable */ - lua_pushvalue(L, -1); - lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ - return 1; -} - - -LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { - void *p = lua_touserdata(L, ud); - if (p != NULL) { /* value is a userdata? */ - if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ - lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */ - if (lua_rawequal(L, -1, -2)) { /* does it have the correct mt? */ - lua_pop(L, 2); /* remove both metatables */ - return p; - } - } - } - luaL_typerror(L, ud, tname); /* else error */ - return NULL; /* to avoid warnings */ -} - - -LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) { - if (!lua_checkstack(L, space)) - luaL_error(L, "stack overflow (%s)", mes); -} - - -LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) { - if (lua_type(L, narg) != t) - tag_error(L, narg, t); -} - - -LUALIB_API void luaL_checkany (lua_State *L, int narg) { - if (lua_type(L, narg) == LUA_TNONE) - luaL_argerror(L, narg, "value expected"); -} - - -LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) { - const char *s = lua_tolstring(L, narg, len); - if (!s) tag_error(L, narg, LUA_TSTRING); - return s; -} - - -LUALIB_API const char *luaL_optlstring (lua_State *L, int narg, - const char *def, size_t *len) { - if (lua_isnoneornil(L, narg)) { - if (len) - *len = (def ? strlen(def) : 0); - return def; - } - else return luaL_checklstring(L, narg, len); -} - - -LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) { - lua_Number d = lua_tonumber(L, narg); - if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */ - tag_error(L, narg, LUA_TNUMBER); - return d; -} - - -LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) { - return luaL_opt(L, luaL_checknumber, narg, def); -} - - -LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) { - lua_Integer d = lua_tointeger(L, narg); - if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */ - tag_error(L, narg, LUA_TNUMBER); - return d; -} - - -LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg, - lua_Integer def) { - return luaL_opt(L, luaL_checkinteger, narg, def); -} - - -LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { - if (!lua_getmetatable(L, obj)) /* no metatable? */ - return 0; - lua_pushstring(L, event); - lua_rawget(L, -2); - if (lua_isnil(L, -1)) { - lua_pop(L, 2); /* remove metatable and metafield */ - return 0; - } - else { - lua_remove(L, -2); /* remove only metatable */ - return 1; - } -} - - -LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) { - obj = abs_index(L, obj); - if (!luaL_getmetafield(L, obj, event)) /* no metafield? */ - return 0; - lua_pushvalue(L, obj); - lua_call(L, 1, 1); - return 1; -} - - -LUALIB_API void (luaL_register) (lua_State *L, const char *libname, - const luaL_Reg *l) { - luaI_openlib(L, libname, l, 0); -} - - -static int libsize (const luaL_Reg *l) { - int size = 0; - for (; l->name; l++) size++; - return size; -} - - -LUALIB_API void luaI_openlib (lua_State *L, const char *libname, - const luaL_Reg *l, int nup) { - if (libname) { - int size = libsize(l); - /* check whether lib already exists */ - luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); - lua_getfield(L, -1, libname); /* get _LOADED[libname] */ - if (!lua_istable(L, -1)) { /* not found? */ - lua_pop(L, 1); /* remove previous result */ - /* try global variable (and create one if it does not exist) */ - if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL) - luaL_error(L, "name conflict for module " LUA_QS, libname); - lua_pushvalue(L, -1); - lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */ - } - lua_remove(L, -2); /* remove _LOADED table */ - lua_insert(L, -(nup+1)); /* move library table to below upvalues */ - } - for (; l->name; l++) { - int i; - for (i=0; ifunc, nup); - lua_setfield(L, -(nup+2), l->name); - } - lua_pop(L, nup); /* remove upvalues */ -} - - - -/* -** {====================================================== -** getn-setn: size for arrays -** ======================================================= -*/ - -#if defined(LUA_COMPAT_GETN) - -static int checkint (lua_State *L, int topop) { - int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1; - lua_pop(L, topop); - return n; -} - - -static void getsizes (lua_State *L) { - lua_getfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); - if (lua_isnil(L, -1)) { /* no `size' table? */ - lua_pop(L, 1); /* remove nil */ - lua_newtable(L); /* create it */ - lua_pushvalue(L, -1); /* `size' will be its own metatable */ - lua_setmetatable(L, -2); - lua_pushliteral(L, "kv"); - lua_setfield(L, -2, "__mode"); /* metatable(N).__mode = "kv" */ - lua_pushvalue(L, -1); - lua_setfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); /* store in register */ - } -} - - -LUALIB_API void luaL_setn (lua_State *L, int t, int n) { - t = abs_index(L, t); - lua_pushliteral(L, "n"); - lua_rawget(L, t); - if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */ - lua_pushliteral(L, "n"); /* use it */ - lua_pushinteger(L, n); - lua_rawset(L, t); - } - else { /* use `sizes' */ - getsizes(L); - lua_pushvalue(L, t); - lua_pushinteger(L, n); - lua_rawset(L, -3); /* sizes[t] = n */ - lua_pop(L, 1); /* remove `sizes' */ - } -} - - -LUALIB_API int luaL_getn (lua_State *L, int t) { - int n; - t = abs_index(L, t); - lua_pushliteral(L, "n"); /* try t.n */ - lua_rawget(L, t); - if ((n = checkint(L, 1)) >= 0) return n; - getsizes(L); /* else try sizes[t] */ - lua_pushvalue(L, t); - lua_rawget(L, -2); - if ((n = checkint(L, 2)) >= 0) return n; - return (int)lua_objlen(L, t); -} - -#endif - -/* }====================================================== */ - - - -LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p, - const char *r) { - const char *wild; - size_t l = strlen(p); - luaL_Buffer b; - luaL_buffinit(L, &b); - while ((wild = strstr(s, p)) != NULL) { - luaL_addlstring(&b, s, wild - s); /* push prefix */ - luaL_addstring(&b, r); /* push replacement in place of pattern */ - s = wild + l; /* continue after `p' */ - } - luaL_addstring(&b, s); /* push last suffix */ - luaL_pushresult(&b); - return lua_tostring(L, -1); -} - - -LUALIB_API const char *luaL_findtable (lua_State *L, int idx, - const char *fname, int szhint) { - const char *e; - lua_pushvalue(L, idx); - do { - e = strchr(fname, '.'); - if (e == NULL) e = fname + strlen(fname); - lua_pushlstring(L, fname, e - fname); - lua_rawget(L, -2); - if (lua_isnil(L, -1)) { /* no such field? */ - lua_pop(L, 1); /* remove this nil */ - lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */ - lua_pushlstring(L, fname, e - fname); - lua_pushvalue(L, -2); - lua_settable(L, -4); /* set new table into field */ - } - else if (!lua_istable(L, -1)) { /* field has a non-table value? */ - lua_pop(L, 2); /* remove table and value */ - return fname; /* return problematic part of the name */ - } - lua_remove(L, -2); /* remove previous table */ - fname = e + 1; - } while (*e == '.'); - return NULL; -} - - - -/* -** {====================================================== -** Generic Buffer manipulation -** ======================================================= -*/ - - -#define bufflen(B) ((B)->p - (B)->buffer) -#define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B))) - -#define LIMIT (LUA_MINSTACK/2) - - -static int emptybuffer (luaL_Buffer *B) { - size_t l = bufflen(B); - if (l == 0) return 0; /* put nothing on stack */ - else { - lua_pushlstring(B->L, B->buffer, l); - B->p = B->buffer; - B->lvl++; - return 1; - } -} - - -static void adjuststack (luaL_Buffer *B) { - if (B->lvl > 1) { - lua_State *L = B->L; - int toget = 1; /* number of levels to concat */ - size_t toplen = lua_strlen(L, -1); - do { - size_t l = lua_strlen(L, -(toget+1)); - if (B->lvl - toget + 1 >= LIMIT || toplen > l) { - toplen += l; - toget++; - } - else break; - } while (toget < B->lvl); - lua_concat(L, toget); - B->lvl = B->lvl - toget + 1; - } -} - - -LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) { - if (emptybuffer(B)) - adjuststack(B); - return B->buffer; -} - - -LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { - while (l--) - luaL_addchar(B, *s++); -} - - -LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) { - luaL_addlstring(B, s, strlen(s)); -} - - -LUALIB_API void luaL_pushresult (luaL_Buffer *B) { - emptybuffer(B); - lua_concat(B->L, B->lvl); - B->lvl = 1; -} - - -LUALIB_API void luaL_addvalue (luaL_Buffer *B) { - lua_State *L = B->L; - size_t vl; - const char *s = lua_tolstring(L, -1, &vl); - if (vl <= bufffree(B)) { /* fit into buffer? */ - memcpy(B->p, s, vl); /* put it there */ - B->p += vl; - lua_pop(L, 1); /* remove from stack */ - } - else { - if (emptybuffer(B)) - lua_insert(L, -2); /* put buffer before new value */ - B->lvl++; /* add new value into B stack */ - adjuststack(B); - } -} - - -LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) { - B->L = L; - B->p = B->buffer; - B->lvl = 0; -} - -/* }====================================================== */ - - -LUALIB_API int luaL_ref (lua_State *L, int t) { - int ref; - t = abs_index(L, t); - if (lua_isnil(L, -1)) { - lua_pop(L, 1); /* remove from stack */ - return LUA_REFNIL; /* `nil' has a unique fixed reference */ - } - lua_rawgeti(L, t, FREELIST_REF); /* get first free element */ - ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */ - lua_pop(L, 1); /* remove it from stack */ - if (ref != 0) { /* any free element? */ - lua_rawgeti(L, t, ref); /* remove it from list */ - lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */ - } - else { /* no free elements */ - ref = (int)lua_objlen(L, t); - ref++; /* create new reference */ - } - lua_rawseti(L, t, ref); - return ref; -} - - -LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { - if (ref >= 0) { - t = abs_index(L, t); - lua_rawgeti(L, t, FREELIST_REF); - lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */ - lua_pushinteger(L, ref); - lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */ - } -} - - - -/* -** {====================================================== -** Load functions -** ======================================================= -*/ - -typedef struct LoadF { - int extraline; - FILE *f; - char buff[LUAL_BUFFERSIZE]; -} LoadF; - - -static const char *getF (lua_State *L, void *ud, size_t *size) { - LoadF *lf = (LoadF *)ud; - (void)L; - if (lf->extraline) { - lf->extraline = 0; - *size = 1; - return "\n"; - } - if (feof(lf->f)) return NULL; - *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); - return (*size > 0) ? lf->buff : NULL; -} - - -static int errfile (lua_State *L, const char *what, int fnameindex) { - const char *serr = strerror(errno); - const char *filename = lua_tostring(L, fnameindex) + 1; - lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr); - lua_remove(L, fnameindex); - return LUA_ERRFILE; -} - - -LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) { - LoadF lf; - int status, readstatus; - int c; - int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ - lf.extraline = 0; - if (filename == NULL) { - lua_pushliteral(L, "=stdin"); - lf.f = stdin; - } - else { - lua_pushfstring(L, "@%s", filename); - lf.f = fopen(filename, "r"); - if (lf.f == NULL) return errfile(L, "open", fnameindex); - } - c = getc(lf.f); - if (c == '#') { /* Unix exec. file? */ - lf.extraline = 1; - while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */ - if (c == '\n') c = getc(lf.f); - } - if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */ - lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */ - if (lf.f == NULL) return errfile(L, "reopen", fnameindex); - /* skip eventual `#!...' */ - while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) - ; - lf.extraline = 0; - } - ungetc(c, lf.f); - status = lua_load(L, getF, &lf, lua_tostring(L, -1)); - readstatus = ferror(lf.f); - if (filename) fclose(lf.f); /* close file (even in case of errors) */ - if (readstatus) { - lua_settop(L, fnameindex); /* ignore results from `lua_load' */ - return errfile(L, "read", fnameindex); - } - lua_remove(L, fnameindex); - return status; -} - - -typedef struct LoadS { - const char *s; - size_t size; -} LoadS; - - -static const char *getS (lua_State *L, void *ud, size_t *size) { - LoadS *ls = (LoadS *)ud; - (void)L; - if (ls->size == 0) return NULL; - *size = ls->size; - ls->size = 0; - return ls->s; -} - - -LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size, - const char *name) { - LoadS ls; - ls.s = buff; - ls.size = size; - return lua_load(L, getS, &ls, name); -} - - -LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s) { - return luaL_loadbuffer(L, s, strlen(s), s); -} - - - -/* }====================================================== */ - - -static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { - (void)ud; - (void)osize; - if (nsize == 0) { - free(ptr); - return NULL; - } - else - return realloc(ptr, nsize); -} - - -static int panic (lua_State *L) { - (void)L; /* to avoid warnings */ - fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n", - lua_tostring(L, -1)); - return 0; -} - - -LUALIB_API lua_State *luaL_newstate (void) { - lua_State *L = lua_newstate(l_alloc, NULL); - if (L) lua_atpanic(L, &panic); - return L; -} - diff --git a/Utilities/lua-5.1.5/src/lauxlib.h b/Utilities/lua-5.1.5/src/lauxlib.h deleted file mode 100644 index 34258235d..000000000 --- a/Utilities/lua-5.1.5/src/lauxlib.h +++ /dev/null @@ -1,174 +0,0 @@ -/* -** $Id: lauxlib.h,v 1.88.1.1 2007/12/27 13:02:25 roberto Exp $ -** Auxiliary functions for building Lua libraries -** See Copyright Notice in lua.h -*/ - - -#ifndef lauxlib_h -#define lauxlib_h - - -#include -#include - -#include "lua.h" - - -#if defined(LUA_COMPAT_GETN) -LUALIB_API int (luaL_getn) (lua_State *L, int t); -LUALIB_API void (luaL_setn) (lua_State *L, int t, int n); -#else -#define luaL_getn(L,i) ((int)lua_objlen(L, i)) -#define luaL_setn(L,i,j) ((void)0) /* no op! */ -#endif - -#if defined(LUA_COMPAT_OPENLIB) -#define luaI_openlib luaL_openlib -#endif - - -/* extra error code for `luaL_load' */ -#define LUA_ERRFILE (LUA_ERRERR+1) - - -typedef struct luaL_Reg { - const char *name; - lua_CFunction func; -} luaL_Reg; - - - -LUALIB_API void (luaI_openlib) (lua_State *L, const char *libname, - const luaL_Reg *l, int nup); -LUALIB_API void (luaL_register) (lua_State *L, const char *libname, - const luaL_Reg *l); -LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e); -LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e); -LUALIB_API int (luaL_typerror) (lua_State *L, int narg, const char *tname); -LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg); -LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg, - size_t *l); -LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg, - const char *def, size_t *l); -LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int numArg); -LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int nArg, lua_Number def); - -LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg); -LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg, - lua_Integer def); - -LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg); -LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t); -LUALIB_API void (luaL_checkany) (lua_State *L, int narg); - -LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname); -LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); - -LUALIB_API void (luaL_where) (lua_State *L, int lvl); -LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...); - -LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def, - const char *const lst[]); - -LUALIB_API int (luaL_ref) (lua_State *L, int t); -LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); - -LUALIB_API int (luaL_loadfile) (lua_State *L, const char *filename); -LUALIB_API int (luaL_loadbuffer) (lua_State *L, const char *buff, size_t sz, - const char *name); -LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); - -LUALIB_API lua_State *(luaL_newstate) (void); - - -LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p, - const char *r); - -LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx, - const char *fname, int szhint); - - - - -/* -** =============================================================== -** some useful macros -** =============================================================== -*/ - -#define luaL_argcheck(L, cond,numarg,extramsg) \ - ((void)((cond) || luaL_argerror(L, (numarg), (extramsg)))) -#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) -#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) -#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) -#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) -#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) -#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) - -#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) - -#define luaL_dofile(L, fn) \ - (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_dostring(L, s) \ - (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) - -#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) - -/* -** {====================================================== -** Generic Buffer manipulation -** ======================================================= -*/ - - - -typedef struct luaL_Buffer { - char *p; /* current position in buffer */ - int lvl; /* number of strings in the stack (level) */ - lua_State *L; - char buffer[LUAL_BUFFERSIZE]; -} luaL_Buffer; - -#define luaL_addchar(B,c) \ - ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \ - (*(B)->p++ = (char)(c))) - -/* compatibility only */ -#define luaL_putchar(B,c) luaL_addchar(B,c) - -#define luaL_addsize(B,n) ((B)->p += (n)) - -LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B); -LUALIB_API char *(luaL_prepbuffer) (luaL_Buffer *B); -LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l); -LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s); -LUALIB_API void (luaL_addvalue) (luaL_Buffer *B); -LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); - - -/* }====================================================== */ - - -/* compatibility with ref system */ - -/* pre-defined references */ -#define LUA_NOREF (-2) -#define LUA_REFNIL (-1) - -#define lua_ref(L,lock) ((lock) ? luaL_ref(L, LUA_REGISTRYINDEX) : \ - (lua_pushstring(L, "unlocked references are obsolete"), lua_error(L), 0)) - -#define lua_unref(L,ref) luaL_unref(L, LUA_REGISTRYINDEX, (ref)) - -#define lua_getref(L,ref) lua_rawgeti(L, LUA_REGISTRYINDEX, (ref)) - - -#define luaL_reg luaL_Reg - -#endif - - diff --git a/Utilities/lua-5.1.5/src/lbaselib.c b/Utilities/lua-5.1.5/src/lbaselib.c deleted file mode 100644 index 2ab550bd4..000000000 --- a/Utilities/lua-5.1.5/src/lbaselib.c +++ /dev/null @@ -1,653 +0,0 @@ -/* -** $Id: lbaselib.c,v 1.191.1.6 2008/02/14 16:46:22 roberto Exp $ -** Basic library -** See Copyright Notice in lua.h -*/ - - - -#include -#include -#include -#include - -#define lbaselib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - - - -/* -** If your system does not support `stdout', you can just remove this function. -** If you need, you can define your own `print' function, following this -** model but changing `fputs' to put the strings at a proper place -** (a console window or a log file, for instance). -*/ -static int luaB_print (lua_State *L) { - int n = lua_gettop(L); /* number of arguments */ - int i; - lua_getglobal(L, "tostring"); - for (i=1; i<=n; i++) { - const char *s; - lua_pushvalue(L, -1); /* function to be called */ - lua_pushvalue(L, i); /* value to print */ - lua_call(L, 1, 1); - s = lua_tostring(L, -1); /* get result */ - if (s == NULL) - return luaL_error(L, LUA_QL("tostring") " must return a string to " - LUA_QL("print")); - if (i>1) fputs("\t", stdout); - fputs(s, stdout); - lua_pop(L, 1); /* pop result */ - } - fputs("\n", stdout); - return 0; -} - - -static int luaB_tonumber (lua_State *L) { - int base = luaL_optint(L, 2, 10); - if (base == 10) { /* standard conversion */ - luaL_checkany(L, 1); - if (lua_isnumber(L, 1)) { - lua_pushnumber(L, lua_tonumber(L, 1)); - return 1; - } - } - else { - const char *s1 = luaL_checkstring(L, 1); - char *s2; - unsigned long n; - luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); - n = strtoul(s1, &s2, base); - if (s1 != s2) { /* at least one valid digit? */ - while (isspace((unsigned char)(*s2))) s2++; /* skip trailing spaces */ - if (*s2 == '\0') { /* no invalid trailing characters? */ - lua_pushnumber(L, (lua_Number)n); - return 1; - } - } - } - lua_pushnil(L); /* else not a number */ - return 1; -} - - -static int luaB_error (lua_State *L) { - int level = luaL_optint(L, 2, 1); - lua_settop(L, 1); - if (lua_isstring(L, 1) && level > 0) { /* add extra information? */ - luaL_where(L, level); - lua_pushvalue(L, 1); - lua_concat(L, 2); - } - return lua_error(L); -} - - -static int luaB_getmetatable (lua_State *L) { - luaL_checkany(L, 1); - if (!lua_getmetatable(L, 1)) { - lua_pushnil(L); - return 1; /* no metatable */ - } - luaL_getmetafield(L, 1, "__metatable"); - return 1; /* returns either __metatable field (if present) or metatable */ -} - - -static int luaB_setmetatable (lua_State *L) { - int t = lua_type(L, 2); - luaL_checktype(L, 1, LUA_TTABLE); - luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, - "nil or table expected"); - if (luaL_getmetafield(L, 1, "__metatable")) - luaL_error(L, "cannot change a protected metatable"); - lua_settop(L, 2); - lua_setmetatable(L, 1); - return 1; -} - - -static void getfunc (lua_State *L, int opt) { - if (lua_isfunction(L, 1)) lua_pushvalue(L, 1); - else { - lua_Debug ar; - int level = opt ? luaL_optint(L, 1, 1) : luaL_checkint(L, 1); - luaL_argcheck(L, level >= 0, 1, "level must be non-negative"); - if (lua_getstack(L, level, &ar) == 0) - luaL_argerror(L, 1, "invalid level"); - lua_getinfo(L, "f", &ar); - if (lua_isnil(L, -1)) - luaL_error(L, "no function environment for tail call at level %d", - level); - } -} - - -static int luaB_getfenv (lua_State *L) { - getfunc(L, 1); - if (lua_iscfunction(L, -1)) /* is a C function? */ - lua_pushvalue(L, LUA_GLOBALSINDEX); /* return the thread's global env. */ - else - lua_getfenv(L, -1); - return 1; -} - - -static int luaB_setfenv (lua_State *L) { - luaL_checktype(L, 2, LUA_TTABLE); - getfunc(L, 0); - lua_pushvalue(L, 2); - if (lua_isnumber(L, 1) && lua_tonumber(L, 1) == 0) { - /* change environment of current thread */ - lua_pushthread(L); - lua_insert(L, -2); - lua_setfenv(L, -2); - return 0; - } - else if (lua_iscfunction(L, -2) || lua_setfenv(L, -2) == 0) - luaL_error(L, - LUA_QL("setfenv") " cannot change environment of given object"); - return 1; -} - - -static int luaB_rawequal (lua_State *L) { - luaL_checkany(L, 1); - luaL_checkany(L, 2); - lua_pushboolean(L, lua_rawequal(L, 1, 2)); - return 1; -} - - -static int luaB_rawget (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - luaL_checkany(L, 2); - lua_settop(L, 2); - lua_rawget(L, 1); - return 1; -} - -static int luaB_rawset (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - luaL_checkany(L, 2); - luaL_checkany(L, 3); - lua_settop(L, 3); - lua_rawset(L, 1); - return 1; -} - - -static int luaB_gcinfo (lua_State *L) { - lua_pushinteger(L, lua_getgccount(L)); - return 1; -} - - -static int luaB_collectgarbage (lua_State *L) { - static const char *const opts[] = {"stop", "restart", "collect", - "count", "step", "setpause", "setstepmul", NULL}; - static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, - LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL}; - int o = luaL_checkoption(L, 1, "collect", opts); - int ex = luaL_optint(L, 2, 0); - int res = lua_gc(L, optsnum[o], ex); - switch (optsnum[o]) { - case LUA_GCCOUNT: { - int b = lua_gc(L, LUA_GCCOUNTB, 0); - lua_pushnumber(L, res + ((lua_Number)b/1024)); - return 1; - } - case LUA_GCSTEP: { - lua_pushboolean(L, res); - return 1; - } - default: { - lua_pushnumber(L, res); - return 1; - } - } -} - - -static int luaB_type (lua_State *L) { - luaL_checkany(L, 1); - lua_pushstring(L, luaL_typename(L, 1)); - return 1; -} - - -static int luaB_next (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - lua_settop(L, 2); /* create a 2nd argument if there isn't one */ - if (lua_next(L, 1)) - return 2; - else { - lua_pushnil(L); - return 1; - } -} - - -static int luaB_pairs (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */ - lua_pushvalue(L, 1); /* state, */ - lua_pushnil(L); /* and initial value */ - return 3; -} - - -static int ipairsaux (lua_State *L) { - int i = luaL_checkint(L, 2); - luaL_checktype(L, 1, LUA_TTABLE); - i++; /* next value */ - lua_pushinteger(L, i); - lua_rawgeti(L, 1, i); - return (lua_isnil(L, -1)) ? 0 : 2; -} - - -static int luaB_ipairs (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */ - lua_pushvalue(L, 1); /* state, */ - lua_pushinteger(L, 0); /* and initial value */ - return 3; -} - - -static int load_aux (lua_State *L, int status) { - if (status == 0) /* OK? */ - return 1; - else { - lua_pushnil(L); - lua_insert(L, -2); /* put before error message */ - return 2; /* return nil plus error message */ - } -} - - -static int luaB_loadstring (lua_State *L) { - size_t l; - const char *s = luaL_checklstring(L, 1, &l); - const char *chunkname = luaL_optstring(L, 2, s); - return load_aux(L, luaL_loadbuffer(L, s, l, chunkname)); -} - - -static int luaB_loadfile (lua_State *L) { - const char *fname = luaL_optstring(L, 1, NULL); - return load_aux(L, luaL_loadfile(L, fname)); -} - - -/* -** Reader for generic `load' function: `lua_load' uses the -** stack for internal stuff, so the reader cannot change the -** stack top. Instead, it keeps its resulting string in a -** reserved slot inside the stack. -*/ -static const char *generic_reader (lua_State *L, void *ud, size_t *size) { - (void)ud; /* to avoid warnings */ - luaL_checkstack(L, 2, "too many nested functions"); - lua_pushvalue(L, 1); /* get function */ - lua_call(L, 0, 1); /* call it */ - if (lua_isnil(L, -1)) { - *size = 0; - return NULL; - } - else if (lua_isstring(L, -1)) { - lua_replace(L, 3); /* save string in a reserved stack slot */ - return lua_tolstring(L, 3, size); - } - else luaL_error(L, "reader function must return a string"); - return NULL; /* to avoid warnings */ -} - - -static int luaB_load (lua_State *L) { - int status; - const char *cname = luaL_optstring(L, 2, "=(load)"); - luaL_checktype(L, 1, LUA_TFUNCTION); - lua_settop(L, 3); /* function, eventual name, plus one reserved slot */ - status = lua_load(L, generic_reader, NULL, cname); - return load_aux(L, status); -} - - -static int luaB_dofile (lua_State *L) { - const char *fname = luaL_optstring(L, 1, NULL); - int n = lua_gettop(L); - if (luaL_loadfile(L, fname) != 0) lua_error(L); - lua_call(L, 0, LUA_MULTRET); - return lua_gettop(L) - n; -} - - -static int luaB_assert (lua_State *L) { - luaL_checkany(L, 1); - if (!lua_toboolean(L, 1)) - return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!")); - return lua_gettop(L); -} - - -static int luaB_unpack (lua_State *L) { - int i, e, n; - luaL_checktype(L, 1, LUA_TTABLE); - i = luaL_optint(L, 2, 1); - e = luaL_opt(L, luaL_checkint, 3, luaL_getn(L, 1)); - if (i > e) return 0; /* empty range */ - n = e - i + 1; /* number of elements */ - if (n <= 0 || !lua_checkstack(L, n)) /* n <= 0 means arith. overflow */ - return luaL_error(L, "too many results to unpack"); - lua_rawgeti(L, 1, i); /* push arg[i] (avoiding overflow problems) */ - while (i++ < e) /* push arg[i + 1...e] */ - lua_rawgeti(L, 1, i); - return n; -} - - -static int luaB_select (lua_State *L) { - int n = lua_gettop(L); - if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') { - lua_pushinteger(L, n-1); - return 1; - } - else { - int i = luaL_checkint(L, 1); - if (i < 0) i = n + i; - else if (i > n) i = n; - luaL_argcheck(L, 1 <= i, 1, "index out of range"); - return n - i; - } -} - - -static int luaB_pcall (lua_State *L) { - int status; - luaL_checkany(L, 1); - status = lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0); - lua_pushboolean(L, (status == 0)); - lua_insert(L, 1); - return lua_gettop(L); /* return status + all results */ -} - - -static int luaB_xpcall (lua_State *L) { - int status; - luaL_checkany(L, 2); - lua_settop(L, 2); - lua_insert(L, 1); /* put error function under function to be called */ - status = lua_pcall(L, 0, LUA_MULTRET, 1); - lua_pushboolean(L, (status == 0)); - lua_replace(L, 1); - return lua_gettop(L); /* return status + all results */ -} - - -static int luaB_tostring (lua_State *L) { - luaL_checkany(L, 1); - if (luaL_callmeta(L, 1, "__tostring")) /* is there a metafield? */ - return 1; /* use its value */ - switch (lua_type(L, 1)) { - case LUA_TNUMBER: - lua_pushstring(L, lua_tostring(L, 1)); - break; - case LUA_TSTRING: - lua_pushvalue(L, 1); - break; - case LUA_TBOOLEAN: - lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false")); - break; - case LUA_TNIL: - lua_pushliteral(L, "nil"); - break; - default: - lua_pushfstring(L, "%s: %p", luaL_typename(L, 1), lua_topointer(L, 1)); - break; - } - return 1; -} - - -static int luaB_newproxy (lua_State *L) { - lua_settop(L, 1); - lua_newuserdata(L, 0); /* create proxy */ - if (lua_toboolean(L, 1) == 0) - return 1; /* no metatable */ - else if (lua_isboolean(L, 1)) { - lua_newtable(L); /* create a new metatable `m' ... */ - lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */ - lua_pushboolean(L, 1); - lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */ - } - else { - int validproxy = 0; /* to check if weaktable[metatable(u)] == true */ - if (lua_getmetatable(L, 1)) { - lua_rawget(L, lua_upvalueindex(1)); - validproxy = lua_toboolean(L, -1); - lua_pop(L, 1); /* remove value */ - } - luaL_argcheck(L, validproxy, 1, "boolean or proxy expected"); - lua_getmetatable(L, 1); /* metatable is valid; get it */ - } - lua_setmetatable(L, 2); - return 1; -} - - -static const luaL_Reg base_funcs[] = { - {"assert", luaB_assert}, - {"collectgarbage", luaB_collectgarbage}, - {"dofile", luaB_dofile}, - {"error", luaB_error}, - {"gcinfo", luaB_gcinfo}, - {"getfenv", luaB_getfenv}, - {"getmetatable", luaB_getmetatable}, - {"loadfile", luaB_loadfile}, - {"load", luaB_load}, - {"loadstring", luaB_loadstring}, - {"next", luaB_next}, - {"pcall", luaB_pcall}, - {"print", luaB_print}, - {"rawequal", luaB_rawequal}, - {"rawget", luaB_rawget}, - {"rawset", luaB_rawset}, - {"select", luaB_select}, - {"setfenv", luaB_setfenv}, - {"setmetatable", luaB_setmetatable}, - {"tonumber", luaB_tonumber}, - {"tostring", luaB_tostring}, - {"type", luaB_type}, - {"unpack", luaB_unpack}, - {"xpcall", luaB_xpcall}, - {NULL, NULL} -}; - - -/* -** {====================================================== -** Coroutine library -** ======================================================= -*/ - -#define CO_RUN 0 /* running */ -#define CO_SUS 1 /* suspended */ -#define CO_NOR 2 /* 'normal' (it resumed another coroutine) */ -#define CO_DEAD 3 - -static const char *const statnames[] = - {"running", "suspended", "normal", "dead"}; - -static int costatus (lua_State *L, lua_State *co) { - if (L == co) return CO_RUN; - switch (lua_status(co)) { - case LUA_YIELD: - return CO_SUS; - case 0: { - lua_Debug ar; - if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */ - return CO_NOR; /* it is running */ - else if (lua_gettop(co) == 0) - return CO_DEAD; - else - return CO_SUS; /* initial state */ - } - default: /* some error occured */ - return CO_DEAD; - } -} - - -static int luaB_costatus (lua_State *L) { - lua_State *co = lua_tothread(L, 1); - luaL_argcheck(L, co, 1, "coroutine expected"); - lua_pushstring(L, statnames[costatus(L, co)]); - return 1; -} - - -static int auxresume (lua_State *L, lua_State *co, int narg) { - int status = costatus(L, co); - if (!lua_checkstack(co, narg)) - luaL_error(L, "too many arguments to resume"); - if (status != CO_SUS) { - lua_pushfstring(L, "cannot resume %s coroutine", statnames[status]); - return -1; /* error flag */ - } - lua_xmove(L, co, narg); - lua_setlevel(L, co); - status = lua_resume(co, narg); - if (status == 0 || status == LUA_YIELD) { - int nres = lua_gettop(co); - if (!lua_checkstack(L, nres + 1)) - luaL_error(L, "too many results to resume"); - lua_xmove(co, L, nres); /* move yielded values */ - return nres; - } - else { - lua_xmove(co, L, 1); /* move error message */ - return -1; /* error flag */ - } -} - - -static int luaB_coresume (lua_State *L) { - lua_State *co = lua_tothread(L, 1); - int r; - luaL_argcheck(L, co, 1, "coroutine expected"); - r = auxresume(L, co, lua_gettop(L) - 1); - if (r < 0) { - lua_pushboolean(L, 0); - lua_insert(L, -2); - return 2; /* return false + error message */ - } - else { - lua_pushboolean(L, 1); - lua_insert(L, -(r + 1)); - return r + 1; /* return true + `resume' returns */ - } -} - - -static int luaB_auxwrap (lua_State *L) { - lua_State *co = lua_tothread(L, lua_upvalueindex(1)); - int r = auxresume(L, co, lua_gettop(L)); - if (r < 0) { - if (lua_isstring(L, -1)) { /* error object is a string? */ - luaL_where(L, 1); /* add extra info */ - lua_insert(L, -2); - lua_concat(L, 2); - } - lua_error(L); /* propagate error */ - } - return r; -} - - -static int luaB_cocreate (lua_State *L) { - lua_State *NL = lua_newthread(L); - luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1, - "Lua function expected"); - lua_pushvalue(L, 1); /* move function to top */ - lua_xmove(L, NL, 1); /* move function from L to NL */ - return 1; -} - - -static int luaB_cowrap (lua_State *L) { - luaB_cocreate(L); - lua_pushcclosure(L, luaB_auxwrap, 1); - return 1; -} - - -static int luaB_yield (lua_State *L) { - return lua_yield(L, lua_gettop(L)); -} - - -static int luaB_corunning (lua_State *L) { - if (lua_pushthread(L)) - lua_pushnil(L); /* main thread is not a coroutine */ - return 1; -} - - -static const luaL_Reg co_funcs[] = { - {"create", luaB_cocreate}, - {"resume", luaB_coresume}, - {"running", luaB_corunning}, - {"status", luaB_costatus}, - {"wrap", luaB_cowrap}, - {"yield", luaB_yield}, - {NULL, NULL} -}; - -/* }====================================================== */ - - -static void auxopen (lua_State *L, const char *name, - lua_CFunction f, lua_CFunction u) { - lua_pushcfunction(L, u); - lua_pushcclosure(L, f, 1); - lua_setfield(L, -2, name); -} - - -static void base_open (lua_State *L) { - /* set global _G */ - lua_pushvalue(L, LUA_GLOBALSINDEX); - lua_setglobal(L, "_G"); - /* open lib into global table */ - luaL_register(L, "_G", base_funcs); - lua_pushliteral(L, LUA_VERSION); - lua_setglobal(L, "_VERSION"); /* set global _VERSION */ - /* `ipairs' and `pairs' need auxiliary functions as upvalues */ - auxopen(L, "ipairs", luaB_ipairs, ipairsaux); - auxopen(L, "pairs", luaB_pairs, luaB_next); - /* `newproxy' needs a weaktable as upvalue */ - lua_createtable(L, 0, 1); /* new table `w' */ - lua_pushvalue(L, -1); /* `w' will be its own metatable */ - lua_setmetatable(L, -2); - lua_pushliteral(L, "kv"); - lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */ - lua_pushcclosure(L, luaB_newproxy, 1); - lua_setglobal(L, "newproxy"); /* set global `newproxy' */ -} - - -LUALIB_API int luaopen_base (lua_State *L) { - base_open(L); - luaL_register(L, LUA_COLIBNAME, co_funcs); - return 2; -} - diff --git a/Utilities/lua-5.1.5/src/lcode.c b/Utilities/lua-5.1.5/src/lcode.c deleted file mode 100644 index 679cb9cfd..000000000 --- a/Utilities/lua-5.1.5/src/lcode.c +++ /dev/null @@ -1,831 +0,0 @@ -/* -** $Id: lcode.c,v 2.25.1.5 2011/01/31 14:53:16 roberto Exp $ -** Code generator for Lua -** See Copyright Notice in lua.h -*/ - - -#include - -#define lcode_c -#define LUA_CORE - -#include "lua.h" - -#include "lcode.h" -#include "ldebug.h" -#include "ldo.h" -#include "lgc.h" -#include "llex.h" -#include "lmem.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lparser.h" -#include "ltable.h" - - -#define hasjumps(e) ((e)->t != (e)->f) - - -static int isnumeral(expdesc *e) { - return (e->k == VKNUM && e->t == NO_JUMP && e->f == NO_JUMP); -} - - -void luaK_nil (FuncState *fs, int from, int n) { - Instruction *previous; - if (fs->pc > fs->lasttarget) { /* no jumps to current position? */ - if (fs->pc == 0) { /* function start? */ - if (from >= fs->nactvar) - return; /* positions are already clean */ - } - else { - previous = &fs->f->code[fs->pc-1]; - if (GET_OPCODE(*previous) == OP_LOADNIL) { - int pfrom = GETARG_A(*previous); - int pto = GETARG_B(*previous); - if (pfrom <= from && from <= pto+1) { /* can connect both? */ - if (from+n-1 > pto) - SETARG_B(*previous, from+n-1); - return; - } - } - } - } - luaK_codeABC(fs, OP_LOADNIL, from, from+n-1, 0); /* else no optimization */ -} - - -int luaK_jump (FuncState *fs) { - int jpc = fs->jpc; /* save list of jumps to here */ - int j; - fs->jpc = NO_JUMP; - j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP); - luaK_concat(fs, &j, jpc); /* keep them on hold */ - return j; -} - - -void luaK_ret (FuncState *fs, int first, int nret) { - luaK_codeABC(fs, OP_RETURN, first, nret+1, 0); -} - - -static int condjump (FuncState *fs, OpCode op, int A, int B, int C) { - luaK_codeABC(fs, op, A, B, C); - return luaK_jump(fs); -} - - -static void fixjump (FuncState *fs, int pc, int dest) { - Instruction *jmp = &fs->f->code[pc]; - int offset = dest-(pc+1); - lua_assert(dest != NO_JUMP); - if (abs(offset) > MAXARG_sBx) - luaX_syntaxerror(fs->ls, "control structure too long"); - SETARG_sBx(*jmp, offset); -} - - -/* -** returns current `pc' and marks it as a jump target (to avoid wrong -** optimizations with consecutive instructions not in the same basic block). -*/ -int luaK_getlabel (FuncState *fs) { - fs->lasttarget = fs->pc; - return fs->pc; -} - - -static int getjump (FuncState *fs, int pc) { - int offset = GETARG_sBx(fs->f->code[pc]); - if (offset == NO_JUMP) /* point to itself represents end of list */ - return NO_JUMP; /* end of list */ - else - return (pc+1)+offset; /* turn offset into absolute position */ -} - - -static Instruction *getjumpcontrol (FuncState *fs, int pc) { - Instruction *pi = &fs->f->code[pc]; - if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1)))) - return pi-1; - else - return pi; -} - - -/* -** check whether list has any jump that do not produce a value -** (or produce an inverted value) -*/ -static int need_value (FuncState *fs, int list) { - for (; list != NO_JUMP; list = getjump(fs, list)) { - Instruction i = *getjumpcontrol(fs, list); - if (GET_OPCODE(i) != OP_TESTSET) return 1; - } - return 0; /* not found */ -} - - -static int patchtestreg (FuncState *fs, int node, int reg) { - Instruction *i = getjumpcontrol(fs, node); - if (GET_OPCODE(*i) != OP_TESTSET) - return 0; /* cannot patch other instructions */ - if (reg != NO_REG && reg != GETARG_B(*i)) - SETARG_A(*i, reg); - else /* no register to put value or register already has the value */ - *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i)); - - return 1; -} - - -static void removevalues (FuncState *fs, int list) { - for (; list != NO_JUMP; list = getjump(fs, list)) - patchtestreg(fs, list, NO_REG); -} - - -static void patchlistaux (FuncState *fs, int list, int vtarget, int reg, - int dtarget) { - while (list != NO_JUMP) { - int next = getjump(fs, list); - if (patchtestreg(fs, list, reg)) - fixjump(fs, list, vtarget); - else - fixjump(fs, list, dtarget); /* jump to default target */ - list = next; - } -} - - -static void dischargejpc (FuncState *fs) { - patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc); - fs->jpc = NO_JUMP; -} - - -void luaK_patchlist (FuncState *fs, int list, int target) { - if (target == fs->pc) - luaK_patchtohere(fs, list); - else { - lua_assert(target < fs->pc); - patchlistaux(fs, list, target, NO_REG, target); - } -} - - -void luaK_patchtohere (FuncState *fs, int list) { - luaK_getlabel(fs); - luaK_concat(fs, &fs->jpc, list); -} - - -void luaK_concat (FuncState *fs, int *l1, int l2) { - if (l2 == NO_JUMP) return; - else if (*l1 == NO_JUMP) - *l1 = l2; - else { - int list = *l1; - int next; - while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ - list = next; - fixjump(fs, list, l2); - } -} - - -void luaK_checkstack (FuncState *fs, int n) { - int newstack = fs->freereg + n; - if (newstack > fs->f->maxstacksize) { - if (newstack >= MAXSTACK) - luaX_syntaxerror(fs->ls, "function or expression too complex"); - fs->f->maxstacksize = cast_byte(newstack); - } -} - - -void luaK_reserveregs (FuncState *fs, int n) { - luaK_checkstack(fs, n); - fs->freereg += n; -} - - -static void freereg (FuncState *fs, int reg) { - if (!ISK(reg) && reg >= fs->nactvar) { - fs->freereg--; - lua_assert(reg == fs->freereg); - } -} - - -static void freeexp (FuncState *fs, expdesc *e) { - if (e->k == VNONRELOC) - freereg(fs, e->u.s.info); -} - - -static int addk (FuncState *fs, TValue *k, TValue *v) { - lua_State *L = fs->L; - TValue *idx = luaH_set(L, fs->h, k); - Proto *f = fs->f; - int oldsize = f->sizek; - if (ttisnumber(idx)) { - lua_assert(luaO_rawequalObj(&fs->f->k[cast_int(nvalue(idx))], v)); - return cast_int(nvalue(idx)); - } - else { /* constant not found; create a new entry */ - setnvalue(idx, cast_num(fs->nk)); - luaM_growvector(L, f->k, fs->nk, f->sizek, TValue, - MAXARG_Bx, "constant table overflow"); - while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); - setobj(L, &f->k[fs->nk], v); - luaC_barrier(L, f, v); - return fs->nk++; - } -} - - -int luaK_stringK (FuncState *fs, TString *s) { - TValue o; - setsvalue(fs->L, &o, s); - return addk(fs, &o, &o); -} - - -int luaK_numberK (FuncState *fs, lua_Number r) { - TValue o; - setnvalue(&o, r); - return addk(fs, &o, &o); -} - - -static int boolK (FuncState *fs, int b) { - TValue o; - setbvalue(&o, b); - return addk(fs, &o, &o); -} - - -static int nilK (FuncState *fs) { - TValue k, v; - setnilvalue(&v); - /* cannot use nil as key; instead use table itself to represent nil */ - sethvalue(fs->L, &k, fs->h); - return addk(fs, &k, &v); -} - - -void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) { - if (e->k == VCALL) { /* expression is an open function call? */ - SETARG_C(getcode(fs, e), nresults+1); - } - else if (e->k == VVARARG) { - SETARG_B(getcode(fs, e), nresults+1); - SETARG_A(getcode(fs, e), fs->freereg); - luaK_reserveregs(fs, 1); - } -} - - -void luaK_setoneret (FuncState *fs, expdesc *e) { - if (e->k == VCALL) { /* expression is an open function call? */ - e->k = VNONRELOC; - e->u.s.info = GETARG_A(getcode(fs, e)); - } - else if (e->k == VVARARG) { - SETARG_B(getcode(fs, e), 2); - e->k = VRELOCABLE; /* can relocate its simple result */ - } -} - - -void luaK_dischargevars (FuncState *fs, expdesc *e) { - switch (e->k) { - case VLOCAL: { - e->k = VNONRELOC; - break; - } - case VUPVAL: { - e->u.s.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.s.info, 0); - e->k = VRELOCABLE; - break; - } - case VGLOBAL: { - e->u.s.info = luaK_codeABx(fs, OP_GETGLOBAL, 0, e->u.s.info); - e->k = VRELOCABLE; - break; - } - case VINDEXED: { - freereg(fs, e->u.s.aux); - freereg(fs, e->u.s.info); - e->u.s.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.s.info, e->u.s.aux); - e->k = VRELOCABLE; - break; - } - case VVARARG: - case VCALL: { - luaK_setoneret(fs, e); - break; - } - default: break; /* there is one value available (somewhere) */ - } -} - - -static int code_label (FuncState *fs, int A, int b, int jump) { - luaK_getlabel(fs); /* those instructions may be jump targets */ - return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump); -} - - -static void discharge2reg (FuncState *fs, expdesc *e, int reg) { - luaK_dischargevars(fs, e); - switch (e->k) { - case VNIL: { - luaK_nil(fs, reg, 1); - break; - } - case VFALSE: case VTRUE: { - luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0); - break; - } - case VK: { - luaK_codeABx(fs, OP_LOADK, reg, e->u.s.info); - break; - } - case VKNUM: { - luaK_codeABx(fs, OP_LOADK, reg, luaK_numberK(fs, e->u.nval)); - break; - } - case VRELOCABLE: { - Instruction *pc = &getcode(fs, e); - SETARG_A(*pc, reg); - break; - } - case VNONRELOC: { - if (reg != e->u.s.info) - luaK_codeABC(fs, OP_MOVE, reg, e->u.s.info, 0); - break; - } - default: { - lua_assert(e->k == VVOID || e->k == VJMP); - return; /* nothing to do... */ - } - } - e->u.s.info = reg; - e->k = VNONRELOC; -} - - -static void discharge2anyreg (FuncState *fs, expdesc *e) { - if (e->k != VNONRELOC) { - luaK_reserveregs(fs, 1); - discharge2reg(fs, e, fs->freereg-1); - } -} - - -static void exp2reg (FuncState *fs, expdesc *e, int reg) { - discharge2reg(fs, e, reg); - if (e->k == VJMP) - luaK_concat(fs, &e->t, e->u.s.info); /* put this jump in `t' list */ - if (hasjumps(e)) { - int final; /* position after whole expression */ - int p_f = NO_JUMP; /* position of an eventual LOAD false */ - int p_t = NO_JUMP; /* position of an eventual LOAD true */ - if (need_value(fs, e->t) || need_value(fs, e->f)) { - int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs); - p_f = code_label(fs, reg, 0, 1); - p_t = code_label(fs, reg, 1, 0); - luaK_patchtohere(fs, fj); - } - final = luaK_getlabel(fs); - patchlistaux(fs, e->f, final, reg, p_f); - patchlistaux(fs, e->t, final, reg, p_t); - } - e->f = e->t = NO_JUMP; - e->u.s.info = reg; - e->k = VNONRELOC; -} - - -void luaK_exp2nextreg (FuncState *fs, expdesc *e) { - luaK_dischargevars(fs, e); - freeexp(fs, e); - luaK_reserveregs(fs, 1); - exp2reg(fs, e, fs->freereg - 1); -} - - -int luaK_exp2anyreg (FuncState *fs, expdesc *e) { - luaK_dischargevars(fs, e); - if (e->k == VNONRELOC) { - if (!hasjumps(e)) return e->u.s.info; /* exp is already in a register */ - if (e->u.s.info >= fs->nactvar) { /* reg. is not a local? */ - exp2reg(fs, e, e->u.s.info); /* put value on it */ - return e->u.s.info; - } - } - luaK_exp2nextreg(fs, e); /* default */ - return e->u.s.info; -} - - -void luaK_exp2val (FuncState *fs, expdesc *e) { - if (hasjumps(e)) - luaK_exp2anyreg(fs, e); - else - luaK_dischargevars(fs, e); -} - - -int luaK_exp2RK (FuncState *fs, expdesc *e) { - luaK_exp2val(fs, e); - switch (e->k) { - case VKNUM: - case VTRUE: - case VFALSE: - case VNIL: { - if (fs->nk <= MAXINDEXRK) { /* constant fit in RK operand? */ - e->u.s.info = (e->k == VNIL) ? nilK(fs) : - (e->k == VKNUM) ? luaK_numberK(fs, e->u.nval) : - boolK(fs, (e->k == VTRUE)); - e->k = VK; - return RKASK(e->u.s.info); - } - else break; - } - case VK: { - if (e->u.s.info <= MAXINDEXRK) /* constant fit in argC? */ - return RKASK(e->u.s.info); - else break; - } - default: break; - } - /* not a constant in the right range: put it in a register */ - return luaK_exp2anyreg(fs, e); -} - - -void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { - switch (var->k) { - case VLOCAL: { - freeexp(fs, ex); - exp2reg(fs, ex, var->u.s.info); - return; - } - case VUPVAL: { - int e = luaK_exp2anyreg(fs, ex); - luaK_codeABC(fs, OP_SETUPVAL, e, var->u.s.info, 0); - break; - } - case VGLOBAL: { - int e = luaK_exp2anyreg(fs, ex); - luaK_codeABx(fs, OP_SETGLOBAL, e, var->u.s.info); - break; - } - case VINDEXED: { - int e = luaK_exp2RK(fs, ex); - luaK_codeABC(fs, OP_SETTABLE, var->u.s.info, var->u.s.aux, e); - break; - } - default: { - lua_assert(0); /* invalid var kind to store */ - break; - } - } - freeexp(fs, ex); -} - - -void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { - int func; - luaK_exp2anyreg(fs, e); - freeexp(fs, e); - func = fs->freereg; - luaK_reserveregs(fs, 2); - luaK_codeABC(fs, OP_SELF, func, e->u.s.info, luaK_exp2RK(fs, key)); - freeexp(fs, key); - e->u.s.info = func; - e->k = VNONRELOC; -} - - -static void invertjump (FuncState *fs, expdesc *e) { - Instruction *pc = getjumpcontrol(fs, e->u.s.info); - lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && - GET_OPCODE(*pc) != OP_TEST); - SETARG_A(*pc, !(GETARG_A(*pc))); -} - - -static int jumponcond (FuncState *fs, expdesc *e, int cond) { - if (e->k == VRELOCABLE) { - Instruction ie = getcode(fs, e); - if (GET_OPCODE(ie) == OP_NOT) { - fs->pc--; /* remove previous OP_NOT */ - return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond); - } - /* else go through */ - } - discharge2anyreg(fs, e); - freeexp(fs, e); - return condjump(fs, OP_TESTSET, NO_REG, e->u.s.info, cond); -} - - -void luaK_goiftrue (FuncState *fs, expdesc *e) { - int pc; /* pc of last jump */ - luaK_dischargevars(fs, e); - switch (e->k) { - case VK: case VKNUM: case VTRUE: { - pc = NO_JUMP; /* always true; do nothing */ - break; - } - case VJMP: { - invertjump(fs, e); - pc = e->u.s.info; - break; - } - default: { - pc = jumponcond(fs, e, 0); - break; - } - } - luaK_concat(fs, &e->f, pc); /* insert last jump in `f' list */ - luaK_patchtohere(fs, e->t); - e->t = NO_JUMP; -} - - -static void luaK_goiffalse (FuncState *fs, expdesc *e) { - int pc; /* pc of last jump */ - luaK_dischargevars(fs, e); - switch (e->k) { - case VNIL: case VFALSE: { - pc = NO_JUMP; /* always false; do nothing */ - break; - } - case VJMP: { - pc = e->u.s.info; - break; - } - default: { - pc = jumponcond(fs, e, 1); - break; - } - } - luaK_concat(fs, &e->t, pc); /* insert last jump in `t' list */ - luaK_patchtohere(fs, e->f); - e->f = NO_JUMP; -} - - -static void codenot (FuncState *fs, expdesc *e) { - luaK_dischargevars(fs, e); - switch (e->k) { - case VNIL: case VFALSE: { - e->k = VTRUE; - break; - } - case VK: case VKNUM: case VTRUE: { - e->k = VFALSE; - break; - } - case VJMP: { - invertjump(fs, e); - break; - } - case VRELOCABLE: - case VNONRELOC: { - discharge2anyreg(fs, e); - freeexp(fs, e); - e->u.s.info = luaK_codeABC(fs, OP_NOT, 0, e->u.s.info, 0); - e->k = VRELOCABLE; - break; - } - default: { - lua_assert(0); /* cannot happen */ - break; - } - } - /* interchange true and false lists */ - { int temp = e->f; e->f = e->t; e->t = temp; } - removevalues(fs, e->f); - removevalues(fs, e->t); -} - - -void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { - t->u.s.aux = luaK_exp2RK(fs, k); - t->k = VINDEXED; -} - - -static int constfolding (OpCode op, expdesc *e1, expdesc *e2) { - lua_Number v1, v2, r; - if (!isnumeral(e1) || !isnumeral(e2)) return 0; - v1 = e1->u.nval; - v2 = e2->u.nval; - switch (op) { - case OP_ADD: r = luai_numadd(v1, v2); break; - case OP_SUB: r = luai_numsub(v1, v2); break; - case OP_MUL: r = luai_nummul(v1, v2); break; - case OP_DIV: - if (v2 == 0) return 0; /* do not attempt to divide by 0 */ - r = luai_numdiv(v1, v2); break; - case OP_MOD: - if (v2 == 0) return 0; /* do not attempt to divide by 0 */ - r = luai_nummod(v1, v2); break; - case OP_POW: r = luai_numpow(v1, v2); break; - case OP_UNM: r = luai_numunm(v1); break; - case OP_LEN: return 0; /* no constant folding for 'len' */ - default: lua_assert(0); r = 0; break; - } - if (luai_numisnan(r)) return 0; /* do not attempt to produce NaN */ - e1->u.nval = r; - return 1; -} - - -static void codearith (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) { - if (constfolding(op, e1, e2)) - return; - else { - int o2 = (op != OP_UNM && op != OP_LEN) ? luaK_exp2RK(fs, e2) : 0; - int o1 = luaK_exp2RK(fs, e1); - if (o1 > o2) { - freeexp(fs, e1); - freeexp(fs, e2); - } - else { - freeexp(fs, e2); - freeexp(fs, e1); - } - e1->u.s.info = luaK_codeABC(fs, op, 0, o1, o2); - e1->k = VRELOCABLE; - } -} - - -static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1, - expdesc *e2) { - int o1 = luaK_exp2RK(fs, e1); - int o2 = luaK_exp2RK(fs, e2); - freeexp(fs, e2); - freeexp(fs, e1); - if (cond == 0 && op != OP_EQ) { - int temp; /* exchange args to replace by `<' or `<=' */ - temp = o1; o1 = o2; o2 = temp; /* o1 <==> o2 */ - cond = 1; - } - e1->u.s.info = condjump(fs, op, cond, o1, o2); - e1->k = VJMP; -} - - -void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e) { - expdesc e2; - e2.t = e2.f = NO_JUMP; e2.k = VKNUM; e2.u.nval = 0; - switch (op) { - case OPR_MINUS: { - if (!isnumeral(e)) - luaK_exp2anyreg(fs, e); /* cannot operate on non-numeric constants */ - codearith(fs, OP_UNM, e, &e2); - break; - } - case OPR_NOT: codenot(fs, e); break; - case OPR_LEN: { - luaK_exp2anyreg(fs, e); /* cannot operate on constants */ - codearith(fs, OP_LEN, e, &e2); - break; - } - default: lua_assert(0); - } -} - - -void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { - switch (op) { - case OPR_AND: { - luaK_goiftrue(fs, v); - break; - } - case OPR_OR: { - luaK_goiffalse(fs, v); - break; - } - case OPR_CONCAT: { - luaK_exp2nextreg(fs, v); /* operand must be on the `stack' */ - break; - } - case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: - case OPR_MOD: case OPR_POW: { - if (!isnumeral(v)) luaK_exp2RK(fs, v); - break; - } - default: { - luaK_exp2RK(fs, v); - break; - } - } -} - - -void luaK_posfix (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2) { - switch (op) { - case OPR_AND: { - lua_assert(e1->t == NO_JUMP); /* list must be closed */ - luaK_dischargevars(fs, e2); - luaK_concat(fs, &e2->f, e1->f); - *e1 = *e2; - break; - } - case OPR_OR: { - lua_assert(e1->f == NO_JUMP); /* list must be closed */ - luaK_dischargevars(fs, e2); - luaK_concat(fs, &e2->t, e1->t); - *e1 = *e2; - break; - } - case OPR_CONCAT: { - luaK_exp2val(fs, e2); - if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) { - lua_assert(e1->u.s.info == GETARG_B(getcode(fs, e2))-1); - freeexp(fs, e1); - SETARG_B(getcode(fs, e2), e1->u.s.info); - e1->k = VRELOCABLE; e1->u.s.info = e2->u.s.info; - } - else { - luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */ - codearith(fs, OP_CONCAT, e1, e2); - } - break; - } - case OPR_ADD: codearith(fs, OP_ADD, e1, e2); break; - case OPR_SUB: codearith(fs, OP_SUB, e1, e2); break; - case OPR_MUL: codearith(fs, OP_MUL, e1, e2); break; - case OPR_DIV: codearith(fs, OP_DIV, e1, e2); break; - case OPR_MOD: codearith(fs, OP_MOD, e1, e2); break; - case OPR_POW: codearith(fs, OP_POW, e1, e2); break; - case OPR_EQ: codecomp(fs, OP_EQ, 1, e1, e2); break; - case OPR_NE: codecomp(fs, OP_EQ, 0, e1, e2); break; - case OPR_LT: codecomp(fs, OP_LT, 1, e1, e2); break; - case OPR_LE: codecomp(fs, OP_LE, 1, e1, e2); break; - case OPR_GT: codecomp(fs, OP_LT, 0, e1, e2); break; - case OPR_GE: codecomp(fs, OP_LE, 0, e1, e2); break; - default: lua_assert(0); - } -} - - -void luaK_fixline (FuncState *fs, int line) { - fs->f->lineinfo[fs->pc - 1] = line; -} - - -static int luaK_code (FuncState *fs, Instruction i, int line) { - Proto *f = fs->f; - dischargejpc(fs); /* `pc' will change */ - /* put new instruction in code array */ - luaM_growvector(fs->L, f->code, fs->pc, f->sizecode, Instruction, - MAX_INT, "code size overflow"); - f->code[fs->pc] = i; - /* save corresponding line information */ - luaM_growvector(fs->L, f->lineinfo, fs->pc, f->sizelineinfo, int, - MAX_INT, "code size overflow"); - f->lineinfo[fs->pc] = line; - return fs->pc++; -} - - -int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) { - lua_assert(getOpMode(o) == iABC); - lua_assert(getBMode(o) != OpArgN || b == 0); - lua_assert(getCMode(o) != OpArgN || c == 0); - return luaK_code(fs, CREATE_ABC(o, a, b, c), fs->ls->lastline); -} - - -int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) { - lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx); - lua_assert(getCMode(o) == OpArgN); - return luaK_code(fs, CREATE_ABx(o, a, bc), fs->ls->lastline); -} - - -void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) { - int c = (nelems - 1)/LFIELDS_PER_FLUSH + 1; - int b = (tostore == LUA_MULTRET) ? 0 : tostore; - lua_assert(tostore != 0); - if (c <= MAXARG_C) - luaK_codeABC(fs, OP_SETLIST, base, b, c); - else { - luaK_codeABC(fs, OP_SETLIST, base, b, 0); - luaK_code(fs, cast(Instruction, c), fs->ls->lastline); - } - fs->freereg = base + 1; /* free registers with list values */ -} - diff --git a/Utilities/lua-5.1.5/src/lcode.h b/Utilities/lua-5.1.5/src/lcode.h deleted file mode 100644 index b941c6072..000000000 --- a/Utilities/lua-5.1.5/src/lcode.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -** $Id: lcode.h,v 1.48.1.1 2007/12/27 13:02:25 roberto Exp $ -** Code generator for Lua -** See Copyright Notice in lua.h -*/ - -#ifndef lcode_h -#define lcode_h - -#include "llex.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lparser.h" - - -/* -** Marks the end of a patch list. It is an invalid value both as an absolute -** address, and as a list link (would link an element to itself). -*/ -#define NO_JUMP (-1) - - -/* -** grep "ORDER OPR" if you change these enums -*/ -typedef enum BinOpr { - OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW, - OPR_CONCAT, - OPR_NE, OPR_EQ, - OPR_LT, OPR_LE, OPR_GT, OPR_GE, - OPR_AND, OPR_OR, - OPR_NOBINOPR -} BinOpr; - - -typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr; - - -#define getcode(fs,e) ((fs)->f->code[(e)->u.s.info]) - -#define luaK_codeAsBx(fs,o,A,sBx) luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx) - -#define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET) - -LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx); -LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C); -LUAI_FUNC void luaK_fixline (FuncState *fs, int line); -LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n); -LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n); -LUAI_FUNC void luaK_checkstack (FuncState *fs, int n); -LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s); -LUAI_FUNC int luaK_numberK (FuncState *fs, lua_Number r); -LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e); -LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e); -LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e); -LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e); -LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e); -LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key); -LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k); -LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e); -LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e); -LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults); -LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e); -LUAI_FUNC int luaK_jump (FuncState *fs); -LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret); -LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target); -LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list); -LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2); -LUAI_FUNC int luaK_getlabel (FuncState *fs); -LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v); -LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v); -LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, expdesc *v2); -LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore); - - -#endif diff --git a/Utilities/lua-5.1.5/src/ldblib.c b/Utilities/lua-5.1.5/src/ldblib.c deleted file mode 100644 index 2027eda59..000000000 --- a/Utilities/lua-5.1.5/src/ldblib.c +++ /dev/null @@ -1,398 +0,0 @@ -/* -** $Id: ldblib.c,v 1.104.1.4 2009/08/04 18:50:18 roberto Exp $ -** Interface from Lua to its debug API -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include - -#define ldblib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - - -static int db_getregistry (lua_State *L) { - lua_pushvalue(L, LUA_REGISTRYINDEX); - return 1; -} - - -static int db_getmetatable (lua_State *L) { - luaL_checkany(L, 1); - if (!lua_getmetatable(L, 1)) { - lua_pushnil(L); /* no metatable */ - } - return 1; -} - - -static int db_setmetatable (lua_State *L) { - int t = lua_type(L, 2); - luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, - "nil or table expected"); - lua_settop(L, 2); - lua_pushboolean(L, lua_setmetatable(L, 1)); - return 1; -} - - -static int db_getfenv (lua_State *L) { - luaL_checkany(L, 1); - lua_getfenv(L, 1); - return 1; -} - - -static int db_setfenv (lua_State *L) { - luaL_checktype(L, 2, LUA_TTABLE); - lua_settop(L, 2); - if (lua_setfenv(L, 1) == 0) - luaL_error(L, LUA_QL("setfenv") - " cannot change environment of given object"); - return 1; -} - - -static void settabss (lua_State *L, const char *i, const char *v) { - lua_pushstring(L, v); - lua_setfield(L, -2, i); -} - - -static void settabsi (lua_State *L, const char *i, int v) { - lua_pushinteger(L, v); - lua_setfield(L, -2, i); -} - - -static lua_State *getthread (lua_State *L, int *arg) { - if (lua_isthread(L, 1)) { - *arg = 1; - return lua_tothread(L, 1); - } - else { - *arg = 0; - return L; - } -} - - -static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) { - if (L == L1) { - lua_pushvalue(L, -2); - lua_remove(L, -3); - } - else - lua_xmove(L1, L, 1); - lua_setfield(L, -2, fname); -} - - -static int db_getinfo (lua_State *L) { - lua_Debug ar; - int arg; - lua_State *L1 = getthread(L, &arg); - const char *options = luaL_optstring(L, arg+2, "flnSu"); - if (lua_isnumber(L, arg+1)) { - if (!lua_getstack(L1, (int)lua_tointeger(L, arg+1), &ar)) { - lua_pushnil(L); /* level out of range */ - return 1; - } - } - else if (lua_isfunction(L, arg+1)) { - lua_pushfstring(L, ">%s", options); - options = lua_tostring(L, -1); - lua_pushvalue(L, arg+1); - lua_xmove(L, L1, 1); - } - else - return luaL_argerror(L, arg+1, "function or level expected"); - if (!lua_getinfo(L1, options, &ar)) - return luaL_argerror(L, arg+2, "invalid option"); - lua_createtable(L, 0, 2); - if (strchr(options, 'S')) { - settabss(L, "source", ar.source); - settabss(L, "short_src", ar.short_src); - settabsi(L, "linedefined", ar.linedefined); - settabsi(L, "lastlinedefined", ar.lastlinedefined); - settabss(L, "what", ar.what); - } - if (strchr(options, 'l')) - settabsi(L, "currentline", ar.currentline); - if (strchr(options, 'u')) - settabsi(L, "nups", ar.nups); - if (strchr(options, 'n')) { - settabss(L, "name", ar.name); - settabss(L, "namewhat", ar.namewhat); - } - if (strchr(options, 'L')) - treatstackoption(L, L1, "activelines"); - if (strchr(options, 'f')) - treatstackoption(L, L1, "func"); - return 1; /* return table */ -} - - -static int db_getlocal (lua_State *L) { - int arg; - lua_State *L1 = getthread(L, &arg); - lua_Debug ar; - const char *name; - if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */ - return luaL_argerror(L, arg+1, "level out of range"); - name = lua_getlocal(L1, &ar, luaL_checkint(L, arg+2)); - if (name) { - lua_xmove(L1, L, 1); - lua_pushstring(L, name); - lua_pushvalue(L, -2); - return 2; - } - else { - lua_pushnil(L); - return 1; - } -} - - -static int db_setlocal (lua_State *L) { - int arg; - lua_State *L1 = getthread(L, &arg); - lua_Debug ar; - if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */ - return luaL_argerror(L, arg+1, "level out of range"); - luaL_checkany(L, arg+3); - lua_settop(L, arg+3); - lua_xmove(L, L1, 1); - lua_pushstring(L, lua_setlocal(L1, &ar, luaL_checkint(L, arg+2))); - return 1; -} - - -static int auxupvalue (lua_State *L, int get) { - const char *name; - int n = luaL_checkint(L, 2); - luaL_checktype(L, 1, LUA_TFUNCTION); - if (lua_iscfunction(L, 1)) return 0; /* cannot touch C upvalues from Lua */ - name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n); - if (name == NULL) return 0; - lua_pushstring(L, name); - lua_insert(L, -(get+1)); - return get + 1; -} - - -static int db_getupvalue (lua_State *L) { - return auxupvalue(L, 1); -} - - -static int db_setupvalue (lua_State *L) { - luaL_checkany(L, 3); - return auxupvalue(L, 0); -} - - - -static const char KEY_HOOK = 'h'; - - -static void hookf (lua_State *L, lua_Debug *ar) { - static const char *const hooknames[] = - {"call", "return", "line", "count", "tail return"}; - lua_pushlightuserdata(L, (void *)&KEY_HOOK); - lua_rawget(L, LUA_REGISTRYINDEX); - lua_pushlightuserdata(L, L); - lua_rawget(L, -2); - if (lua_isfunction(L, -1)) { - lua_pushstring(L, hooknames[(int)ar->event]); - if (ar->currentline >= 0) - lua_pushinteger(L, ar->currentline); - else lua_pushnil(L); - lua_assert(lua_getinfo(L, "lS", ar)); - lua_call(L, 2, 0); - } -} - - -static int makemask (const char *smask, int count) { - int mask = 0; - if (strchr(smask, 'c')) mask |= LUA_MASKCALL; - if (strchr(smask, 'r')) mask |= LUA_MASKRET; - if (strchr(smask, 'l')) mask |= LUA_MASKLINE; - if (count > 0) mask |= LUA_MASKCOUNT; - return mask; -} - - -static char *unmakemask (int mask, char *smask) { - int i = 0; - if (mask & LUA_MASKCALL) smask[i++] = 'c'; - if (mask & LUA_MASKRET) smask[i++] = 'r'; - if (mask & LUA_MASKLINE) smask[i++] = 'l'; - smask[i] = '\0'; - return smask; -} - - -static void gethooktable (lua_State *L) { - lua_pushlightuserdata(L, (void *)&KEY_HOOK); - lua_rawget(L, LUA_REGISTRYINDEX); - if (!lua_istable(L, -1)) { - lua_pop(L, 1); - lua_createtable(L, 0, 1); - lua_pushlightuserdata(L, (void *)&KEY_HOOK); - lua_pushvalue(L, -2); - lua_rawset(L, LUA_REGISTRYINDEX); - } -} - - -static int db_sethook (lua_State *L) { - int arg, mask, count; - lua_Hook func; - lua_State *L1 = getthread(L, &arg); - if (lua_isnoneornil(L, arg+1)) { - lua_settop(L, arg+1); - func = NULL; mask = 0; count = 0; /* turn off hooks */ - } - else { - const char *smask = luaL_checkstring(L, arg+2); - luaL_checktype(L, arg+1, LUA_TFUNCTION); - count = luaL_optint(L, arg+3, 0); - func = hookf; mask = makemask(smask, count); - } - gethooktable(L); - lua_pushlightuserdata(L, L1); - lua_pushvalue(L, arg+1); - lua_rawset(L, -3); /* set new hook */ - lua_pop(L, 1); /* remove hook table */ - lua_sethook(L1, func, mask, count); /* set hooks */ - return 0; -} - - -static int db_gethook (lua_State *L) { - int arg; - lua_State *L1 = getthread(L, &arg); - char buff[5]; - int mask = lua_gethookmask(L1); - lua_Hook hook = lua_gethook(L1); - if (hook != NULL && hook != hookf) /* external hook? */ - lua_pushliteral(L, "external hook"); - else { - gethooktable(L); - lua_pushlightuserdata(L, L1); - lua_rawget(L, -2); /* get hook */ - lua_remove(L, -2); /* remove hook table */ - } - lua_pushstring(L, unmakemask(mask, buff)); - lua_pushinteger(L, lua_gethookcount(L1)); - return 3; -} - - -static int db_debug (lua_State *L) { - for (;;) { - char buffer[250]; - fputs("lua_debug> ", stderr); - if (fgets(buffer, sizeof(buffer), stdin) == 0 || - strcmp(buffer, "cont\n") == 0) - return 0; - if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") || - lua_pcall(L, 0, 0, 0)) { - fputs(lua_tostring(L, -1), stderr); - fputs("\n", stderr); - } - lua_settop(L, 0); /* remove eventual returns */ - } -} - - -#define LEVELS1 12 /* size of the first part of the stack */ -#define LEVELS2 10 /* size of the second part of the stack */ - -static int db_errorfb (lua_State *L) { - int level; - int firstpart = 1; /* still before eventual `...' */ - int arg; - lua_State *L1 = getthread(L, &arg); - lua_Debug ar; - if (lua_isnumber(L, arg+2)) { - level = (int)lua_tointeger(L, arg+2); - lua_pop(L, 1); - } - else - level = (L == L1) ? 1 : 0; /* level 0 may be this own function */ - if (lua_gettop(L) == arg) - lua_pushliteral(L, ""); - else if (!lua_isstring(L, arg+1)) return 1; /* message is not a string */ - else lua_pushliteral(L, "\n"); - lua_pushliteral(L, "stack traceback:"); - while (lua_getstack(L1, level++, &ar)) { - if (level > LEVELS1 && firstpart) { - /* no more than `LEVELS2' more levels? */ - if (!lua_getstack(L1, level+LEVELS2, &ar)) - level--; /* keep going */ - else { - lua_pushliteral(L, "\n\t..."); /* too many levels */ - while (lua_getstack(L1, level+LEVELS2, &ar)) /* find last levels */ - level++; - } - firstpart = 0; - continue; - } - lua_pushliteral(L, "\n\t"); - lua_getinfo(L1, "Snl", &ar); - lua_pushfstring(L, "%s:", ar.short_src); - if (ar.currentline > 0) - lua_pushfstring(L, "%d:", ar.currentline); - if (*ar.namewhat != '\0') /* is there a name? */ - lua_pushfstring(L, " in function " LUA_QS, ar.name); - else { - if (*ar.what == 'm') /* main? */ - lua_pushfstring(L, " in main chunk"); - else if (*ar.what == 'C' || *ar.what == 't') - lua_pushliteral(L, " ?"); /* C function or tail call */ - else - lua_pushfstring(L, " in function <%s:%d>", - ar.short_src, ar.linedefined); - } - lua_concat(L, lua_gettop(L) - arg); - } - lua_concat(L, lua_gettop(L) - arg); - return 1; -} - - -static const luaL_Reg dblib[] = { - {"debug", db_debug}, - {"getfenv", db_getfenv}, - {"gethook", db_gethook}, - {"getinfo", db_getinfo}, - {"getlocal", db_getlocal}, - {"getregistry", db_getregistry}, - {"getmetatable", db_getmetatable}, - {"getupvalue", db_getupvalue}, - {"setfenv", db_setfenv}, - {"sethook", db_sethook}, - {"setlocal", db_setlocal}, - {"setmetatable", db_setmetatable}, - {"setupvalue", db_setupvalue}, - {"traceback", db_errorfb}, - {NULL, NULL} -}; - - -LUALIB_API int luaopen_debug (lua_State *L) { - luaL_register(L, LUA_DBLIBNAME, dblib); - return 1; -} - diff --git a/Utilities/lua-5.1.5/src/ldebug.c b/Utilities/lua-5.1.5/src/ldebug.c deleted file mode 100644 index 50ad3d380..000000000 --- a/Utilities/lua-5.1.5/src/ldebug.c +++ /dev/null @@ -1,638 +0,0 @@ -/* -** $Id: ldebug.c,v 2.29.1.6 2008/05/08 16:56:26 roberto Exp $ -** Debug Interface -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include - - -#define ldebug_c -#define LUA_CORE - -#include "lua.h" - -#include "lapi.h" -#include "lcode.h" -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" -#include "lvm.h" - - - -static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name); - - -static int currentpc (lua_State *L, CallInfo *ci) { - if (!isLua(ci)) return -1; /* function is not a Lua function? */ - if (ci == L->ci) - ci->savedpc = L->savedpc; - return pcRel(ci->savedpc, ci_func(ci)->l.p); -} - - -static int currentline (lua_State *L, CallInfo *ci) { - int pc = currentpc(L, ci); - if (pc < 0) - return -1; /* only active lua functions have current-line information */ - else - return getline(ci_func(ci)->l.p, pc); -} - - -/* -** this function can be called asynchronous (e.g. during a signal) -*/ -LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) { - if (func == NULL || mask == 0) { /* turn off hooks? */ - mask = 0; - func = NULL; - } - L->hook = func; - L->basehookcount = count; - resethookcount(L); - L->hookmask = cast_byte(mask); - return 1; -} - - -LUA_API lua_Hook lua_gethook (lua_State *L) { - return L->hook; -} - - -LUA_API int lua_gethookmask (lua_State *L) { - return L->hookmask; -} - - -LUA_API int lua_gethookcount (lua_State *L) { - return L->basehookcount; -} - - -LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) { - int status; - CallInfo *ci; - lua_lock(L); - for (ci = L->ci; level > 0 && ci > L->base_ci; ci--) { - level--; - if (f_isLua(ci)) /* Lua function? */ - level -= ci->tailcalls; /* skip lost tail calls */ - } - if (level == 0 && ci > L->base_ci) { /* level found? */ - status = 1; - ar->i_ci = cast_int(ci - L->base_ci); - } - else if (level < 0) { /* level is of a lost tail call? */ - status = 1; - ar->i_ci = 0; - } - else status = 0; /* no such level */ - lua_unlock(L); - return status; -} - - -static Proto *getluaproto (CallInfo *ci) { - return (isLua(ci) ? ci_func(ci)->l.p : NULL); -} - - -static const char *findlocal (lua_State *L, CallInfo *ci, int n) { - const char *name; - Proto *fp = getluaproto(ci); - if (fp && (name = luaF_getlocalname(fp, n, currentpc(L, ci))) != NULL) - return name; /* is a local variable in a Lua function */ - else { - StkId limit = (ci == L->ci) ? L->top : (ci+1)->func; - if (limit - ci->base >= n && n > 0) /* is 'n' inside 'ci' stack? */ - return "(*temporary)"; - else - return NULL; - } -} - - -LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { - CallInfo *ci = L->base_ci + ar->i_ci; - const char *name = findlocal(L, ci, n); - lua_lock(L); - if (name) - luaA_pushobject(L, ci->base + (n - 1)); - lua_unlock(L); - return name; -} - - -LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { - CallInfo *ci = L->base_ci + ar->i_ci; - const char *name = findlocal(L, ci, n); - lua_lock(L); - if (name) - setobjs2s(L, ci->base + (n - 1), L->top - 1); - L->top--; /* pop value */ - lua_unlock(L); - return name; -} - - -static void funcinfo (lua_Debug *ar, Closure *cl) { - if (cl->c.isC) { - ar->source = "=[C]"; - ar->linedefined = -1; - ar->lastlinedefined = -1; - ar->what = "C"; - } - else { - ar->source = getstr(cl->l.p->source); - ar->linedefined = cl->l.p->linedefined; - ar->lastlinedefined = cl->l.p->lastlinedefined; - ar->what = (ar->linedefined == 0) ? "main" : "Lua"; - } - luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE); -} - - -static void info_tailcall (lua_Debug *ar) { - ar->name = ar->namewhat = ""; - ar->what = "tail"; - ar->lastlinedefined = ar->linedefined = ar->currentline = -1; - ar->source = "=(tail call)"; - luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE); - ar->nups = 0; -} - - -static void collectvalidlines (lua_State *L, Closure *f) { - if (f == NULL || f->c.isC) { - setnilvalue(L->top); - } - else { - Table *t = luaH_new(L, 0, 0); - int *lineinfo = f->l.p->lineinfo; - int i; - for (i=0; il.p->sizelineinfo; i++) - setbvalue(luaH_setnum(L, t, lineinfo[i]), 1); - sethvalue(L, L->top, t); - } - incr_top(L); -} - - -static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, - Closure *f, CallInfo *ci) { - int status = 1; - if (f == NULL) { - info_tailcall(ar); - return status; - } - for (; *what; what++) { - switch (*what) { - case 'S': { - funcinfo(ar, f); - break; - } - case 'l': { - ar->currentline = (ci) ? currentline(L, ci) : -1; - break; - } - case 'u': { - ar->nups = f->c.nupvalues; - break; - } - case 'n': { - ar->namewhat = (ci) ? getfuncname(L, ci, &ar->name) : NULL; - if (ar->namewhat == NULL) { - ar->namewhat = ""; /* not found */ - ar->name = NULL; - } - break; - } - case 'L': - case 'f': /* handled by lua_getinfo */ - break; - default: status = 0; /* invalid option */ - } - } - return status; -} - - -LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { - int status; - Closure *f = NULL; - CallInfo *ci = NULL; - lua_lock(L); - if (*what == '>') { - StkId func = L->top - 1; - luai_apicheck(L, ttisfunction(func)); - what++; /* skip the '>' */ - f = clvalue(func); - L->top--; /* pop function */ - } - else if (ar->i_ci != 0) { /* no tail call? */ - ci = L->base_ci + ar->i_ci; - lua_assert(ttisfunction(ci->func)); - f = clvalue(ci->func); - } - status = auxgetinfo(L, what, ar, f, ci); - if (strchr(what, 'f')) { - if (f == NULL) setnilvalue(L->top); - else setclvalue(L, L->top, f); - incr_top(L); - } - if (strchr(what, 'L')) - collectvalidlines(L, f); - lua_unlock(L); - return status; -} - - -/* -** {====================================================== -** Symbolic Execution and code checker -** ======================================================= -*/ - -#define check(x) if (!(x)) return 0; - -#define checkjump(pt,pc) check(0 <= pc && pc < pt->sizecode) - -#define checkreg(pt,reg) check((reg) < (pt)->maxstacksize) - - - -static int precheck (const Proto *pt) { - check(pt->maxstacksize <= MAXSTACK); - check(pt->numparams+(pt->is_vararg & VARARG_HASARG) <= pt->maxstacksize); - check(!(pt->is_vararg & VARARG_NEEDSARG) || - (pt->is_vararg & VARARG_HASARG)); - check(pt->sizeupvalues <= pt->nups); - check(pt->sizelineinfo == pt->sizecode || pt->sizelineinfo == 0); - check(pt->sizecode > 0 && GET_OPCODE(pt->code[pt->sizecode-1]) == OP_RETURN); - return 1; -} - - -#define checkopenop(pt,pc) luaG_checkopenop((pt)->code[(pc)+1]) - -int luaG_checkopenop (Instruction i) { - switch (GET_OPCODE(i)) { - case OP_CALL: - case OP_TAILCALL: - case OP_RETURN: - case OP_SETLIST: { - check(GETARG_B(i) == 0); - return 1; - } - default: return 0; /* invalid instruction after an open call */ - } -} - - -static int checkArgMode (const Proto *pt, int r, enum OpArgMask mode) { - switch (mode) { - case OpArgN: check(r == 0); break; - case OpArgU: break; - case OpArgR: checkreg(pt, r); break; - case OpArgK: - check(ISK(r) ? INDEXK(r) < pt->sizek : r < pt->maxstacksize); - break; - } - return 1; -} - - -static Instruction symbexec (const Proto *pt, int lastpc, int reg) { - int pc; - int last; /* stores position of last instruction that changed `reg' */ - last = pt->sizecode-1; /* points to final return (a `neutral' instruction) */ - check(precheck(pt)); - for (pc = 0; pc < lastpc; pc++) { - Instruction i = pt->code[pc]; - OpCode op = GET_OPCODE(i); - int a = GETARG_A(i); - int b = 0; - int c = 0; - check(op < NUM_OPCODES); - checkreg(pt, a); - switch (getOpMode(op)) { - case iABC: { - b = GETARG_B(i); - c = GETARG_C(i); - check(checkArgMode(pt, b, getBMode(op))); - check(checkArgMode(pt, c, getCMode(op))); - break; - } - case iABx: { - b = GETARG_Bx(i); - if (getBMode(op) == OpArgK) check(b < pt->sizek); - break; - } - case iAsBx: { - b = GETARG_sBx(i); - if (getBMode(op) == OpArgR) { - int dest = pc+1+b; - check(0 <= dest && dest < pt->sizecode); - if (dest > 0) { - int j; - /* check that it does not jump to a setlist count; this - is tricky, because the count from a previous setlist may - have the same value of an invalid setlist; so, we must - go all the way back to the first of them (if any) */ - for (j = 0; j < dest; j++) { - Instruction d = pt->code[dest-1-j]; - if (!(GET_OPCODE(d) == OP_SETLIST && GETARG_C(d) == 0)) break; - } - /* if 'j' is even, previous value is not a setlist (even if - it looks like one) */ - check((j&1) == 0); - } - } - break; - } - } - if (testAMode(op)) { - if (a == reg) last = pc; /* change register `a' */ - } - if (testTMode(op)) { - check(pc+2 < pt->sizecode); /* check skip */ - check(GET_OPCODE(pt->code[pc+1]) == OP_JMP); - } - switch (op) { - case OP_LOADBOOL: { - if (c == 1) { /* does it jump? */ - check(pc+2 < pt->sizecode); /* check its jump */ - check(GET_OPCODE(pt->code[pc+1]) != OP_SETLIST || - GETARG_C(pt->code[pc+1]) != 0); - } - break; - } - case OP_LOADNIL: { - if (a <= reg && reg <= b) - last = pc; /* set registers from `a' to `b' */ - break; - } - case OP_GETUPVAL: - case OP_SETUPVAL: { - check(b < pt->nups); - break; - } - case OP_GETGLOBAL: - case OP_SETGLOBAL: { - check(ttisstring(&pt->k[b])); - break; - } - case OP_SELF: { - checkreg(pt, a+1); - if (reg == a+1) last = pc; - break; - } - case OP_CONCAT: { - check(b < c); /* at least two operands */ - break; - } - case OP_TFORLOOP: { - check(c >= 1); /* at least one result (control variable) */ - checkreg(pt, a+2+c); /* space for results */ - if (reg >= a+2) last = pc; /* affect all regs above its base */ - break; - } - case OP_FORLOOP: - case OP_FORPREP: - checkreg(pt, a+3); - /* go through */ - case OP_JMP: { - int dest = pc+1+b; - /* not full check and jump is forward and do not skip `lastpc'? */ - if (reg != NO_REG && pc < dest && dest <= lastpc) - pc += b; /* do the jump */ - break; - } - case OP_CALL: - case OP_TAILCALL: { - if (b != 0) { - checkreg(pt, a+b-1); - } - c--; /* c = num. returns */ - if (c == LUA_MULTRET) { - check(checkopenop(pt, pc)); - } - else if (c != 0) - checkreg(pt, a+c-1); - if (reg >= a) last = pc; /* affect all registers above base */ - break; - } - case OP_RETURN: { - b--; /* b = num. returns */ - if (b > 0) checkreg(pt, a+b-1); - break; - } - case OP_SETLIST: { - if (b > 0) checkreg(pt, a + b); - if (c == 0) { - pc++; - check(pc < pt->sizecode - 1); - } - break; - } - case OP_CLOSURE: { - int nup, j; - check(b < pt->sizep); - nup = pt->p[b]->nups; - check(pc + nup < pt->sizecode); - for (j = 1; j <= nup; j++) { - OpCode op1 = GET_OPCODE(pt->code[pc + j]); - check(op1 == OP_GETUPVAL || op1 == OP_MOVE); - } - if (reg != NO_REG) /* tracing? */ - pc += nup; /* do not 'execute' these pseudo-instructions */ - break; - } - case OP_VARARG: { - check((pt->is_vararg & VARARG_ISVARARG) && - !(pt->is_vararg & VARARG_NEEDSARG)); - b--; - if (b == LUA_MULTRET) check(checkopenop(pt, pc)); - checkreg(pt, a+b-1); - break; - } - default: break; - } - } - return pt->code[last]; -} - -#undef check -#undef checkjump -#undef checkreg - -/* }====================================================== */ - - -int luaG_checkcode (const Proto *pt) { - return (symbexec(pt, pt->sizecode, NO_REG) != 0); -} - - -static const char *kname (Proto *p, int c) { - if (ISK(c) && ttisstring(&p->k[INDEXK(c)])) - return svalue(&p->k[INDEXK(c)]); - else - return "?"; -} - - -static const char *getobjname (lua_State *L, CallInfo *ci, int stackpos, - const char **name) { - if (isLua(ci)) { /* a Lua function? */ - Proto *p = ci_func(ci)->l.p; - int pc = currentpc(L, ci); - Instruction i; - *name = luaF_getlocalname(p, stackpos+1, pc); - if (*name) /* is a local? */ - return "local"; - i = symbexec(p, pc, stackpos); /* try symbolic execution */ - lua_assert(pc != -1); - switch (GET_OPCODE(i)) { - case OP_GETGLOBAL: { - int g = GETARG_Bx(i); /* global index */ - lua_assert(ttisstring(&p->k[g])); - *name = svalue(&p->k[g]); - return "global"; - } - case OP_MOVE: { - int a = GETARG_A(i); - int b = GETARG_B(i); /* move from `b' to `a' */ - if (b < a) - return getobjname(L, ci, b, name); /* get name for `b' */ - break; - } - case OP_GETTABLE: { - int k = GETARG_C(i); /* key index */ - *name = kname(p, k); - return "field"; - } - case OP_GETUPVAL: { - int u = GETARG_B(i); /* upvalue index */ - *name = p->upvalues ? getstr(p->upvalues[u]) : "?"; - return "upvalue"; - } - case OP_SELF: { - int k = GETARG_C(i); /* key index */ - *name = kname(p, k); - return "method"; - } - default: break; - } - } - return NULL; /* no useful name found */ -} - - -static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { - Instruction i; - if ((isLua(ci) && ci->tailcalls > 0) || !isLua(ci - 1)) - return NULL; /* calling function is not Lua (or is unknown) */ - ci--; /* calling function */ - i = ci_func(ci)->l.p->code[currentpc(L, ci)]; - if (GET_OPCODE(i) == OP_CALL || GET_OPCODE(i) == OP_TAILCALL || - GET_OPCODE(i) == OP_TFORLOOP) - return getobjname(L, ci, GETARG_A(i), name); - else - return NULL; /* no useful name can be found */ -} - - -/* only ANSI way to check whether a pointer points to an array */ -static int isinstack (CallInfo *ci, const TValue *o) { - StkId p; - for (p = ci->base; p < ci->top; p++) - if (o == p) return 1; - return 0; -} - - -void luaG_typeerror (lua_State *L, const TValue *o, const char *op) { - const char *name = NULL; - const char *t = luaT_typenames[ttype(o)]; - const char *kind = (isinstack(L->ci, o)) ? - getobjname(L, L->ci, cast_int(o - L->base), &name) : - NULL; - if (kind) - luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)", - op, kind, name, t); - else - luaG_runerror(L, "attempt to %s a %s value", op, t); -} - - -void luaG_concaterror (lua_State *L, StkId p1, StkId p2) { - if (ttisstring(p1) || ttisnumber(p1)) p1 = p2; - lua_assert(!ttisstring(p1) && !ttisnumber(p1)); - luaG_typeerror(L, p1, "concatenate"); -} - - -void luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) { - TValue temp; - if (luaV_tonumber(p1, &temp) == NULL) - p2 = p1; /* first operand is wrong */ - luaG_typeerror(L, p2, "perform arithmetic on"); -} - - -int luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) { - const char *t1 = luaT_typenames[ttype(p1)]; - const char *t2 = luaT_typenames[ttype(p2)]; - if (t1[2] == t2[2]) - luaG_runerror(L, "attempt to compare two %s values", t1); - else - luaG_runerror(L, "attempt to compare %s with %s", t1, t2); - return 0; -} - - -static void addinfo (lua_State *L, const char *msg) { - CallInfo *ci = L->ci; - if (isLua(ci)) { /* is Lua code? */ - char buff[LUA_IDSIZE]; /* add file:line information */ - int line = currentline(L, ci); - luaO_chunkid(buff, getstr(getluaproto(ci)->source), LUA_IDSIZE); - luaO_pushfstring(L, "%s:%d: %s", buff, line, msg); - } -} - - -void luaG_errormsg (lua_State *L) { - if (L->errfunc != 0) { /* is there an error handling function? */ - StkId errfunc = restorestack(L, L->errfunc); - if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR); - setobjs2s(L, L->top, L->top - 1); /* move argument */ - setobjs2s(L, L->top - 1, errfunc); /* push function */ - incr_top(L); - luaD_call(L, L->top - 2, 1); /* call it */ - } - luaD_throw(L, LUA_ERRRUN); -} - - -void luaG_runerror (lua_State *L, const char *fmt, ...) { - va_list argp; - va_start(argp, fmt); - addinfo(L, luaO_pushvfstring(L, fmt, argp)); - va_end(argp); - luaG_errormsg(L); -} - diff --git a/Utilities/lua-5.1.5/src/ldebug.h b/Utilities/lua-5.1.5/src/ldebug.h deleted file mode 100644 index ba28a9724..000000000 --- a/Utilities/lua-5.1.5/src/ldebug.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -** $Id: ldebug.h,v 2.3.1.1 2007/12/27 13:02:25 roberto Exp $ -** Auxiliary functions from Debug Interface module -** See Copyright Notice in lua.h -*/ - -#ifndef ldebug_h -#define ldebug_h - - -#include "lstate.h" - - -#define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1) - -#define getline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : 0) - -#define resethookcount(L) (L->hookcount = L->basehookcount) - - -LUAI_FUNC void luaG_typeerror (lua_State *L, const TValue *o, - const char *opname); -LUAI_FUNC void luaG_concaterror (lua_State *L, StkId p1, StkId p2); -LUAI_FUNC void luaG_aritherror (lua_State *L, const TValue *p1, - const TValue *p2); -LUAI_FUNC int luaG_ordererror (lua_State *L, const TValue *p1, - const TValue *p2); -LUAI_FUNC void luaG_runerror (lua_State *L, const char *fmt, ...); -LUAI_FUNC void luaG_errormsg (lua_State *L); -LUAI_FUNC int luaG_checkcode (const Proto *pt); -LUAI_FUNC int luaG_checkopenop (Instruction i); - -#endif diff --git a/Utilities/lua-5.1.5/src/ldo.c b/Utilities/lua-5.1.5/src/ldo.c deleted file mode 100644 index d1bf786cb..000000000 --- a/Utilities/lua-5.1.5/src/ldo.c +++ /dev/null @@ -1,519 +0,0 @@ -/* -** $Id: ldo.c,v 2.38.1.4 2012/01/18 02:27:10 roberto Exp $ -** Stack and Call structure of Lua -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include - -#define ldo_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lgc.h" -#include "lmem.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lparser.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" -#include "lundump.h" -#include "lvm.h" -#include "lzio.h" - - - - -/* -** {====================================================== -** Error-recovery functions -** ======================================================= -*/ - - -/* chain list of long jump buffers */ -struct lua_longjmp { - struct lua_longjmp *previous; - luai_jmpbuf b; - volatile int status; /* error code */ -}; - - -void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) { - switch (errcode) { - case LUA_ERRMEM: { - setsvalue2s(L, oldtop, luaS_newliteral(L, MEMERRMSG)); - break; - } - case LUA_ERRERR: { - setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling")); - break; - } - case LUA_ERRSYNTAX: - case LUA_ERRRUN: { - setobjs2s(L, oldtop, L->top - 1); /* error message on current top */ - break; - } - } - L->top = oldtop + 1; -} - - -static void restore_stack_limit (lua_State *L) { - lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1); - if (L->size_ci > LUAI_MAXCALLS) { /* there was an overflow? */ - int inuse = cast_int(L->ci - L->base_ci); - if (inuse + 1 < LUAI_MAXCALLS) /* can `undo' overflow? */ - luaD_reallocCI(L, LUAI_MAXCALLS); - } -} - - -static void resetstack (lua_State *L, int status) { - L->ci = L->base_ci; - L->base = L->ci->base; - luaF_close(L, L->base); /* close eventual pending closures */ - luaD_seterrorobj(L, status, L->base); - L->nCcalls = L->baseCcalls; - L->allowhook = 1; - restore_stack_limit(L); - L->errfunc = 0; - L->errorJmp = NULL; -} - - -void luaD_throw (lua_State *L, int errcode) { - if (L->errorJmp) { - L->errorJmp->status = errcode; - LUAI_THROW(L, L->errorJmp); - } - else { - L->status = cast_byte(errcode); - if (G(L)->panic) { - resetstack(L, errcode); - lua_unlock(L); - G(L)->panic(L); - } - exit(EXIT_FAILURE); - } -} - - -int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { - struct lua_longjmp lj; - lj.status = 0; - lj.previous = L->errorJmp; /* chain new error handler */ - L->errorJmp = &lj; - LUAI_TRY(L, &lj, - (*f)(L, ud); - ); - L->errorJmp = lj.previous; /* restore old error handler */ - return lj.status; -} - -/* }====================================================== */ - - -static void correctstack (lua_State *L, TValue *oldstack) { - CallInfo *ci; - GCObject *up; - L->top = (L->top - oldstack) + L->stack; - for (up = L->openupval; up != NULL; up = up->gch.next) - gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack; - for (ci = L->base_ci; ci <= L->ci; ci++) { - ci->top = (ci->top - oldstack) + L->stack; - ci->base = (ci->base - oldstack) + L->stack; - ci->func = (ci->func - oldstack) + L->stack; - } - L->base = (L->base - oldstack) + L->stack; -} - - -void luaD_reallocstack (lua_State *L, int newsize) { - TValue *oldstack = L->stack; - int realsize = newsize + 1 + EXTRA_STACK; - lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1); - luaM_reallocvector(L, L->stack, L->stacksize, realsize, TValue); - L->stacksize = realsize; - L->stack_last = L->stack+newsize; - correctstack(L, oldstack); -} - - -void luaD_reallocCI (lua_State *L, int newsize) { - CallInfo *oldci = L->base_ci; - luaM_reallocvector(L, L->base_ci, L->size_ci, newsize, CallInfo); - L->size_ci = newsize; - L->ci = (L->ci - oldci) + L->base_ci; - L->end_ci = L->base_ci + L->size_ci - 1; -} - - -void luaD_growstack (lua_State *L, int n) { - if (n <= L->stacksize) /* double size is enough? */ - luaD_reallocstack(L, 2*L->stacksize); - else - luaD_reallocstack(L, L->stacksize + n); -} - - -static CallInfo *growCI (lua_State *L) { - if (L->size_ci > LUAI_MAXCALLS) /* overflow while handling overflow? */ - luaD_throw(L, LUA_ERRERR); - else { - luaD_reallocCI(L, 2*L->size_ci); - if (L->size_ci > LUAI_MAXCALLS) - luaG_runerror(L, "stack overflow"); - } - return ++L->ci; -} - - -void luaD_callhook (lua_State *L, int event, int line) { - lua_Hook hook = L->hook; - if (hook && L->allowhook) { - ptrdiff_t top = savestack(L, L->top); - ptrdiff_t ci_top = savestack(L, L->ci->top); - lua_Debug ar; - ar.event = event; - ar.currentline = line; - if (event == LUA_HOOKTAILRET) - ar.i_ci = 0; /* tail call; no debug information about it */ - else - ar.i_ci = cast_int(L->ci - L->base_ci); - luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ - L->ci->top = L->top + LUA_MINSTACK; - lua_assert(L->ci->top <= L->stack_last); - L->allowhook = 0; /* cannot call hooks inside a hook */ - lua_unlock(L); - (*hook)(L, &ar); - lua_lock(L); - lua_assert(!L->allowhook); - L->allowhook = 1; - L->ci->top = restorestack(L, ci_top); - L->top = restorestack(L, top); - } -} - - -static StkId adjust_varargs (lua_State *L, Proto *p, int actual) { - int i; - int nfixargs = p->numparams; - Table *htab = NULL; - StkId base, fixed; - for (; actual < nfixargs; ++actual) - setnilvalue(L->top++); -#if defined(LUA_COMPAT_VARARG) - if (p->is_vararg & VARARG_NEEDSARG) { /* compat. with old-style vararg? */ - int nvar = actual - nfixargs; /* number of extra arguments */ - lua_assert(p->is_vararg & VARARG_HASARG); - luaC_checkGC(L); - luaD_checkstack(L, p->maxstacksize); - htab = luaH_new(L, nvar, 1); /* create `arg' table */ - for (i=0; itop - nvar + i); - /* store counter in field `n' */ - setnvalue(luaH_setstr(L, htab, luaS_newliteral(L, "n")), cast_num(nvar)); - } -#endif - /* move fixed parameters to final position */ - fixed = L->top - actual; /* first fixed argument */ - base = L->top; /* final position of first argument */ - for (i=0; itop++, fixed+i); - setnilvalue(fixed+i); - } - /* add `arg' parameter */ - if (htab) { - sethvalue(L, L->top++, htab); - lua_assert(iswhite(obj2gco(htab))); - } - return base; -} - - -static StkId tryfuncTM (lua_State *L, StkId func) { - const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL); - StkId p; - ptrdiff_t funcr = savestack(L, func); - if (!ttisfunction(tm)) - luaG_typeerror(L, func, "call"); - /* Open a hole inside the stack at `func' */ - for (p = L->top; p > func; p--) setobjs2s(L, p, p-1); - incr_top(L); - func = restorestack(L, funcr); /* previous call may change stack */ - setobj2s(L, func, tm); /* tag method is the new function to be called */ - return func; -} - - - -#define inc_ci(L) \ - ((L->ci == L->end_ci) ? growCI(L) : \ - (condhardstacktests(luaD_reallocCI(L, L->size_ci)), ++L->ci)) - - -int luaD_precall (lua_State *L, StkId func, int nresults) { - LClosure *cl; - ptrdiff_t funcr; - if (!ttisfunction(func)) /* `func' is not a function? */ - func = tryfuncTM(L, func); /* check the `function' tag method */ - funcr = savestack(L, func); - cl = &clvalue(func)->l; - L->ci->savedpc = L->savedpc; - if (!cl->isC) { /* Lua function? prepare its call */ - CallInfo *ci; - StkId st, base; - Proto *p = cl->p; - luaD_checkstack(L, p->maxstacksize); - func = restorestack(L, funcr); - if (!p->is_vararg) { /* no varargs? */ - base = func + 1; - if (L->top > base + p->numparams) - L->top = base + p->numparams; - } - else { /* vararg function */ - int nargs = cast_int(L->top - func) - 1; - base = adjust_varargs(L, p, nargs); - func = restorestack(L, funcr); /* previous call may change the stack */ - } - ci = inc_ci(L); /* now `enter' new function */ - ci->func = func; - L->base = ci->base = base; - ci->top = L->base + p->maxstacksize; - lua_assert(ci->top <= L->stack_last); - L->savedpc = p->code; /* starting point */ - ci->tailcalls = 0; - ci->nresults = nresults; - for (st = L->top; st < ci->top; st++) - setnilvalue(st); - L->top = ci->top; - if (L->hookmask & LUA_MASKCALL) { - L->savedpc++; /* hooks assume 'pc' is already incremented */ - luaD_callhook(L, LUA_HOOKCALL, -1); - L->savedpc--; /* correct 'pc' */ - } - return PCRLUA; - } - else { /* if is a C function, call it */ - CallInfo *ci; - int n; - luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ - ci = inc_ci(L); /* now `enter' new function */ - ci->func = restorestack(L, funcr); - L->base = ci->base = ci->func + 1; - ci->top = L->top + LUA_MINSTACK; - lua_assert(ci->top <= L->stack_last); - ci->nresults = nresults; - if (L->hookmask & LUA_MASKCALL) - luaD_callhook(L, LUA_HOOKCALL, -1); - lua_unlock(L); - n = (*curr_func(L)->c.f)(L); /* do the actual call */ - lua_lock(L); - if (n < 0) /* yielding? */ - return PCRYIELD; - else { - luaD_poscall(L, L->top - n); - return PCRC; - } - } -} - - -static StkId callrethooks (lua_State *L, StkId firstResult) { - ptrdiff_t fr = savestack(L, firstResult); /* next call may change stack */ - luaD_callhook(L, LUA_HOOKRET, -1); - if (f_isLua(L->ci)) { /* Lua function? */ - while ((L->hookmask & LUA_MASKRET) && L->ci->tailcalls--) /* tail calls */ - luaD_callhook(L, LUA_HOOKTAILRET, -1); - } - return restorestack(L, fr); -} - - -int luaD_poscall (lua_State *L, StkId firstResult) { - StkId res; - int wanted, i; - CallInfo *ci; - if (L->hookmask & LUA_MASKRET) - firstResult = callrethooks(L, firstResult); - ci = L->ci--; - res = ci->func; /* res == final position of 1st result */ - wanted = ci->nresults; - L->base = (ci - 1)->base; /* restore base */ - L->savedpc = (ci - 1)->savedpc; /* restore savedpc */ - /* move results to correct place */ - for (i = wanted; i != 0 && firstResult < L->top; i--) - setobjs2s(L, res++, firstResult++); - while (i-- > 0) - setnilvalue(res++); - L->top = res; - return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */ -} - - -/* -** Call a function (C or Lua). The function to be called is at *func. -** The arguments are on the stack, right after the function. -** When returns, all the results are on the stack, starting at the original -** function position. -*/ -void luaD_call (lua_State *L, StkId func, int nResults) { - if (++L->nCcalls >= LUAI_MAXCCALLS) { - if (L->nCcalls == LUAI_MAXCCALLS) - luaG_runerror(L, "C stack overflow"); - else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3))) - luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ - } - if (luaD_precall(L, func, nResults) == PCRLUA) /* is a Lua function? */ - luaV_execute(L, 1); /* call it */ - L->nCcalls--; - luaC_checkGC(L); -} - - -static void resume (lua_State *L, void *ud) { - StkId firstArg = cast(StkId, ud); - CallInfo *ci = L->ci; - if (L->status == 0) { /* start coroutine? */ - lua_assert(ci == L->base_ci && firstArg > L->base); - if (luaD_precall(L, firstArg - 1, LUA_MULTRET) != PCRLUA) - return; - } - else { /* resuming from previous yield */ - lua_assert(L->status == LUA_YIELD); - L->status = 0; - if (!f_isLua(ci)) { /* `common' yield? */ - /* finish interrupted execution of `OP_CALL' */ - lua_assert(GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_CALL || - GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_TAILCALL); - if (luaD_poscall(L, firstArg)) /* complete it... */ - L->top = L->ci->top; /* and correct top if not multiple results */ - } - else /* yielded inside a hook: just continue its execution */ - L->base = L->ci->base; - } - luaV_execute(L, cast_int(L->ci - L->base_ci)); -} - - -static int resume_error (lua_State *L, const char *msg) { - L->top = L->ci->base; - setsvalue2s(L, L->top, luaS_new(L, msg)); - incr_top(L); - lua_unlock(L); - return LUA_ERRRUN; -} - - -LUA_API int lua_resume (lua_State *L, int nargs) { - int status; - lua_lock(L); - if (L->status != LUA_YIELD && (L->status != 0 || L->ci != L->base_ci)) - return resume_error(L, "cannot resume non-suspended coroutine"); - if (L->nCcalls >= LUAI_MAXCCALLS) - return resume_error(L, "C stack overflow"); - luai_userstateresume(L, nargs); - lua_assert(L->errfunc == 0); - L->baseCcalls = ++L->nCcalls; - status = luaD_rawrunprotected(L, resume, L->top - nargs); - if (status != 0) { /* error? */ - L->status = cast_byte(status); /* mark thread as `dead' */ - luaD_seterrorobj(L, status, L->top); - L->ci->top = L->top; - } - else { - lua_assert(L->nCcalls == L->baseCcalls); - status = L->status; - } - --L->nCcalls; - lua_unlock(L); - return status; -} - - -LUA_API int lua_yield (lua_State *L, int nresults) { - luai_userstateyield(L, nresults); - lua_lock(L); - if (L->nCcalls > L->baseCcalls) - luaG_runerror(L, "attempt to yield across metamethod/C-call boundary"); - L->base = L->top - nresults; /* protect stack slots below */ - L->status = LUA_YIELD; - lua_unlock(L); - return -1; -} - - -int luaD_pcall (lua_State *L, Pfunc func, void *u, - ptrdiff_t old_top, ptrdiff_t ef) { - int status; - unsigned short oldnCcalls = L->nCcalls; - ptrdiff_t old_ci = saveci(L, L->ci); - lu_byte old_allowhooks = L->allowhook; - ptrdiff_t old_errfunc = L->errfunc; - L->errfunc = ef; - status = luaD_rawrunprotected(L, func, u); - if (status != 0) { /* an error occurred? */ - StkId oldtop = restorestack(L, old_top); - luaF_close(L, oldtop); /* close eventual pending closures */ - luaD_seterrorobj(L, status, oldtop); - L->nCcalls = oldnCcalls; - L->ci = restoreci(L, old_ci); - L->base = L->ci->base; - L->savedpc = L->ci->savedpc; - L->allowhook = old_allowhooks; - restore_stack_limit(L); - } - L->errfunc = old_errfunc; - return status; -} - - - -/* -** Execute a protected parser. -*/ -struct SParser { /* data to `f_parser' */ - ZIO *z; - Mbuffer buff; /* buffer to be used by the scanner */ - const char *name; -}; - -static void f_parser (lua_State *L, void *ud) { - int i; - Proto *tf; - Closure *cl; - struct SParser *p = cast(struct SParser *, ud); - int c = luaZ_lookahead(p->z); - luaC_checkGC(L); - tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z, - &p->buff, p->name); - cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L))); - cl->l.p = tf; - for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */ - cl->l.upvals[i] = luaF_newupval(L); - setclvalue(L, L->top, cl); - incr_top(L); -} - - -int luaD_protectedparser (lua_State *L, ZIO *z, const char *name) { - struct SParser p; - int status; - p.z = z; p.name = name; - luaZ_initbuffer(L, &p.buff); - status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc); - luaZ_freebuffer(L, &p.buff); - return status; -} - - diff --git a/Utilities/lua-5.1.5/src/ldo.h b/Utilities/lua-5.1.5/src/ldo.h deleted file mode 100644 index 98fddac59..000000000 --- a/Utilities/lua-5.1.5/src/ldo.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -** $Id: ldo.h,v 2.7.1.1 2007/12/27 13:02:25 roberto Exp $ -** Stack and Call structure of Lua -** See Copyright Notice in lua.h -*/ - -#ifndef ldo_h -#define ldo_h - - -#include "lobject.h" -#include "lstate.h" -#include "lzio.h" - - -#define luaD_checkstack(L,n) \ - if ((char *)L->stack_last - (char *)L->top <= (n)*(int)sizeof(TValue)) \ - luaD_growstack(L, n); \ - else condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); - - -#define incr_top(L) {luaD_checkstack(L,1); L->top++;} - -#define savestack(L,p) ((char *)(p) - (char *)L->stack) -#define restorestack(L,n) ((TValue *)((char *)L->stack + (n))) - -#define saveci(L,p) ((char *)(p) - (char *)L->base_ci) -#define restoreci(L,n) ((CallInfo *)((char *)L->base_ci + (n))) - - -/* results from luaD_precall */ -#define PCRLUA 0 /* initiated a call to a Lua function */ -#define PCRC 1 /* did a call to a C function */ -#define PCRYIELD 2 /* C funtion yielded */ - - -/* type of protected functions, to be ran by `runprotected' */ -typedef void (*Pfunc) (lua_State *L, void *ud); - -LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name); -LUAI_FUNC void luaD_callhook (lua_State *L, int event, int line); -LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults); -LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults); -LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u, - ptrdiff_t oldtop, ptrdiff_t ef); -LUAI_FUNC int luaD_poscall (lua_State *L, StkId firstResult); -LUAI_FUNC void luaD_reallocCI (lua_State *L, int newsize); -LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize); -LUAI_FUNC void luaD_growstack (lua_State *L, int n); - -LUAI_FUNC void luaD_throw (lua_State *L, int errcode); -LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); - -LUAI_FUNC void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop); - -#endif - diff --git a/Utilities/lua-5.1.5/src/ldump.c b/Utilities/lua-5.1.5/src/ldump.c deleted file mode 100644 index c9d3d4870..000000000 --- a/Utilities/lua-5.1.5/src/ldump.c +++ /dev/null @@ -1,164 +0,0 @@ -/* -** $Id: ldump.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $ -** save precompiled Lua chunks -** See Copyright Notice in lua.h -*/ - -#include - -#define ldump_c -#define LUA_CORE - -#include "lua.h" - -#include "lobject.h" -#include "lstate.h" -#include "lundump.h" - -typedef struct { - lua_State* L; - lua_Writer writer; - void* data; - int strip; - int status; -} DumpState; - -#define DumpMem(b,n,size,D) DumpBlock(b,(n)*(size),D) -#define DumpVar(x,D) DumpMem(&x,1,sizeof(x),D) - -static void DumpBlock(const void* b, size_t size, DumpState* D) -{ - if (D->status==0) - { - lua_unlock(D->L); - D->status=(*D->writer)(D->L,b,size,D->data); - lua_lock(D->L); - } -} - -static void DumpChar(int y, DumpState* D) -{ - char x=(char)y; - DumpVar(x,D); -} - -static void DumpInt(int x, DumpState* D) -{ - DumpVar(x,D); -} - -static void DumpNumber(lua_Number x, DumpState* D) -{ - DumpVar(x,D); -} - -static void DumpVector(const void* b, int n, size_t size, DumpState* D) -{ - DumpInt(n,D); - DumpMem(b,n,size,D); -} - -static void DumpString(const TString* s, DumpState* D) -{ - if (s==NULL || getstr(s)==NULL) - { - size_t size=0; - DumpVar(size,D); - } - else - { - size_t size=s->tsv.len+1; /* include trailing '\0' */ - DumpVar(size,D); - DumpBlock(getstr(s),size,D); - } -} - -#define DumpCode(f,D) DumpVector(f->code,f->sizecode,sizeof(Instruction),D) - -static void DumpFunction(const Proto* f, const TString* p, DumpState* D); - -static void DumpConstants(const Proto* f, DumpState* D) -{ - int i,n=f->sizek; - DumpInt(n,D); - for (i=0; ik[i]; - DumpChar(ttype(o),D); - switch (ttype(o)) - { - case LUA_TNIL: - break; - case LUA_TBOOLEAN: - DumpChar(bvalue(o),D); - break; - case LUA_TNUMBER: - DumpNumber(nvalue(o),D); - break; - case LUA_TSTRING: - DumpString(rawtsvalue(o),D); - break; - default: - lua_assert(0); /* cannot happen */ - break; - } - } - n=f->sizep; - DumpInt(n,D); - for (i=0; ip[i],f->source,D); -} - -static void DumpDebug(const Proto* f, DumpState* D) -{ - int i,n; - n= (D->strip) ? 0 : f->sizelineinfo; - DumpVector(f->lineinfo,n,sizeof(int),D); - n= (D->strip) ? 0 : f->sizelocvars; - DumpInt(n,D); - for (i=0; ilocvars[i].varname,D); - DumpInt(f->locvars[i].startpc,D); - DumpInt(f->locvars[i].endpc,D); - } - n= (D->strip) ? 0 : f->sizeupvalues; - DumpInt(n,D); - for (i=0; iupvalues[i],D); -} - -static void DumpFunction(const Proto* f, const TString* p, DumpState* D) -{ - DumpString((f->source==p || D->strip) ? NULL : f->source,D); - DumpInt(f->linedefined,D); - DumpInt(f->lastlinedefined,D); - DumpChar(f->nups,D); - DumpChar(f->numparams,D); - DumpChar(f->is_vararg,D); - DumpChar(f->maxstacksize,D); - DumpCode(f,D); - DumpConstants(f,D); - DumpDebug(f,D); -} - -static void DumpHeader(DumpState* D) -{ - char h[LUAC_HEADERSIZE]; - luaU_header(h); - DumpBlock(h,LUAC_HEADERSIZE,D); -} - -/* -** dump Lua function as precompiled chunk -*/ -int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip) -{ - DumpState D; - D.L=L; - D.writer=w; - D.data=data; - D.strip=strip; - D.status=0; - DumpHeader(&D); - DumpFunction(f,NULL,&D); - return D.status; -} diff --git a/Utilities/lua-5.1.5/src/lfunc.c b/Utilities/lua-5.1.5/src/lfunc.c deleted file mode 100644 index 813e88f58..000000000 --- a/Utilities/lua-5.1.5/src/lfunc.c +++ /dev/null @@ -1,174 +0,0 @@ -/* -** $Id: lfunc.c,v 2.12.1.2 2007/12/28 14:58:43 roberto Exp $ -** Auxiliary functions to manipulate prototypes and closures -** See Copyright Notice in lua.h -*/ - - -#include - -#define lfunc_c -#define LUA_CORE - -#include "lua.h" - -#include "lfunc.h" -#include "lgc.h" -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" - - - -Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e) { - Closure *c = cast(Closure *, luaM_malloc(L, sizeCclosure(nelems))); - luaC_link(L, obj2gco(c), LUA_TFUNCTION); - c->c.isC = 1; - c->c.env = e; - c->c.nupvalues = cast_byte(nelems); - return c; -} - - -Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e) { - Closure *c = cast(Closure *, luaM_malloc(L, sizeLclosure(nelems))); - luaC_link(L, obj2gco(c), LUA_TFUNCTION); - c->l.isC = 0; - c->l.env = e; - c->l.nupvalues = cast_byte(nelems); - while (nelems--) c->l.upvals[nelems] = NULL; - return c; -} - - -UpVal *luaF_newupval (lua_State *L) { - UpVal *uv = luaM_new(L, UpVal); - luaC_link(L, obj2gco(uv), LUA_TUPVAL); - uv->v = &uv->u.value; - setnilvalue(uv->v); - return uv; -} - - -UpVal *luaF_findupval (lua_State *L, StkId level) { - global_State *g = G(L); - GCObject **pp = &L->openupval; - UpVal *p; - UpVal *uv; - while (*pp != NULL && (p = ngcotouv(*pp))->v >= level) { - lua_assert(p->v != &p->u.value); - if (p->v == level) { /* found a corresponding upvalue? */ - if (isdead(g, obj2gco(p))) /* is it dead? */ - changewhite(obj2gco(p)); /* ressurect it */ - return p; - } - pp = &p->next; - } - uv = luaM_new(L, UpVal); /* not found: create a new one */ - uv->tt = LUA_TUPVAL; - uv->marked = luaC_white(g); - uv->v = level; /* current value lives in the stack */ - uv->next = *pp; /* chain it in the proper position */ - *pp = obj2gco(uv); - uv->u.l.prev = &g->uvhead; /* double link it in `uvhead' list */ - uv->u.l.next = g->uvhead.u.l.next; - uv->u.l.next->u.l.prev = uv; - g->uvhead.u.l.next = uv; - lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); - return uv; -} - - -static void unlinkupval (UpVal *uv) { - lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); - uv->u.l.next->u.l.prev = uv->u.l.prev; /* remove from `uvhead' list */ - uv->u.l.prev->u.l.next = uv->u.l.next; -} - - -void luaF_freeupval (lua_State *L, UpVal *uv) { - if (uv->v != &uv->u.value) /* is it open? */ - unlinkupval(uv); /* remove from open list */ - luaM_free(L, uv); /* free upvalue */ -} - - -void luaF_close (lua_State *L, StkId level) { - UpVal *uv; - global_State *g = G(L); - while (L->openupval != NULL && (uv = ngcotouv(L->openupval))->v >= level) { - GCObject *o = obj2gco(uv); - lua_assert(!isblack(o) && uv->v != &uv->u.value); - L->openupval = uv->next; /* remove from `open' list */ - if (isdead(g, o)) - luaF_freeupval(L, uv); /* free upvalue */ - else { - unlinkupval(uv); - setobj(L, &uv->u.value, uv->v); - uv->v = &uv->u.value; /* now current value lives here */ - luaC_linkupval(L, uv); /* link upvalue into `gcroot' list */ - } - } -} - - -Proto *luaF_newproto (lua_State *L) { - Proto *f = luaM_new(L, Proto); - luaC_link(L, obj2gco(f), LUA_TPROTO); - f->k = NULL; - f->sizek = 0; - f->p = NULL; - f->sizep = 0; - f->code = NULL; - f->sizecode = 0; - f->sizelineinfo = 0; - f->sizeupvalues = 0; - f->nups = 0; - f->upvalues = NULL; - f->numparams = 0; - f->is_vararg = 0; - f->maxstacksize = 0; - f->lineinfo = NULL; - f->sizelocvars = 0; - f->locvars = NULL; - f->linedefined = 0; - f->lastlinedefined = 0; - f->source = NULL; - return f; -} - - -void luaF_freeproto (lua_State *L, Proto *f) { - luaM_freearray(L, f->code, f->sizecode, Instruction); - luaM_freearray(L, f->p, f->sizep, Proto *); - luaM_freearray(L, f->k, f->sizek, TValue); - luaM_freearray(L, f->lineinfo, f->sizelineinfo, int); - luaM_freearray(L, f->locvars, f->sizelocvars, struct LocVar); - luaM_freearray(L, f->upvalues, f->sizeupvalues, TString *); - luaM_free(L, f); -} - - -void luaF_freeclosure (lua_State *L, Closure *c) { - int size = (c->c.isC) ? sizeCclosure(c->c.nupvalues) : - sizeLclosure(c->l.nupvalues); - luaM_freemem(L, c, size); -} - - -/* -** Look for n-th local variable at line `line' in function `func'. -** Returns NULL if not found. -*/ -const char *luaF_getlocalname (const Proto *f, int local_number, int pc) { - int i; - for (i = 0; isizelocvars && f->locvars[i].startpc <= pc; i++) { - if (pc < f->locvars[i].endpc) { /* is variable active? */ - local_number--; - if (local_number == 0) - return getstr(f->locvars[i].varname); - } - } - return NULL; /* not found */ -} - diff --git a/Utilities/lua-5.1.5/src/lfunc.h b/Utilities/lua-5.1.5/src/lfunc.h deleted file mode 100644 index a68cf5151..000000000 --- a/Utilities/lua-5.1.5/src/lfunc.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -** $Id: lfunc.h,v 2.4.1.1 2007/12/27 13:02:25 roberto Exp $ -** Auxiliary functions to manipulate prototypes and closures -** See Copyright Notice in lua.h -*/ - -#ifndef lfunc_h -#define lfunc_h - - -#include "lobject.h" - - -#define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \ - cast(int, sizeof(TValue)*((n)-1))) - -#define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \ - cast(int, sizeof(TValue *)*((n)-1))) - - -LUAI_FUNC Proto *luaF_newproto (lua_State *L); -LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e); -LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e); -LUAI_FUNC UpVal *luaF_newupval (lua_State *L); -LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level); -LUAI_FUNC void luaF_close (lua_State *L, StkId level); -LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); -LUAI_FUNC void luaF_freeclosure (lua_State *L, Closure *c); -LUAI_FUNC void luaF_freeupval (lua_State *L, UpVal *uv); -LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number, - int pc); - - -#endif diff --git a/Utilities/lua-5.1.5/src/lgc.c b/Utilities/lua-5.1.5/src/lgc.c deleted file mode 100644 index e909c79a9..000000000 --- a/Utilities/lua-5.1.5/src/lgc.c +++ /dev/null @@ -1,710 +0,0 @@ -/* -** $Id: lgc.c,v 2.38.1.2 2011/03/18 18:05:38 roberto Exp $ -** Garbage Collector -** See Copyright Notice in lua.h -*/ - -#include - -#define lgc_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lgc.h" -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" - - -#define GCSTEPSIZE 1024u -#define GCSWEEPMAX 40 -#define GCSWEEPCOST 10 -#define GCFINALIZECOST 100 - - -#define maskmarks cast_byte(~(bitmask(BLACKBIT)|WHITEBITS)) - -#define makewhite(g,x) \ - ((x)->gch.marked = cast_byte(((x)->gch.marked & maskmarks) | luaC_white(g))) - -#define white2gray(x) reset2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT) -#define black2gray(x) resetbit((x)->gch.marked, BLACKBIT) - -#define stringmark(s) reset2bits((s)->tsv.marked, WHITE0BIT, WHITE1BIT) - - -#define isfinalized(u) testbit((u)->marked, FINALIZEDBIT) -#define markfinalized(u) l_setbit((u)->marked, FINALIZEDBIT) - - -#define KEYWEAK bitmask(KEYWEAKBIT) -#define VALUEWEAK bitmask(VALUEWEAKBIT) - - - -#define markvalue(g,o) { checkconsistency(o); \ - if (iscollectable(o) && iswhite(gcvalue(o))) reallymarkobject(g,gcvalue(o)); } - -#define markobject(g,t) { if (iswhite(obj2gco(t))) \ - reallymarkobject(g, obj2gco(t)); } - - -#define setthreshold(g) (g->GCthreshold = (g->estimate/100) * g->gcpause) - - -static void removeentry (Node *n) { - lua_assert(ttisnil(gval(n))); - if (iscollectable(gkey(n))) - setttype(gkey(n), LUA_TDEADKEY); /* dead key; remove it */ -} - - -static void reallymarkobject (global_State *g, GCObject *o) { - lua_assert(iswhite(o) && !isdead(g, o)); - white2gray(o); - switch (o->gch.tt) { - case LUA_TSTRING: { - return; - } - case LUA_TUSERDATA: { - Table *mt = gco2u(o)->metatable; - gray2black(o); /* udata are never gray */ - if (mt) markobject(g, mt); - markobject(g, gco2u(o)->env); - return; - } - case LUA_TUPVAL: { - UpVal *uv = gco2uv(o); - markvalue(g, uv->v); - if (uv->v == &uv->u.value) /* closed? */ - gray2black(o); /* open upvalues are never black */ - return; - } - case LUA_TFUNCTION: { - gco2cl(o)->c.gclist = g->gray; - g->gray = o; - break; - } - case LUA_TTABLE: { - gco2h(o)->gclist = g->gray; - g->gray = o; - break; - } - case LUA_TTHREAD: { - gco2th(o)->gclist = g->gray; - g->gray = o; - break; - } - case LUA_TPROTO: { - gco2p(o)->gclist = g->gray; - g->gray = o; - break; - } - default: lua_assert(0); - } -} - - -static void marktmu (global_State *g) { - GCObject *u = g->tmudata; - if (u) { - do { - u = u->gch.next; - makewhite(g, u); /* may be marked, if left from previous GC */ - reallymarkobject(g, u); - } while (u != g->tmudata); - } -} - - -/* move `dead' udata that need finalization to list `tmudata' */ -size_t luaC_separateudata (lua_State *L, int all) { - global_State *g = G(L); - size_t deadmem = 0; - GCObject **p = &g->mainthread->next; - GCObject *curr; - while ((curr = *p) != NULL) { - if (!(iswhite(curr) || all) || isfinalized(gco2u(curr))) - p = &curr->gch.next; /* don't bother with them */ - else if (fasttm(L, gco2u(curr)->metatable, TM_GC) == NULL) { - markfinalized(gco2u(curr)); /* don't need finalization */ - p = &curr->gch.next; - } - else { /* must call its gc method */ - deadmem += sizeudata(gco2u(curr)); - markfinalized(gco2u(curr)); - *p = curr->gch.next; - /* link `curr' at the end of `tmudata' list */ - if (g->tmudata == NULL) /* list is empty? */ - g->tmudata = curr->gch.next = curr; /* creates a circular list */ - else { - curr->gch.next = g->tmudata->gch.next; - g->tmudata->gch.next = curr; - g->tmudata = curr; - } - } - } - return deadmem; -} - - -static int traversetable (global_State *g, Table *h) { - int i; - int weakkey = 0; - int weakvalue = 0; - const TValue *mode; - if (h->metatable) - markobject(g, h->metatable); - mode = gfasttm(g, h->metatable, TM_MODE); - if (mode && ttisstring(mode)) { /* is there a weak mode? */ - weakkey = (strchr(svalue(mode), 'k') != NULL); - weakvalue = (strchr(svalue(mode), 'v') != NULL); - if (weakkey || weakvalue) { /* is really weak? */ - h->marked &= ~(KEYWEAK | VALUEWEAK); /* clear bits */ - h->marked |= cast_byte((weakkey << KEYWEAKBIT) | - (weakvalue << VALUEWEAKBIT)); - h->gclist = g->weak; /* must be cleared after GC, ... */ - g->weak = obj2gco(h); /* ... so put in the appropriate list */ - } - } - if (weakkey && weakvalue) return 1; - if (!weakvalue) { - i = h->sizearray; - while (i--) - markvalue(g, &h->array[i]); - } - i = sizenode(h); - while (i--) { - Node *n = gnode(h, i); - lua_assert(ttype(gkey(n)) != LUA_TDEADKEY || ttisnil(gval(n))); - if (ttisnil(gval(n))) - removeentry(n); /* remove empty entries */ - else { - lua_assert(!ttisnil(gkey(n))); - if (!weakkey) markvalue(g, gkey(n)); - if (!weakvalue) markvalue(g, gval(n)); - } - } - return weakkey || weakvalue; -} - - -/* -** All marks are conditional because a GC may happen while the -** prototype is still being created -*/ -static void traverseproto (global_State *g, Proto *f) { - int i; - if (f->source) stringmark(f->source); - for (i=0; isizek; i++) /* mark literals */ - markvalue(g, &f->k[i]); - for (i=0; isizeupvalues; i++) { /* mark upvalue names */ - if (f->upvalues[i]) - stringmark(f->upvalues[i]); - } - for (i=0; isizep; i++) { /* mark nested protos */ - if (f->p[i]) - markobject(g, f->p[i]); - } - for (i=0; isizelocvars; i++) { /* mark local-variable names */ - if (f->locvars[i].varname) - stringmark(f->locvars[i].varname); - } -} - - - -static void traverseclosure (global_State *g, Closure *cl) { - markobject(g, cl->c.env); - if (cl->c.isC) { - int i; - for (i=0; ic.nupvalues; i++) /* mark its upvalues */ - markvalue(g, &cl->c.upvalue[i]); - } - else { - int i; - lua_assert(cl->l.nupvalues == cl->l.p->nups); - markobject(g, cl->l.p); - for (i=0; il.nupvalues; i++) /* mark its upvalues */ - markobject(g, cl->l.upvals[i]); - } -} - - -static void checkstacksizes (lua_State *L, StkId max) { - int ci_used = cast_int(L->ci - L->base_ci); /* number of `ci' in use */ - int s_used = cast_int(max - L->stack); /* part of stack in use */ - if (L->size_ci > LUAI_MAXCALLS) /* handling overflow? */ - return; /* do not touch the stacks */ - if (4*ci_used < L->size_ci && 2*BASIC_CI_SIZE < L->size_ci) - luaD_reallocCI(L, L->size_ci/2); /* still big enough... */ - condhardstacktests(luaD_reallocCI(L, ci_used + 1)); - if (4*s_used < L->stacksize && - 2*(BASIC_STACK_SIZE+EXTRA_STACK) < L->stacksize) - luaD_reallocstack(L, L->stacksize/2); /* still big enough... */ - condhardstacktests(luaD_reallocstack(L, s_used)); -} - - -static void traversestack (global_State *g, lua_State *l) { - StkId o, lim; - CallInfo *ci; - markvalue(g, gt(l)); - lim = l->top; - for (ci = l->base_ci; ci <= l->ci; ci++) { - lua_assert(ci->top <= l->stack_last); - if (lim < ci->top) lim = ci->top; - } - for (o = l->stack; o < l->top; o++) - markvalue(g, o); - for (; o <= lim; o++) - setnilvalue(o); - checkstacksizes(l, lim); -} - - -/* -** traverse one gray object, turning it to black. -** Returns `quantity' traversed. -*/ -static l_mem propagatemark (global_State *g) { - GCObject *o = g->gray; - lua_assert(isgray(o)); - gray2black(o); - switch (o->gch.tt) { - case LUA_TTABLE: { - Table *h = gco2h(o); - g->gray = h->gclist; - if (traversetable(g, h)) /* table is weak? */ - black2gray(o); /* keep it gray */ - return sizeof(Table) + sizeof(TValue) * h->sizearray + - sizeof(Node) * sizenode(h); - } - case LUA_TFUNCTION: { - Closure *cl = gco2cl(o); - g->gray = cl->c.gclist; - traverseclosure(g, cl); - return (cl->c.isC) ? sizeCclosure(cl->c.nupvalues) : - sizeLclosure(cl->l.nupvalues); - } - case LUA_TTHREAD: { - lua_State *th = gco2th(o); - g->gray = th->gclist; - th->gclist = g->grayagain; - g->grayagain = o; - black2gray(o); - traversestack(g, th); - return sizeof(lua_State) + sizeof(TValue) * th->stacksize + - sizeof(CallInfo) * th->size_ci; - } - case LUA_TPROTO: { - Proto *p = gco2p(o); - g->gray = p->gclist; - traverseproto(g, p); - return sizeof(Proto) + sizeof(Instruction) * p->sizecode + - sizeof(Proto *) * p->sizep + - sizeof(TValue) * p->sizek + - sizeof(int) * p->sizelineinfo + - sizeof(LocVar) * p->sizelocvars + - sizeof(TString *) * p->sizeupvalues; - } - default: lua_assert(0); return 0; - } -} - - -static size_t propagateall (global_State *g) { - size_t m = 0; - while (g->gray) m += propagatemark(g); - return m; -} - - -/* -** The next function tells whether a key or value can be cleared from -** a weak table. Non-collectable objects are never removed from weak -** tables. Strings behave as `values', so are never removed too. for -** other objects: if really collected, cannot keep them; for userdata -** being finalized, keep them in keys, but not in values -*/ -static int iscleared (const TValue *o, int iskey) { - if (!iscollectable(o)) return 0; - if (ttisstring(o)) { - stringmark(rawtsvalue(o)); /* strings are `values', so are never weak */ - return 0; - } - return iswhite(gcvalue(o)) || - (ttisuserdata(o) && (!iskey && isfinalized(uvalue(o)))); -} - - -/* -** clear collected entries from weaktables -*/ -static void cleartable (GCObject *l) { - while (l) { - Table *h = gco2h(l); - int i = h->sizearray; - lua_assert(testbit(h->marked, VALUEWEAKBIT) || - testbit(h->marked, KEYWEAKBIT)); - if (testbit(h->marked, VALUEWEAKBIT)) { - while (i--) { - TValue *o = &h->array[i]; - if (iscleared(o, 0)) /* value was collected? */ - setnilvalue(o); /* remove value */ - } - } - i = sizenode(h); - while (i--) { - Node *n = gnode(h, i); - if (!ttisnil(gval(n)) && /* non-empty entry? */ - (iscleared(key2tval(n), 1) || iscleared(gval(n), 0))) { - setnilvalue(gval(n)); /* remove value ... */ - removeentry(n); /* remove entry from table */ - } - } - l = h->gclist; - } -} - - -static void freeobj (lua_State *L, GCObject *o) { - switch (o->gch.tt) { - case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break; - case LUA_TFUNCTION: luaF_freeclosure(L, gco2cl(o)); break; - case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break; - case LUA_TTABLE: luaH_free(L, gco2h(o)); break; - case LUA_TTHREAD: { - lua_assert(gco2th(o) != L && gco2th(o) != G(L)->mainthread); - luaE_freethread(L, gco2th(o)); - break; - } - case LUA_TSTRING: { - G(L)->strt.nuse--; - luaM_freemem(L, o, sizestring(gco2ts(o))); - break; - } - case LUA_TUSERDATA: { - luaM_freemem(L, o, sizeudata(gco2u(o))); - break; - } - default: lua_assert(0); - } -} - - - -#define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM) - - -static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) { - GCObject *curr; - global_State *g = G(L); - int deadmask = otherwhite(g); - while ((curr = *p) != NULL && count-- > 0) { - if (curr->gch.tt == LUA_TTHREAD) /* sweep open upvalues of each thread */ - sweepwholelist(L, &gco2th(curr)->openupval); - if ((curr->gch.marked ^ WHITEBITS) & deadmask) { /* not dead? */ - lua_assert(!isdead(g, curr) || testbit(curr->gch.marked, FIXEDBIT)); - makewhite(g, curr); /* make it white (for next cycle) */ - p = &curr->gch.next; - } - else { /* must erase `curr' */ - lua_assert(isdead(g, curr) || deadmask == bitmask(SFIXEDBIT)); - *p = curr->gch.next; - if (curr == g->rootgc) /* is the first element of the list? */ - g->rootgc = curr->gch.next; /* adjust first */ - freeobj(L, curr); - } - } - return p; -} - - -static void checkSizes (lua_State *L) { - global_State *g = G(L); - /* check size of string hash */ - if (g->strt.nuse < cast(lu_int32, g->strt.size/4) && - g->strt.size > MINSTRTABSIZE*2) - luaS_resize(L, g->strt.size/2); /* table is too big */ - /* check size of buffer */ - if (luaZ_sizebuffer(&g->buff) > LUA_MINBUFFER*2) { /* buffer too big? */ - size_t newsize = luaZ_sizebuffer(&g->buff) / 2; - luaZ_resizebuffer(L, &g->buff, newsize); - } -} - - -static void GCTM (lua_State *L) { - global_State *g = G(L); - GCObject *o = g->tmudata->gch.next; /* get first element */ - Udata *udata = rawgco2u(o); - const TValue *tm; - /* remove udata from `tmudata' */ - if (o == g->tmudata) /* last element? */ - g->tmudata = NULL; - else - g->tmudata->gch.next = udata->uv.next; - udata->uv.next = g->mainthread->next; /* return it to `root' list */ - g->mainthread->next = o; - makewhite(g, o); - tm = fasttm(L, udata->uv.metatable, TM_GC); - if (tm != NULL) { - lu_byte oldah = L->allowhook; - lu_mem oldt = g->GCthreshold; - L->allowhook = 0; /* stop debug hooks during GC tag method */ - g->GCthreshold = 2*g->totalbytes; /* avoid GC steps */ - setobj2s(L, L->top, tm); - setuvalue(L, L->top+1, udata); - L->top += 2; - luaD_call(L, L->top - 2, 0); - L->allowhook = oldah; /* restore hooks */ - g->GCthreshold = oldt; /* restore threshold */ - } -} - - -/* -** Call all GC tag methods -*/ -void luaC_callGCTM (lua_State *L) { - while (G(L)->tmudata) - GCTM(L); -} - - -void luaC_freeall (lua_State *L) { - global_State *g = G(L); - int i; - g->currentwhite = WHITEBITS | bitmask(SFIXEDBIT); /* mask to collect all elements */ - sweepwholelist(L, &g->rootgc); - for (i = 0; i < g->strt.size; i++) /* free all string lists */ - sweepwholelist(L, &g->strt.hash[i]); -} - - -static void markmt (global_State *g) { - int i; - for (i=0; imt[i]) markobject(g, g->mt[i]); -} - - -/* mark root set */ -static void markroot (lua_State *L) { - global_State *g = G(L); - g->gray = NULL; - g->grayagain = NULL; - g->weak = NULL; - markobject(g, g->mainthread); - /* make global table be traversed before main stack */ - markvalue(g, gt(g->mainthread)); - markvalue(g, registry(L)); - markmt(g); - g->gcstate = GCSpropagate; -} - - -static void remarkupvals (global_State *g) { - UpVal *uv; - for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) { - lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); - if (isgray(obj2gco(uv))) - markvalue(g, uv->v); - } -} - - -static void atomic (lua_State *L) { - global_State *g = G(L); - size_t udsize; /* total size of userdata to be finalized */ - /* remark occasional upvalues of (maybe) dead threads */ - remarkupvals(g); - /* traverse objects cautch by write barrier and by 'remarkupvals' */ - propagateall(g); - /* remark weak tables */ - g->gray = g->weak; - g->weak = NULL; - lua_assert(!iswhite(obj2gco(g->mainthread))); - markobject(g, L); /* mark running thread */ - markmt(g); /* mark basic metatables (again) */ - propagateall(g); - /* remark gray again */ - g->gray = g->grayagain; - g->grayagain = NULL; - propagateall(g); - udsize = luaC_separateudata(L, 0); /* separate userdata to be finalized */ - marktmu(g); /* mark `preserved' userdata */ - udsize += propagateall(g); /* remark, to propagate `preserveness' */ - cleartable(g->weak); /* remove collected objects from weak tables */ - /* flip current white */ - g->currentwhite = cast_byte(otherwhite(g)); - g->sweepstrgc = 0; - g->sweepgc = &g->rootgc; - g->gcstate = GCSsweepstring; - g->estimate = g->totalbytes - udsize; /* first estimate */ -} - - -static l_mem singlestep (lua_State *L) { - global_State *g = G(L); - /*lua_checkmemory(L);*/ - switch (g->gcstate) { - case GCSpause: { - markroot(L); /* start a new collection */ - return 0; - } - case GCSpropagate: { - if (g->gray) - return propagatemark(g); - else { /* no more `gray' objects */ - atomic(L); /* finish mark phase */ - return 0; - } - } - case GCSsweepstring: { - lu_mem old = g->totalbytes; - sweepwholelist(L, &g->strt.hash[g->sweepstrgc++]); - if (g->sweepstrgc >= g->strt.size) /* nothing more to sweep? */ - g->gcstate = GCSsweep; /* end sweep-string phase */ - lua_assert(old >= g->totalbytes); - g->estimate -= old - g->totalbytes; - return GCSWEEPCOST; - } - case GCSsweep: { - lu_mem old = g->totalbytes; - g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX); - if (*g->sweepgc == NULL) { /* nothing more to sweep? */ - checkSizes(L); - g->gcstate = GCSfinalize; /* end sweep phase */ - } - lua_assert(old >= g->totalbytes); - g->estimate -= old - g->totalbytes; - return GCSWEEPMAX*GCSWEEPCOST; - } - case GCSfinalize: { - if (g->tmudata) { - GCTM(L); - if (g->estimate > GCFINALIZECOST) - g->estimate -= GCFINALIZECOST; - return GCFINALIZECOST; - } - else { - g->gcstate = GCSpause; /* end collection */ - g->gcdept = 0; - return 0; - } - } - default: lua_assert(0); return 0; - } -} - - -void luaC_step (lua_State *L) { - global_State *g = G(L); - l_mem lim = (GCSTEPSIZE/100) * g->gcstepmul; - if (lim == 0) - lim = (MAX_LUMEM-1)/2; /* no limit */ - g->gcdept += g->totalbytes - g->GCthreshold; - do { - lim -= singlestep(L); - if (g->gcstate == GCSpause) - break; - } while (lim > 0); - if (g->gcstate != GCSpause) { - if (g->gcdept < GCSTEPSIZE) - g->GCthreshold = g->totalbytes + GCSTEPSIZE; /* - lim/g->gcstepmul;*/ - else { - g->gcdept -= GCSTEPSIZE; - g->GCthreshold = g->totalbytes; - } - } - else { - setthreshold(g); - } -} - - -void luaC_fullgc (lua_State *L) { - global_State *g = G(L); - if (g->gcstate <= GCSpropagate) { - /* reset sweep marks to sweep all elements (returning them to white) */ - g->sweepstrgc = 0; - g->sweepgc = &g->rootgc; - /* reset other collector lists */ - g->gray = NULL; - g->grayagain = NULL; - g->weak = NULL; - g->gcstate = GCSsweepstring; - } - lua_assert(g->gcstate != GCSpause && g->gcstate != GCSpropagate); - /* finish any pending sweep phase */ - while (g->gcstate != GCSfinalize) { - lua_assert(g->gcstate == GCSsweepstring || g->gcstate == GCSsweep); - singlestep(L); - } - markroot(L); - while (g->gcstate != GCSpause) { - singlestep(L); - } - setthreshold(g); -} - - -void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v) { - global_State *g = G(L); - lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); - lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause); - lua_assert(ttype(&o->gch) != LUA_TTABLE); - /* must keep invariant? */ - if (g->gcstate == GCSpropagate) - reallymarkobject(g, v); /* restore invariant */ - else /* don't mind */ - makewhite(g, o); /* mark as white just to avoid other barriers */ -} - - -void luaC_barrierback (lua_State *L, Table *t) { - global_State *g = G(L); - GCObject *o = obj2gco(t); - lua_assert(isblack(o) && !isdead(g, o)); - lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause); - black2gray(o); /* make table gray (again) */ - t->gclist = g->grayagain; - g->grayagain = o; -} - - -void luaC_link (lua_State *L, GCObject *o, lu_byte tt) { - global_State *g = G(L); - o->gch.next = g->rootgc; - g->rootgc = o; - o->gch.marked = luaC_white(g); - o->gch.tt = tt; -} - - -void luaC_linkupval (lua_State *L, UpVal *uv) { - global_State *g = G(L); - GCObject *o = obj2gco(uv); - o->gch.next = g->rootgc; /* link upvalue into `rootgc' list */ - g->rootgc = o; - if (isgray(o)) { - if (g->gcstate == GCSpropagate) { - gray2black(o); /* closed upvalues need barrier */ - luaC_barrier(L, uv, uv->v); - } - else { /* sweep phase: sweep it (turning it into white) */ - makewhite(g, o); - lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause); - } - } -} - diff --git a/Utilities/lua-5.1.5/src/lgc.h b/Utilities/lua-5.1.5/src/lgc.h deleted file mode 100644 index 5a8dc605b..000000000 --- a/Utilities/lua-5.1.5/src/lgc.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -** $Id: lgc.h,v 2.15.1.1 2007/12/27 13:02:25 roberto Exp $ -** Garbage Collector -** See Copyright Notice in lua.h -*/ - -#ifndef lgc_h -#define lgc_h - - -#include "lobject.h" - - -/* -** Possible states of the Garbage Collector -*/ -#define GCSpause 0 -#define GCSpropagate 1 -#define GCSsweepstring 2 -#define GCSsweep 3 -#define GCSfinalize 4 - - -/* -** some userful bit tricks -*/ -#define resetbits(x,m) ((x) &= cast(lu_byte, ~(m))) -#define setbits(x,m) ((x) |= (m)) -#define testbits(x,m) ((x) & (m)) -#define bitmask(b) (1<<(b)) -#define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) -#define l_setbit(x,b) setbits(x, bitmask(b)) -#define resetbit(x,b) resetbits(x, bitmask(b)) -#define testbit(x,b) testbits(x, bitmask(b)) -#define set2bits(x,b1,b2) setbits(x, (bit2mask(b1, b2))) -#define reset2bits(x,b1,b2) resetbits(x, (bit2mask(b1, b2))) -#define test2bits(x,b1,b2) testbits(x, (bit2mask(b1, b2))) - - - -/* -** Layout for bit use in `marked' field: -** bit 0 - object is white (type 0) -** bit 1 - object is white (type 1) -** bit 2 - object is black -** bit 3 - for userdata: has been finalized -** bit 3 - for tables: has weak keys -** bit 4 - for tables: has weak values -** bit 5 - object is fixed (should not be collected) -** bit 6 - object is "super" fixed (only the main thread) -*/ - - -#define WHITE0BIT 0 -#define WHITE1BIT 1 -#define BLACKBIT 2 -#define FINALIZEDBIT 3 -#define KEYWEAKBIT 3 -#define VALUEWEAKBIT 4 -#define FIXEDBIT 5 -#define SFIXEDBIT 6 -#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) - - -#define iswhite(x) test2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT) -#define isblack(x) testbit((x)->gch.marked, BLACKBIT) -#define isgray(x) (!isblack(x) && !iswhite(x)) - -#define otherwhite(g) (g->currentwhite ^ WHITEBITS) -#define isdead(g,v) ((v)->gch.marked & otherwhite(g) & WHITEBITS) - -#define changewhite(x) ((x)->gch.marked ^= WHITEBITS) -#define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT) - -#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) - -#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS) - - -#define luaC_checkGC(L) { \ - condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); \ - if (G(L)->totalbytes >= G(L)->GCthreshold) \ - luaC_step(L); } - - -#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \ - luaC_barrierf(L,obj2gco(p),gcvalue(v)); } - -#define luaC_barriert(L,t,v) { if (valiswhite(v) && isblack(obj2gco(t))) \ - luaC_barrierback(L,t); } - -#define luaC_objbarrier(L,p,o) \ - { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \ - luaC_barrierf(L,obj2gco(p),obj2gco(o)); } - -#define luaC_objbarriert(L,t,o) \ - { if (iswhite(obj2gco(o)) && isblack(obj2gco(t))) luaC_barrierback(L,t); } - -LUAI_FUNC size_t luaC_separateudata (lua_State *L, int all); -LUAI_FUNC void luaC_callGCTM (lua_State *L); -LUAI_FUNC void luaC_freeall (lua_State *L); -LUAI_FUNC void luaC_step (lua_State *L); -LUAI_FUNC void luaC_fullgc (lua_State *L); -LUAI_FUNC void luaC_link (lua_State *L, GCObject *o, lu_byte tt); -LUAI_FUNC void luaC_linkupval (lua_State *L, UpVal *uv); -LUAI_FUNC void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v); -LUAI_FUNC void luaC_barrierback (lua_State *L, Table *t); - - -#endif diff --git a/Utilities/lua-5.1.5/src/linit.c b/Utilities/lua-5.1.5/src/linit.c deleted file mode 100644 index c1f90dfab..000000000 --- a/Utilities/lua-5.1.5/src/linit.c +++ /dev/null @@ -1,38 +0,0 @@ -/* -** $Id: linit.c,v 1.14.1.1 2007/12/27 13:02:25 roberto Exp $ -** Initialization of libraries for lua.c -** See Copyright Notice in lua.h -*/ - - -#define linit_c -#define LUA_LIB - -#include "lua.h" - -#include "lualib.h" -#include "lauxlib.h" - - -static const luaL_Reg lualibs[] = { - {"", luaopen_base}, - {LUA_LOADLIBNAME, luaopen_package}, - {LUA_TABLIBNAME, luaopen_table}, - {LUA_IOLIBNAME, luaopen_io}, - {LUA_OSLIBNAME, luaopen_os}, - {LUA_STRLIBNAME, luaopen_string}, - {LUA_MATHLIBNAME, luaopen_math}, - {LUA_DBLIBNAME, luaopen_debug}, - {NULL, NULL} -}; - - -LUALIB_API void luaL_openlibs (lua_State *L) { - const luaL_Reg *lib = lualibs; - for (; lib->func; lib++) { - lua_pushcfunction(L, lib->func); - lua_pushstring(L, lib->name); - lua_call(L, 1, 0); - } -} - diff --git a/Utilities/lua-5.1.5/src/liolib.c b/Utilities/lua-5.1.5/src/liolib.c deleted file mode 100644 index 649f9a595..000000000 --- a/Utilities/lua-5.1.5/src/liolib.c +++ /dev/null @@ -1,556 +0,0 @@ -/* -** $Id: liolib.c,v 2.73.1.4 2010/05/14 15:33:51 roberto Exp $ -** Standard I/O (and system) library -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include -#include - -#define liolib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - - -#define IO_INPUT 1 -#define IO_OUTPUT 2 - - -static const char *const fnames[] = {"input", "output"}; - - -static int pushresult (lua_State *L, int i, const char *filename) { - int en = errno; /* calls to Lua API may change this value */ - if (i) { - lua_pushboolean(L, 1); - return 1; - } - else { - lua_pushnil(L); - if (filename) - lua_pushfstring(L, "%s: %s", filename, strerror(en)); - else - lua_pushfstring(L, "%s", strerror(en)); - lua_pushinteger(L, en); - return 3; - } -} - - -static void fileerror (lua_State *L, int arg, const char *filename) { - lua_pushfstring(L, "%s: %s", filename, strerror(errno)); - luaL_argerror(L, arg, lua_tostring(L, -1)); -} - - -#define tofilep(L) ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE)) - - -static int io_type (lua_State *L) { - void *ud; - luaL_checkany(L, 1); - ud = lua_touserdata(L, 1); - lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE); - if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1)) - lua_pushnil(L); /* not a file */ - else if (*((FILE **)ud) == NULL) - lua_pushliteral(L, "closed file"); - else - lua_pushliteral(L, "file"); - return 1; -} - - -static FILE *tofile (lua_State *L) { - FILE **f = tofilep(L); - if (*f == NULL) - luaL_error(L, "attempt to use a closed file"); - return *f; -} - - - -/* -** When creating file handles, always creates a `closed' file handle -** before opening the actual file; so, if there is a memory error, the -** file is not left opened. -*/ -static FILE **newfile (lua_State *L) { - FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *)); - *pf = NULL; /* file handle is currently `closed' */ - luaL_getmetatable(L, LUA_FILEHANDLE); - lua_setmetatable(L, -2); - return pf; -} - - -/* -** function to (not) close the standard files stdin, stdout, and stderr -*/ -static int io_noclose (lua_State *L) { - lua_pushnil(L); - lua_pushliteral(L, "cannot close standard file"); - return 2; -} - - -/* -** function to close 'popen' files -*/ -static int io_pclose (lua_State *L) { - FILE **p = tofilep(L); - int ok = lua_pclose(L, *p); - *p = NULL; - return pushresult(L, ok, NULL); -} - - -/* -** function to close regular files -*/ -static int io_fclose (lua_State *L) { - FILE **p = tofilep(L); - int ok = (fclose(*p) == 0); - *p = NULL; - return pushresult(L, ok, NULL); -} - - -static int aux_close (lua_State *L) { - lua_getfenv(L, 1); - lua_getfield(L, -1, "__close"); - return (lua_tocfunction(L, -1))(L); -} - - -static int io_close (lua_State *L) { - if (lua_isnone(L, 1)) - lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT); - tofile(L); /* make sure argument is a file */ - return aux_close(L); -} - - -static int io_gc (lua_State *L) { - FILE *f = *tofilep(L); - /* ignore closed files */ - if (f != NULL) - aux_close(L); - return 0; -} - - -static int io_tostring (lua_State *L) { - FILE *f = *tofilep(L); - if (f == NULL) - lua_pushliteral(L, "file (closed)"); - else - lua_pushfstring(L, "file (%p)", f); - return 1; -} - - -static int io_open (lua_State *L) { - const char *filename = luaL_checkstring(L, 1); - const char *mode = luaL_optstring(L, 2, "r"); - FILE **pf = newfile(L); - *pf = fopen(filename, mode); - return (*pf == NULL) ? pushresult(L, 0, filename) : 1; -} - - -/* -** this function has a separated environment, which defines the -** correct __close for 'popen' files -*/ -static int io_popen (lua_State *L) { - const char *filename = luaL_checkstring(L, 1); - const char *mode = luaL_optstring(L, 2, "r"); - FILE **pf = newfile(L); - *pf = lua_popen(L, filename, mode); - return (*pf == NULL) ? pushresult(L, 0, filename) : 1; -} - - -static int io_tmpfile (lua_State *L) { - FILE **pf = newfile(L); - *pf = tmpfile(); - return (*pf == NULL) ? pushresult(L, 0, NULL) : 1; -} - - -static FILE *getiofile (lua_State *L, int findex) { - FILE *f; - lua_rawgeti(L, LUA_ENVIRONINDEX, findex); - f = *(FILE **)lua_touserdata(L, -1); - if (f == NULL) - luaL_error(L, "standard %s file is closed", fnames[findex - 1]); - return f; -} - - -static int g_iofile (lua_State *L, int f, const char *mode) { - if (!lua_isnoneornil(L, 1)) { - const char *filename = lua_tostring(L, 1); - if (filename) { - FILE **pf = newfile(L); - *pf = fopen(filename, mode); - if (*pf == NULL) - fileerror(L, 1, filename); - } - else { - tofile(L); /* check that it's a valid file handle */ - lua_pushvalue(L, 1); - } - lua_rawseti(L, LUA_ENVIRONINDEX, f); - } - /* return current value */ - lua_rawgeti(L, LUA_ENVIRONINDEX, f); - return 1; -} - - -static int io_input (lua_State *L) { - return g_iofile(L, IO_INPUT, "r"); -} - - -static int io_output (lua_State *L) { - return g_iofile(L, IO_OUTPUT, "w"); -} - - -static int io_readline (lua_State *L); - - -static void aux_lines (lua_State *L, int idx, int toclose) { - lua_pushvalue(L, idx); - lua_pushboolean(L, toclose); /* close/not close file when finished */ - lua_pushcclosure(L, io_readline, 2); -} - - -static int f_lines (lua_State *L) { - tofile(L); /* check that it's a valid file handle */ - aux_lines(L, 1, 0); - return 1; -} - - -static int io_lines (lua_State *L) { - if (lua_isnoneornil(L, 1)) { /* no arguments? */ - /* will iterate over default input */ - lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT); - return f_lines(L); - } - else { - const char *filename = luaL_checkstring(L, 1); - FILE **pf = newfile(L); - *pf = fopen(filename, "r"); - if (*pf == NULL) - fileerror(L, 1, filename); - aux_lines(L, lua_gettop(L), 1); - return 1; - } -} - - -/* -** {====================================================== -** READ -** ======================================================= -*/ - - -static int read_number (lua_State *L, FILE *f) { - lua_Number d; - if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) { - lua_pushnumber(L, d); - return 1; - } - else { - lua_pushnil(L); /* "result" to be removed */ - return 0; /* read fails */ - } -} - - -static int test_eof (lua_State *L, FILE *f) { - int c = getc(f); - ungetc(c, f); - lua_pushlstring(L, NULL, 0); - return (c != EOF); -} - - -static int read_line (lua_State *L, FILE *f) { - luaL_Buffer b; - luaL_buffinit(L, &b); - for (;;) { - size_t l; - char *p = luaL_prepbuffer(&b); - if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */ - luaL_pushresult(&b); /* close buffer */ - return (lua_objlen(L, -1) > 0); /* check whether read something */ - } - l = strlen(p); - if (l == 0 || p[l-1] != '\n') - luaL_addsize(&b, l); - else { - luaL_addsize(&b, l - 1); /* do not include `eol' */ - luaL_pushresult(&b); /* close buffer */ - return 1; /* read at least an `eol' */ - } - } -} - - -static int read_chars (lua_State *L, FILE *f, size_t n) { - size_t rlen; /* how much to read */ - size_t nr; /* number of chars actually read */ - luaL_Buffer b; - luaL_buffinit(L, &b); - rlen = LUAL_BUFFERSIZE; /* try to read that much each time */ - do { - char *p = luaL_prepbuffer(&b); - if (rlen > n) rlen = n; /* cannot read more than asked */ - nr = fread(p, sizeof(char), rlen, f); - luaL_addsize(&b, nr); - n -= nr; /* still have to read `n' chars */ - } while (n > 0 && nr == rlen); /* until end of count or eof */ - luaL_pushresult(&b); /* close buffer */ - return (n == 0 || lua_objlen(L, -1) > 0); -} - - -static int g_read (lua_State *L, FILE *f, int first) { - int nargs = lua_gettop(L) - 1; - int success; - int n; - clearerr(f); - if (nargs == 0) { /* no arguments? */ - success = read_line(L, f); - n = first+1; /* to return 1 result */ - } - else { /* ensure stack space for all results and for auxlib's buffer */ - luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments"); - success = 1; - for (n = first; nargs-- && success; n++) { - if (lua_type(L, n) == LUA_TNUMBER) { - size_t l = (size_t)lua_tointeger(L, n); - success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l); - } - else { - const char *p = lua_tostring(L, n); - luaL_argcheck(L, p && p[0] == '*', n, "invalid option"); - switch (p[1]) { - case 'n': /* number */ - success = read_number(L, f); - break; - case 'l': /* line */ - success = read_line(L, f); - break; - case 'a': /* file */ - read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */ - success = 1; /* always success */ - break; - default: - return luaL_argerror(L, n, "invalid format"); - } - } - } - } - if (ferror(f)) - return pushresult(L, 0, NULL); - if (!success) { - lua_pop(L, 1); /* remove last result */ - lua_pushnil(L); /* push nil instead */ - } - return n - first; -} - - -static int io_read (lua_State *L) { - return g_read(L, getiofile(L, IO_INPUT), 1); -} - - -static int f_read (lua_State *L) { - return g_read(L, tofile(L), 2); -} - - -static int io_readline (lua_State *L) { - FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1)); - int sucess; - if (f == NULL) /* file is already closed? */ - luaL_error(L, "file is already closed"); - sucess = read_line(L, f); - if (ferror(f)) - return luaL_error(L, "%s", strerror(errno)); - if (sucess) return 1; - else { /* EOF */ - if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */ - lua_settop(L, 0); - lua_pushvalue(L, lua_upvalueindex(1)); - aux_close(L); /* close it */ - } - return 0; - } -} - -/* }====================================================== */ - - -static int g_write (lua_State *L, FILE *f, int arg) { - int nargs = lua_gettop(L) - 1; - int status = 1; - for (; nargs--; arg++) { - if (lua_type(L, arg) == LUA_TNUMBER) { - /* optimization: could be done exactly as for strings */ - status = status && - fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0; - } - else { - size_t l; - const char *s = luaL_checklstring(L, arg, &l); - status = status && (fwrite(s, sizeof(char), l, f) == l); - } - } - return pushresult(L, status, NULL); -} - - -static int io_write (lua_State *L) { - return g_write(L, getiofile(L, IO_OUTPUT), 1); -} - - -static int f_write (lua_State *L) { - return g_write(L, tofile(L), 2); -} - - -static int f_seek (lua_State *L) { - static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END}; - static const char *const modenames[] = {"set", "cur", "end", NULL}; - FILE *f = tofile(L); - int op = luaL_checkoption(L, 2, "cur", modenames); - long offset = luaL_optlong(L, 3, 0); - op = fseek(f, offset, mode[op]); - if (op) - return pushresult(L, 0, NULL); /* error */ - else { - lua_pushinteger(L, ftell(f)); - return 1; - } -} - - -static int f_setvbuf (lua_State *L) { - static const int mode[] = {_IONBF, _IOFBF, _IOLBF}; - static const char *const modenames[] = {"no", "full", "line", NULL}; - FILE *f = tofile(L); - int op = luaL_checkoption(L, 2, NULL, modenames); - lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE); - int res = setvbuf(f, NULL, mode[op], sz); - return pushresult(L, res == 0, NULL); -} - - - -static int io_flush (lua_State *L) { - return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL); -} - - -static int f_flush (lua_State *L) { - return pushresult(L, fflush(tofile(L)) == 0, NULL); -} - - -static const luaL_Reg iolib[] = { - {"close", io_close}, - {"flush", io_flush}, - {"input", io_input}, - {"lines", io_lines}, - {"open", io_open}, - {"output", io_output}, - {"popen", io_popen}, - {"read", io_read}, - {"tmpfile", io_tmpfile}, - {"type", io_type}, - {"write", io_write}, - {NULL, NULL} -}; - - -static const luaL_Reg flib[] = { - {"close", io_close}, - {"flush", f_flush}, - {"lines", f_lines}, - {"read", f_read}, - {"seek", f_seek}, - {"setvbuf", f_setvbuf}, - {"write", f_write}, - {"__gc", io_gc}, - {"__tostring", io_tostring}, - {NULL, NULL} -}; - - -static void createmeta (lua_State *L) { - luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */ - lua_pushvalue(L, -1); /* push metatable */ - lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */ - luaL_register(L, NULL, flib); /* file methods */ -} - - -static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) { - *newfile(L) = f; - if (k > 0) { - lua_pushvalue(L, -1); - lua_rawseti(L, LUA_ENVIRONINDEX, k); - } - lua_pushvalue(L, -2); /* copy environment */ - lua_setfenv(L, -2); /* set it */ - lua_setfield(L, -3, fname); -} - - -static void newfenv (lua_State *L, lua_CFunction cls) { - lua_createtable(L, 0, 1); - lua_pushcfunction(L, cls); - lua_setfield(L, -2, "__close"); -} - - -LUALIB_API int luaopen_io (lua_State *L) { - createmeta(L); - /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */ - newfenv(L, io_fclose); - lua_replace(L, LUA_ENVIRONINDEX); - /* open library */ - luaL_register(L, LUA_IOLIBNAME, iolib); - /* create (and set) default files */ - newfenv(L, io_noclose); /* close function for default files */ - createstdfile(L, stdin, IO_INPUT, "stdin"); - createstdfile(L, stdout, IO_OUTPUT, "stdout"); - createstdfile(L, stderr, 0, "stderr"); - lua_pop(L, 1); /* pop environment for default files */ - lua_getfield(L, -1, "popen"); - newfenv(L, io_pclose); /* create environment for 'popen' */ - lua_setfenv(L, -2); /* set fenv for 'popen' */ - lua_pop(L, 1); /* pop 'popen' */ - return 1; -} - diff --git a/Utilities/lua-5.1.5/src/llex.c b/Utilities/lua-5.1.5/src/llex.c deleted file mode 100644 index 88c6790c0..000000000 --- a/Utilities/lua-5.1.5/src/llex.c +++ /dev/null @@ -1,463 +0,0 @@ -/* -** $Id: llex.c,v 2.20.1.2 2009/11/23 14:58:22 roberto Exp $ -** Lexical Analyzer -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include - -#define llex_c -#define LUA_CORE - -#include "lua.h" - -#include "ldo.h" -#include "llex.h" -#include "lobject.h" -#include "lparser.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "lzio.h" - - - -#define next(ls) (ls->current = zgetc(ls->z)) - - - - -#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r') - - -/* ORDER RESERVED */ -const char *const luaX_tokens [] = { - "and", "break", "do", "else", "elseif", - "end", "false", "for", "function", "if", - "in", "local", "nil", "not", "or", "repeat", - "return", "then", "true", "until", "while", - "..", "...", "==", ">=", "<=", "~=", - "", "", "", "", - NULL -}; - - -#define save_and_next(ls) (save(ls, ls->current), next(ls)) - - -static void save (LexState *ls, int c) { - Mbuffer *b = ls->buff; - if (b->n + 1 > b->buffsize) { - size_t newsize; - if (b->buffsize >= MAX_SIZET/2) - luaX_lexerror(ls, "lexical element too long", 0); - newsize = b->buffsize * 2; - luaZ_resizebuffer(ls->L, b, newsize); - } - b->buffer[b->n++] = cast(char, c); -} - - -void luaX_init (lua_State *L) { - int i; - for (i=0; itsv.reserved = cast_byte(i+1); /* reserved word */ - } -} - - -#define MAXSRC 80 - - -const char *luaX_token2str (LexState *ls, int token) { - if (token < FIRST_RESERVED) { - lua_assert(token == cast(unsigned char, token)); - return (iscntrl(token)) ? luaO_pushfstring(ls->L, "char(%d)", token) : - luaO_pushfstring(ls->L, "%c", token); - } - else - return luaX_tokens[token-FIRST_RESERVED]; -} - - -static const char *txtToken (LexState *ls, int token) { - switch (token) { - case TK_NAME: - case TK_STRING: - case TK_NUMBER: - save(ls, '\0'); - return luaZ_buffer(ls->buff); - default: - return luaX_token2str(ls, token); - } -} - - -void luaX_lexerror (LexState *ls, const char *msg, int token) { - char buff[MAXSRC]; - luaO_chunkid(buff, getstr(ls->source), MAXSRC); - msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg); - if (token) - luaO_pushfstring(ls->L, "%s near " LUA_QS, msg, txtToken(ls, token)); - luaD_throw(ls->L, LUA_ERRSYNTAX); -} - - -void luaX_syntaxerror (LexState *ls, const char *msg) { - luaX_lexerror(ls, msg, ls->t.token); -} - - -TString *luaX_newstring (LexState *ls, const char *str, size_t l) { - lua_State *L = ls->L; - TString *ts = luaS_newlstr(L, str, l); - TValue *o = luaH_setstr(L, ls->fs->h, ts); /* entry for `str' */ - if (ttisnil(o)) { - setbvalue(o, 1); /* make sure `str' will not be collected */ - luaC_checkGC(L); - } - return ts; -} - - -static void inclinenumber (LexState *ls) { - int old = ls->current; - lua_assert(currIsNewline(ls)); - next(ls); /* skip `\n' or `\r' */ - if (currIsNewline(ls) && ls->current != old) - next(ls); /* skip `\n\r' or `\r\n' */ - if (++ls->linenumber >= MAX_INT) - luaX_syntaxerror(ls, "chunk has too many lines"); -} - - -void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source) { - ls->decpoint = '.'; - ls->L = L; - ls->lookahead.token = TK_EOS; /* no look-ahead token */ - ls->z = z; - ls->fs = NULL; - ls->linenumber = 1; - ls->lastline = 1; - ls->source = source; - luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ - next(ls); /* read first char */ -} - - - -/* -** ======================================================= -** LEXICAL ANALYZER -** ======================================================= -*/ - - - -static int check_next (LexState *ls, const char *set) { - if (!strchr(set, ls->current)) - return 0; - save_and_next(ls); - return 1; -} - - -static void buffreplace (LexState *ls, char from, char to) { - size_t n = luaZ_bufflen(ls->buff); - char *p = luaZ_buffer(ls->buff); - while (n--) - if (p[n] == from) p[n] = to; -} - - -static void trydecpoint (LexState *ls, SemInfo *seminfo) { - /* format error: try to update decimal point separator */ - struct lconv *cv = localeconv(); - char old = ls->decpoint; - ls->decpoint = (cv ? cv->decimal_point[0] : '.'); - buffreplace(ls, old, ls->decpoint); /* try updated decimal separator */ - if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) { - /* format error with correct decimal point: no more options */ - buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */ - luaX_lexerror(ls, "malformed number", TK_NUMBER); - } -} - - -/* LUA_NUMBER */ -static void read_numeral (LexState *ls, SemInfo *seminfo) { - lua_assert(isdigit(ls->current)); - do { - save_and_next(ls); - } while (isdigit(ls->current) || ls->current == '.'); - if (check_next(ls, "Ee")) /* `E'? */ - check_next(ls, "+-"); /* optional exponent sign */ - while (isalnum(ls->current) || ls->current == '_') - save_and_next(ls); - save(ls, '\0'); - buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */ - if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) /* format error? */ - trydecpoint(ls, seminfo); /* try to update decimal point separator */ -} - - -static int skip_sep (LexState *ls) { - int count = 0; - int s = ls->current; - lua_assert(s == '[' || s == ']'); - save_and_next(ls); - while (ls->current == '=') { - save_and_next(ls); - count++; - } - return (ls->current == s) ? count : (-count) - 1; -} - - -static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) { - int cont = 0; - (void)(cont); /* avoid warnings when `cont' is not used */ - save_and_next(ls); /* skip 2nd `[' */ - if (currIsNewline(ls)) /* string starts with a newline? */ - inclinenumber(ls); /* skip it */ - for (;;) { - switch (ls->current) { - case EOZ: - luaX_lexerror(ls, (seminfo) ? "unfinished long string" : - "unfinished long comment", TK_EOS); - break; /* to avoid warnings */ -#if defined(LUA_COMPAT_LSTR) - case '[': { - if (skip_sep(ls) == sep) { - save_and_next(ls); /* skip 2nd `[' */ - cont++; -#if LUA_COMPAT_LSTR == 1 - if (sep == 0) - luaX_lexerror(ls, "nesting of [[...]] is deprecated", '['); -#endif - } - break; - } -#endif - case ']': { - if (skip_sep(ls) == sep) { - save_and_next(ls); /* skip 2nd `]' */ -#if defined(LUA_COMPAT_LSTR) && LUA_COMPAT_LSTR == 2 - cont--; - if (sep == 0 && cont >= 0) break; -#endif - goto endloop; - } - break; - } - case '\n': - case '\r': { - save(ls, '\n'); - inclinenumber(ls); - if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */ - break; - } - default: { - if (seminfo) save_and_next(ls); - else next(ls); - } - } - } endloop: - if (seminfo) - seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep), - luaZ_bufflen(ls->buff) - 2*(2 + sep)); -} - - -static void read_string (LexState *ls, int del, SemInfo *seminfo) { - save_and_next(ls); - while (ls->current != del) { - switch (ls->current) { - case EOZ: - luaX_lexerror(ls, "unfinished string", TK_EOS); - continue; /* to avoid warnings */ - case '\n': - case '\r': - luaX_lexerror(ls, "unfinished string", TK_STRING); - continue; /* to avoid warnings */ - case '\\': { - int c; - next(ls); /* do not save the `\' */ - switch (ls->current) { - case 'a': c = '\a'; break; - case 'b': c = '\b'; break; - case 'f': c = '\f'; break; - case 'n': c = '\n'; break; - case 'r': c = '\r'; break; - case 't': c = '\t'; break; - case 'v': c = '\v'; break; - case '\n': /* go through */ - case '\r': save(ls, '\n'); inclinenumber(ls); continue; - case EOZ: continue; /* will raise an error next loop */ - default: { - if (!isdigit(ls->current)) - save_and_next(ls); /* handles \\, \", \', and \? */ - else { /* \xxx */ - int i = 0; - c = 0; - do { - c = 10*c + (ls->current-'0'); - next(ls); - } while (++i<3 && isdigit(ls->current)); - if (c > UCHAR_MAX) - luaX_lexerror(ls, "escape sequence too large", TK_STRING); - save(ls, c); - } - continue; - } - } - save(ls, c); - next(ls); - continue; - } - default: - save_and_next(ls); - } - } - save_and_next(ls); /* skip delimiter */ - seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1, - luaZ_bufflen(ls->buff) - 2); -} - - -static int llex (LexState *ls, SemInfo *seminfo) { - luaZ_resetbuffer(ls->buff); - for (;;) { - switch (ls->current) { - case '\n': - case '\r': { - inclinenumber(ls); - continue; - } - case '-': { - next(ls); - if (ls->current != '-') return '-'; - /* else is a comment */ - next(ls); - if (ls->current == '[') { - int sep = skip_sep(ls); - luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */ - if (sep >= 0) { - read_long_string(ls, NULL, sep); /* long comment */ - luaZ_resetbuffer(ls->buff); - continue; - } - } - /* else short comment */ - while (!currIsNewline(ls) && ls->current != EOZ) - next(ls); - continue; - } - case '[': { - int sep = skip_sep(ls); - if (sep >= 0) { - read_long_string(ls, seminfo, sep); - return TK_STRING; - } - else if (sep == -1) return '['; - else luaX_lexerror(ls, "invalid long string delimiter", TK_STRING); - } - case '=': { - next(ls); - if (ls->current != '=') return '='; - else { next(ls); return TK_EQ; } - } - case '<': { - next(ls); - if (ls->current != '=') return '<'; - else { next(ls); return TK_LE; } - } - case '>': { - next(ls); - if (ls->current != '=') return '>'; - else { next(ls); return TK_GE; } - } - case '~': { - next(ls); - if (ls->current != '=') return '~'; - else { next(ls); return TK_NE; } - } - case '"': - case '\'': { - read_string(ls, ls->current, seminfo); - return TK_STRING; - } - case '.': { - save_and_next(ls); - if (check_next(ls, ".")) { - if (check_next(ls, ".")) - return TK_DOTS; /* ... */ - else return TK_CONCAT; /* .. */ - } - else if (!isdigit(ls->current)) return '.'; - else { - read_numeral(ls, seminfo); - return TK_NUMBER; - } - } - case EOZ: { - return TK_EOS; - } - default: { - if (isspace(ls->current)) { - lua_assert(!currIsNewline(ls)); - next(ls); - continue; - } - else if (isdigit(ls->current)) { - read_numeral(ls, seminfo); - return TK_NUMBER; - } - else if (isalpha(ls->current) || ls->current == '_') { - /* identifier or reserved word */ - TString *ts; - do { - save_and_next(ls); - } while (isalnum(ls->current) || ls->current == '_'); - ts = luaX_newstring(ls, luaZ_buffer(ls->buff), - luaZ_bufflen(ls->buff)); - if (ts->tsv.reserved > 0) /* reserved word? */ - return ts->tsv.reserved - 1 + FIRST_RESERVED; - else { - seminfo->ts = ts; - return TK_NAME; - } - } - else { - int c = ls->current; - next(ls); - return c; /* single-char tokens (+ - / ...) */ - } - } - } - } -} - - -void luaX_next (LexState *ls) { - ls->lastline = ls->linenumber; - if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */ - ls->t = ls->lookahead; /* use this one */ - ls->lookahead.token = TK_EOS; /* and discharge it */ - } - else - ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */ -} - - -void luaX_lookahead (LexState *ls) { - lua_assert(ls->lookahead.token == TK_EOS); - ls->lookahead.token = llex(ls, &ls->lookahead.seminfo); -} - diff --git a/Utilities/lua-5.1.5/src/llex.h b/Utilities/lua-5.1.5/src/llex.h deleted file mode 100644 index a9201cee4..000000000 --- a/Utilities/lua-5.1.5/src/llex.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -** $Id: llex.h,v 1.58.1.1 2007/12/27 13:02:25 roberto Exp $ -** Lexical Analyzer -** See Copyright Notice in lua.h -*/ - -#ifndef llex_h -#define llex_h - -#include "lobject.h" -#include "lzio.h" - - -#define FIRST_RESERVED 257 - -/* maximum length of a reserved word */ -#define TOKEN_LEN (sizeof("function")/sizeof(char)) - - -/* -* WARNING: if you change the order of this enumeration, -* grep "ORDER RESERVED" -*/ -enum RESERVED { - /* terminal symbols denoted by reserved words */ - TK_AND = FIRST_RESERVED, TK_BREAK, - TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION, - TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT, - TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE, - /* other terminal symbols */ - TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_NUMBER, - TK_NAME, TK_STRING, TK_EOS -}; - -/* number of reserved words */ -#define NUM_RESERVED (cast(int, TK_WHILE-FIRST_RESERVED+1)) - - -/* array with token `names' */ -LUAI_DATA const char *const luaX_tokens []; - - -typedef union { - lua_Number r; - TString *ts; -} SemInfo; /* semantics information */ - - -typedef struct Token { - int token; - SemInfo seminfo; -} Token; - - -typedef struct LexState { - int current; /* current character (charint) */ - int linenumber; /* input line counter */ - int lastline; /* line of last token `consumed' */ - Token t; /* current token */ - Token lookahead; /* look ahead token */ - struct FuncState *fs; /* `FuncState' is private to the parser */ - struct lua_State *L; - ZIO *z; /* input stream */ - Mbuffer *buff; /* buffer for tokens */ - TString *source; /* current source name */ - char decpoint; /* locale decimal point */ -} LexState; - - -LUAI_FUNC void luaX_init (lua_State *L); -LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, - TString *source); -LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l); -LUAI_FUNC void luaX_next (LexState *ls); -LUAI_FUNC void luaX_lookahead (LexState *ls); -LUAI_FUNC void luaX_lexerror (LexState *ls, const char *msg, int token); -LUAI_FUNC void luaX_syntaxerror (LexState *ls, const char *s); -LUAI_FUNC const char *luaX_token2str (LexState *ls, int token); - - -#endif diff --git a/Utilities/lua-5.1.5/src/llimits.h b/Utilities/lua-5.1.5/src/llimits.h deleted file mode 100644 index ca8dcb722..000000000 --- a/Utilities/lua-5.1.5/src/llimits.h +++ /dev/null @@ -1,128 +0,0 @@ -/* -** $Id: llimits.h,v 1.69.1.1 2007/12/27 13:02:25 roberto Exp $ -** Limits, basic types, and some other `installation-dependent' definitions -** See Copyright Notice in lua.h -*/ - -#ifndef llimits_h -#define llimits_h - - -#include -#include - - -#include "lua.h" - - -typedef LUAI_UINT32 lu_int32; - -typedef LUAI_UMEM lu_mem; - -typedef LUAI_MEM l_mem; - - - -/* chars used as small naturals (so that `char' is reserved for characters) */ -typedef unsigned char lu_byte; - - -#define MAX_SIZET ((size_t)(~(size_t)0)-2) - -#define MAX_LUMEM ((lu_mem)(~(lu_mem)0)-2) - - -#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */ - -/* -** conversion of pointer to integer -** this is for hashing only; there is no problem if the integer -** cannot hold the whole pointer value -*/ -#define IntPoint(p) ((unsigned int)(lu_mem)(p)) - - - -/* type to ensure maximum alignment */ -typedef LUAI_USER_ALIGNMENT_T L_Umaxalign; - - -/* result of a `usual argument conversion' over lua_Number */ -typedef LUAI_UACNUMBER l_uacNumber; - - -/* internal assertions for in-house debugging */ -#ifdef lua_assert - -#define check_exp(c,e) (lua_assert(c), (e)) -#define api_check(l,e) lua_assert(e) - -#else - -#define lua_assert(c) ((void)0) -#define check_exp(c,e) (e) -#define api_check luai_apicheck - -#endif - - -#ifndef UNUSED -#define UNUSED(x) ((void)(x)) /* to avoid warnings */ -#endif - - -#ifndef cast -#define cast(t, exp) ((t)(exp)) -#endif - -#define cast_byte(i) cast(lu_byte, (i)) -#define cast_num(i) cast(lua_Number, (i)) -#define cast_int(i) cast(int, (i)) - - - -/* -** type for virtual-machine instructions -** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h) -*/ -typedef lu_int32 Instruction; - - - -/* maximum stack for a Lua function */ -#define MAXSTACK 250 - - - -/* minimum size for the string table (must be power of 2) */ -#ifndef MINSTRTABSIZE -#define MINSTRTABSIZE 32 -#endif - - -/* minimum size for string buffer */ -#ifndef LUA_MINBUFFER -#define LUA_MINBUFFER 32 -#endif - - -#ifndef lua_lock -#define lua_lock(L) ((void) 0) -#define lua_unlock(L) ((void) 0) -#endif - -#ifndef luai_threadyield -#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);} -#endif - - -/* -** macro to control inclusion of some hard tests on stack reallocation -*/ -#ifndef HARDSTACKTESTS -#define condhardstacktests(x) ((void)0) -#else -#define condhardstacktests(x) x -#endif - -#endif diff --git a/Utilities/lua-5.1.5/src/lmathlib.c b/Utilities/lua-5.1.5/src/lmathlib.c deleted file mode 100644 index 441fbf736..000000000 --- a/Utilities/lua-5.1.5/src/lmathlib.c +++ /dev/null @@ -1,263 +0,0 @@ -/* -** $Id: lmathlib.c,v 1.67.1.1 2007/12/27 13:02:25 roberto Exp $ -** Standard mathematical library -** See Copyright Notice in lua.h -*/ - - -#include -#include - -#define lmathlib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - -#undef PI -#define PI (3.14159265358979323846) -#define RADIANS_PER_DEGREE (PI/180.0) - - - -static int math_abs (lua_State *L) { - lua_pushnumber(L, fabs(luaL_checknumber(L, 1))); - return 1; -} - -static int math_sin (lua_State *L) { - lua_pushnumber(L, sin(luaL_checknumber(L, 1))); - return 1; -} - -static int math_sinh (lua_State *L) { - lua_pushnumber(L, sinh(luaL_checknumber(L, 1))); - return 1; -} - -static int math_cos (lua_State *L) { - lua_pushnumber(L, cos(luaL_checknumber(L, 1))); - return 1; -} - -static int math_cosh (lua_State *L) { - lua_pushnumber(L, cosh(luaL_checknumber(L, 1))); - return 1; -} - -static int math_tan (lua_State *L) { - lua_pushnumber(L, tan(luaL_checknumber(L, 1))); - return 1; -} - -static int math_tanh (lua_State *L) { - lua_pushnumber(L, tanh(luaL_checknumber(L, 1))); - return 1; -} - -static int math_asin (lua_State *L) { - lua_pushnumber(L, asin(luaL_checknumber(L, 1))); - return 1; -} - -static int math_acos (lua_State *L) { - lua_pushnumber(L, acos(luaL_checknumber(L, 1))); - return 1; -} - -static int math_atan (lua_State *L) { - lua_pushnumber(L, atan(luaL_checknumber(L, 1))); - return 1; -} - -static int math_atan2 (lua_State *L) { - lua_pushnumber(L, atan2(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); - return 1; -} - -static int math_ceil (lua_State *L) { - lua_pushnumber(L, ceil(luaL_checknumber(L, 1))); - return 1; -} - -static int math_floor (lua_State *L) { - lua_pushnumber(L, floor(luaL_checknumber(L, 1))); - return 1; -} - -static int math_fmod (lua_State *L) { - lua_pushnumber(L, fmod(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); - return 1; -} - -static int math_modf (lua_State *L) { - double ip; - double fp = modf(luaL_checknumber(L, 1), &ip); - lua_pushnumber(L, ip); - lua_pushnumber(L, fp); - return 2; -} - -static int math_sqrt (lua_State *L) { - lua_pushnumber(L, sqrt(luaL_checknumber(L, 1))); - return 1; -} - -static int math_pow (lua_State *L) { - lua_pushnumber(L, pow(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); - return 1; -} - -static int math_log (lua_State *L) { - lua_pushnumber(L, log(luaL_checknumber(L, 1))); - return 1; -} - -static int math_log10 (lua_State *L) { - lua_pushnumber(L, log10(luaL_checknumber(L, 1))); - return 1; -} - -static int math_exp (lua_State *L) { - lua_pushnumber(L, exp(luaL_checknumber(L, 1))); - return 1; -} - -static int math_deg (lua_State *L) { - lua_pushnumber(L, luaL_checknumber(L, 1)/RADIANS_PER_DEGREE); - return 1; -} - -static int math_rad (lua_State *L) { - lua_pushnumber(L, luaL_checknumber(L, 1)*RADIANS_PER_DEGREE); - return 1; -} - -static int math_frexp (lua_State *L) { - int e; - lua_pushnumber(L, frexp(luaL_checknumber(L, 1), &e)); - lua_pushinteger(L, e); - return 2; -} - -static int math_ldexp (lua_State *L) { - lua_pushnumber(L, ldexp(luaL_checknumber(L, 1), luaL_checkint(L, 2))); - return 1; -} - - - -static int math_min (lua_State *L) { - int n = lua_gettop(L); /* number of arguments */ - lua_Number dmin = luaL_checknumber(L, 1); - int i; - for (i=2; i<=n; i++) { - lua_Number d = luaL_checknumber(L, i); - if (d < dmin) - dmin = d; - } - lua_pushnumber(L, dmin); - return 1; -} - - -static int math_max (lua_State *L) { - int n = lua_gettop(L); /* number of arguments */ - lua_Number dmax = luaL_checknumber(L, 1); - int i; - for (i=2; i<=n; i++) { - lua_Number d = luaL_checknumber(L, i); - if (d > dmax) - dmax = d; - } - lua_pushnumber(L, dmax); - return 1; -} - - -static int math_random (lua_State *L) { - /* the `%' avoids the (rare) case of r==1, and is needed also because on - some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */ - lua_Number r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX; - switch (lua_gettop(L)) { /* check number of arguments */ - case 0: { /* no arguments */ - lua_pushnumber(L, r); /* Number between 0 and 1 */ - break; - } - case 1: { /* only upper limit */ - int u = luaL_checkint(L, 1); - luaL_argcheck(L, 1<=u, 1, "interval is empty"); - lua_pushnumber(L, floor(r*u)+1); /* int between 1 and `u' */ - break; - } - case 2: { /* lower and upper limits */ - int l = luaL_checkint(L, 1); - int u = luaL_checkint(L, 2); - luaL_argcheck(L, l<=u, 2, "interval is empty"); - lua_pushnumber(L, floor(r*(u-l+1))+l); /* int between `l' and `u' */ - break; - } - default: return luaL_error(L, "wrong number of arguments"); - } - return 1; -} - - -static int math_randomseed (lua_State *L) { - srand(luaL_checkint(L, 1)); - return 0; -} - - -static const luaL_Reg mathlib[] = { - {"abs", math_abs}, - {"acos", math_acos}, - {"asin", math_asin}, - {"atan2", math_atan2}, - {"atan", math_atan}, - {"ceil", math_ceil}, - {"cosh", math_cosh}, - {"cos", math_cos}, - {"deg", math_deg}, - {"exp", math_exp}, - {"floor", math_floor}, - {"fmod", math_fmod}, - {"frexp", math_frexp}, - {"ldexp", math_ldexp}, - {"log10", math_log10}, - {"log", math_log}, - {"max", math_max}, - {"min", math_min}, - {"modf", math_modf}, - {"pow", math_pow}, - {"rad", math_rad}, - {"random", math_random}, - {"randomseed", math_randomseed}, - {"sinh", math_sinh}, - {"sin", math_sin}, - {"sqrt", math_sqrt}, - {"tanh", math_tanh}, - {"tan", math_tan}, - {NULL, NULL} -}; - - -/* -** Open math library -*/ -LUALIB_API int luaopen_math (lua_State *L) { - luaL_register(L, LUA_MATHLIBNAME, mathlib); - lua_pushnumber(L, PI); - lua_setfield(L, -2, "pi"); - lua_pushnumber(L, HUGE_VAL); - lua_setfield(L, -2, "huge"); -#if defined(LUA_COMPAT_MOD) - lua_getfield(L, -1, "fmod"); - lua_setfield(L, -2, "mod"); -#endif - return 1; -} - diff --git a/Utilities/lua-5.1.5/src/lmem.c b/Utilities/lua-5.1.5/src/lmem.c deleted file mode 100644 index ae7d8c965..000000000 --- a/Utilities/lua-5.1.5/src/lmem.c +++ /dev/null @@ -1,86 +0,0 @@ -/* -** $Id: lmem.c,v 1.70.1.1 2007/12/27 13:02:25 roberto Exp $ -** Interface to Memory Manager -** See Copyright Notice in lua.h -*/ - - -#include - -#define lmem_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" - - - -/* -** About the realloc function: -** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize); -** (`osize' is the old size, `nsize' is the new size) -** -** Lua ensures that (ptr == NULL) iff (osize == 0). -** -** * frealloc(ud, NULL, 0, x) creates a new block of size `x' -** -** * frealloc(ud, p, x, 0) frees the block `p' -** (in this specific case, frealloc must return NULL). -** particularly, frealloc(ud, NULL, 0, 0) does nothing -** (which is equivalent to free(NULL) in ANSI C) -** -** frealloc returns NULL if it cannot create or reallocate the area -** (any reallocation to an equal or smaller size cannot fail!) -*/ - - - -#define MINSIZEARRAY 4 - - -void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems, - int limit, const char *errormsg) { - void *newblock; - int newsize; - if (*size >= limit/2) { /* cannot double it? */ - if (*size >= limit) /* cannot grow even a little? */ - luaG_runerror(L, errormsg); - newsize = limit; /* still have at least one free place */ - } - else { - newsize = (*size)*2; - if (newsize < MINSIZEARRAY) - newsize = MINSIZEARRAY; /* minimum size */ - } - newblock = luaM_reallocv(L, block, *size, newsize, size_elems); - *size = newsize; /* update only when everything else is OK */ - return newblock; -} - - -void *luaM_toobig (lua_State *L) { - luaG_runerror(L, "memory allocation error: block too big"); - return NULL; /* to avoid warnings */ -} - - - -/* -** generic allocation routine. -*/ -void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { - global_State *g = G(L); - lua_assert((osize == 0) == (block == NULL)); - block = (*g->frealloc)(g->ud, block, osize, nsize); - if (block == NULL && nsize > 0) - luaD_throw(L, LUA_ERRMEM); - lua_assert((nsize == 0) == (block == NULL)); - g->totalbytes = (g->totalbytes - osize) + nsize; - return block; -} - diff --git a/Utilities/lua-5.1.5/src/lmem.h b/Utilities/lua-5.1.5/src/lmem.h deleted file mode 100644 index 7c2dcb322..000000000 --- a/Utilities/lua-5.1.5/src/lmem.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -** $Id: lmem.h,v 1.31.1.1 2007/12/27 13:02:25 roberto Exp $ -** Interface to Memory Manager -** See Copyright Notice in lua.h -*/ - -#ifndef lmem_h -#define lmem_h - - -#include - -#include "llimits.h" -#include "lua.h" - -#define MEMERRMSG "not enough memory" - - -#define luaM_reallocv(L,b,on,n,e) \ - ((cast(size_t, (n)+1) <= MAX_SIZET/(e)) ? /* +1 to avoid warnings */ \ - luaM_realloc_(L, (b), (on)*(e), (n)*(e)) : \ - luaM_toobig(L)) - -#define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0) -#define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0) -#define luaM_freearray(L, b, n, t) luaM_reallocv(L, (b), n, 0, sizeof(t)) - -#define luaM_malloc(L,t) luaM_realloc_(L, NULL, 0, (t)) -#define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t))) -#define luaM_newvector(L,n,t) \ - cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t))) - -#define luaM_growvector(L,v,nelems,size,t,limit,e) \ - if ((nelems)+1 > (size)) \ - ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e))) - -#define luaM_reallocvector(L, v,oldn,n,t) \ - ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t)))) - - -LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize, - size_t size); -LUAI_FUNC void *luaM_toobig (lua_State *L); -LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int *size, - size_t size_elem, int limit, - const char *errormsg); - -#endif - diff --git a/Utilities/lua-5.1.5/src/loadlib.c b/Utilities/lua-5.1.5/src/loadlib.c deleted file mode 100644 index 6158c5353..000000000 --- a/Utilities/lua-5.1.5/src/loadlib.c +++ /dev/null @@ -1,666 +0,0 @@ -/* -** $Id: loadlib.c,v 1.52.1.4 2009/09/09 13:17:16 roberto Exp $ -** Dynamic library loader for Lua -** See Copyright Notice in lua.h -** -** This module contains an implementation of loadlib for Unix systems -** that have dlfcn, an implementation for Darwin (Mac OS X), an -** implementation for Windows, and a stub for other systems. -*/ - - -#include -#include - - -#define loadlib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - -/* prefix for open functions in C libraries */ -#define LUA_POF "luaopen_" - -/* separator for open functions in C libraries */ -#define LUA_OFSEP "_" - - -#define LIBPREFIX "LOADLIB: " - -#define POF LUA_POF -#define LIB_FAIL "open" - - -/* error codes for ll_loadfunc */ -#define ERRLIB 1 -#define ERRFUNC 2 - -#define setprogdir(L) ((void)0) - - -static void ll_unloadlib (void *lib); -static void *ll_load (lua_State *L, const char *path); -static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym); - - - -#if defined(LUA_DL_DLOPEN) -/* -** {======================================================================== -** This is an implementation of loadlib based on the dlfcn interface. -** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD, -** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least -** as an emulation layer on top of native functions. -** ========================================================================= -*/ - -#include - -static void ll_unloadlib (void *lib) { - dlclose(lib); -} - - -static void *ll_load (lua_State *L, const char *path) { - void *lib = dlopen(path, RTLD_NOW); - if (lib == NULL) lua_pushstring(L, dlerror()); - return lib; -} - - -static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { - lua_CFunction f = (lua_CFunction)dlsym(lib, sym); - if (f == NULL) lua_pushstring(L, dlerror()); - return f; -} - -/* }====================================================== */ - - - -#elif defined(LUA_DL_DLL) -/* -** {====================================================================== -** This is an implementation of loadlib for Windows using native functions. -** ======================================================================= -*/ - -#include - - -#undef setprogdir - -static void setprogdir (lua_State *L) { - char buff[MAX_PATH + 1]; - char *lb; - DWORD nsize = sizeof(buff)/sizeof(char); - DWORD n = GetModuleFileNameA(NULL, buff, nsize); - if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) - luaL_error(L, "unable to get ModuleFileName"); - else { - *lb = '\0'; - luaL_gsub(L, lua_tostring(L, -1), LUA_EXECDIR, buff); - lua_remove(L, -2); /* remove original string */ - } -} - - -static void pusherror (lua_State *L) { - int error = GetLastError(); - char buffer[128]; - if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, error, 0, buffer, sizeof(buffer), NULL)) - lua_pushstring(L, buffer); - else - lua_pushfstring(L, "system error %d\n", error); -} - -static void ll_unloadlib (void *lib) { - FreeLibrary((HINSTANCE)lib); -} - - -static void *ll_load (lua_State *L, const char *path) { - HINSTANCE lib = LoadLibraryA(path); - if (lib == NULL) pusherror(L); - return lib; -} - - -static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { - lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym); - if (f == NULL) pusherror(L); - return f; -} - -/* }====================================================== */ - - - -#elif defined(LUA_DL_DYLD) -/* -** {====================================================================== -** Native Mac OS X / Darwin Implementation -** ======================================================================= -*/ - -#include - - -/* Mac appends a `_' before C function names */ -#undef POF -#define POF "_" LUA_POF - - -static void pusherror (lua_State *L) { - const char *err_str; - const char *err_file; - NSLinkEditErrors err; - int err_num; - NSLinkEditError(&err, &err_num, &err_file, &err_str); - lua_pushstring(L, err_str); -} - - -static const char *errorfromcode (NSObjectFileImageReturnCode ret) { - switch (ret) { - case NSObjectFileImageInappropriateFile: - return "file is not a bundle"; - case NSObjectFileImageArch: - return "library is for wrong CPU type"; - case NSObjectFileImageFormat: - return "bad format"; - case NSObjectFileImageAccess: - return "cannot access file"; - case NSObjectFileImageFailure: - default: - return "unable to load library"; - } -} - - -static void ll_unloadlib (void *lib) { - NSUnLinkModule((NSModule)lib, NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES); -} - - -static void *ll_load (lua_State *L, const char *path) { - NSObjectFileImage img; - NSObjectFileImageReturnCode ret; - /* this would be a rare case, but prevents crashing if it happens */ - if(!_dyld_present()) { - lua_pushliteral(L, "dyld not present"); - return NULL; - } - ret = NSCreateObjectFileImageFromFile(path, &img); - if (ret == NSObjectFileImageSuccess) { - NSModule mod = NSLinkModule(img, path, NSLINKMODULE_OPTION_PRIVATE | - NSLINKMODULE_OPTION_RETURN_ON_ERROR); - NSDestroyObjectFileImage(img); - if (mod == NULL) pusherror(L); - return mod; - } - lua_pushstring(L, errorfromcode(ret)); - return NULL; -} - - -static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { - NSSymbol nss = NSLookupSymbolInModule((NSModule)lib, sym); - if (nss == NULL) { - lua_pushfstring(L, "symbol " LUA_QS " not found", sym); - return NULL; - } - return (lua_CFunction)NSAddressOfSymbol(nss); -} - -/* }====================================================== */ - - - -#else -/* -** {====================================================== -** Fallback for other systems -** ======================================================= -*/ - -#undef LIB_FAIL -#define LIB_FAIL "absent" - - -#define DLMSG "dynamic libraries not enabled; check your Lua installation" - - -static void ll_unloadlib (void *lib) { - (void)lib; /* to avoid warnings */ -} - - -static void *ll_load (lua_State *L, const char *path) { - (void)path; /* to avoid warnings */ - lua_pushliteral(L, DLMSG); - return NULL; -} - - -static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { - (void)lib; (void)sym; /* to avoid warnings */ - lua_pushliteral(L, DLMSG); - return NULL; -} - -/* }====================================================== */ -#endif - - - -static void **ll_register (lua_State *L, const char *path) { - void **plib; - lua_pushfstring(L, "%s%s", LIBPREFIX, path); - lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */ - if (!lua_isnil(L, -1)) /* is there an entry? */ - plib = (void **)lua_touserdata(L, -1); - else { /* no entry yet; create one */ - lua_pop(L, 1); - plib = (void **)lua_newuserdata(L, sizeof(const void *)); - *plib = NULL; - luaL_getmetatable(L, "_LOADLIB"); - lua_setmetatable(L, -2); - lua_pushfstring(L, "%s%s", LIBPREFIX, path); - lua_pushvalue(L, -2); - lua_settable(L, LUA_REGISTRYINDEX); - } - return plib; -} - - -/* -** __gc tag method: calls library's `ll_unloadlib' function with the lib -** handle -*/ -static int gctm (lua_State *L) { - void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB"); - if (*lib) ll_unloadlib(*lib); - *lib = NULL; /* mark library as closed */ - return 0; -} - - -static int ll_loadfunc (lua_State *L, const char *path, const char *sym) { - void **reg = ll_register(L, path); - if (*reg == NULL) *reg = ll_load(L, path); - if (*reg == NULL) - return ERRLIB; /* unable to load library */ - else { - lua_CFunction f = ll_sym(L, *reg, sym); - if (f == NULL) - return ERRFUNC; /* unable to find function */ - lua_pushcfunction(L, f); - return 0; /* return function */ - } -} - - -static int ll_loadlib (lua_State *L) { - const char *path = luaL_checkstring(L, 1); - const char *init = luaL_checkstring(L, 2); - int stat = ll_loadfunc(L, path, init); - if (stat == 0) /* no errors? */ - return 1; /* return the loaded function */ - else { /* error; error message is on stack top */ - lua_pushnil(L); - lua_insert(L, -2); - lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init"); - return 3; /* return nil, error message, and where */ - } -} - - - -/* -** {====================================================== -** 'require' function -** ======================================================= -*/ - - -static int readable (const char *filename) { - FILE *f = fopen(filename, "r"); /* try to open file */ - if (f == NULL) return 0; /* open failed */ - fclose(f); - return 1; -} - - -static const char *pushnexttemplate (lua_State *L, const char *path) { - const char *l; - while (*path == *LUA_PATHSEP) path++; /* skip separators */ - if (*path == '\0') return NULL; /* no more templates */ - l = strchr(path, *LUA_PATHSEP); /* find next separator */ - if (l == NULL) l = path + strlen(path); - lua_pushlstring(L, path, l - path); /* template */ - return l; -} - - -static const char *findfile (lua_State *L, const char *name, - const char *pname) { - const char *path; - name = luaL_gsub(L, name, ".", LUA_DIRSEP); - lua_getfield(L, LUA_ENVIRONINDEX, pname); - path = lua_tostring(L, -1); - if (path == NULL) - luaL_error(L, LUA_QL("package.%s") " must be a string", pname); - lua_pushliteral(L, ""); /* error accumulator */ - while ((path = pushnexttemplate(L, path)) != NULL) { - const char *filename; - filename = luaL_gsub(L, lua_tostring(L, -1), LUA_PATH_MARK, name); - lua_remove(L, -2); /* remove path template */ - if (readable(filename)) /* does file exist and is readable? */ - return filename; /* return that file name */ - lua_pushfstring(L, "\n\tno file " LUA_QS, filename); - lua_remove(L, -2); /* remove file name */ - lua_concat(L, 2); /* add entry to possible error message */ - } - return NULL; /* not found */ -} - - -static void loaderror (lua_State *L, const char *filename) { - luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s", - lua_tostring(L, 1), filename, lua_tostring(L, -1)); -} - - -static int loader_Lua (lua_State *L) { - const char *filename; - const char *name = luaL_checkstring(L, 1); - filename = findfile(L, name, "path"); - if (filename == NULL) return 1; /* library not found in this path */ - if (luaL_loadfile(L, filename) != 0) - loaderror(L, filename); - return 1; /* library loaded successfully */ -} - - -static const char *mkfuncname (lua_State *L, const char *modname) { - const char *funcname; - const char *mark = strchr(modname, *LUA_IGMARK); - if (mark) modname = mark + 1; - funcname = luaL_gsub(L, modname, ".", LUA_OFSEP); - funcname = lua_pushfstring(L, POF"%s", funcname); - lua_remove(L, -2); /* remove 'gsub' result */ - return funcname; -} - - -static int loader_C (lua_State *L) { - const char *funcname; - const char *name = luaL_checkstring(L, 1); - const char *filename = findfile(L, name, "cpath"); - if (filename == NULL) return 1; /* library not found in this path */ - funcname = mkfuncname(L, name); - if (ll_loadfunc(L, filename, funcname) != 0) - loaderror(L, filename); - return 1; /* library loaded successfully */ -} - - -static int loader_Croot (lua_State *L) { - const char *funcname; - const char *filename; - const char *name = luaL_checkstring(L, 1); - const char *p = strchr(name, '.'); - int stat; - if (p == NULL) return 0; /* is root */ - lua_pushlstring(L, name, p - name); - filename = findfile(L, lua_tostring(L, -1), "cpath"); - if (filename == NULL) return 1; /* root not found */ - funcname = mkfuncname(L, name); - if ((stat = ll_loadfunc(L, filename, funcname)) != 0) { - if (stat != ERRFUNC) loaderror(L, filename); /* real error */ - lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS, - name, filename); - return 1; /* function not found */ - } - return 1; -} - - -static int loader_preload (lua_State *L) { - const char *name = luaL_checkstring(L, 1); - lua_getfield(L, LUA_ENVIRONINDEX, "preload"); - if (!lua_istable(L, -1)) - luaL_error(L, LUA_QL("package.preload") " must be a table"); - lua_getfield(L, -1, name); - if (lua_isnil(L, -1)) /* not found? */ - lua_pushfstring(L, "\n\tno field package.preload['%s']", name); - return 1; -} - - -static const int sentinel_ = 0; -#define sentinel ((void *)&sentinel_) - - -static int ll_require (lua_State *L) { - const char *name = luaL_checkstring(L, 1); - int i; - lua_settop(L, 1); /* _LOADED table will be at index 2 */ - lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); - lua_getfield(L, 2, name); - if (lua_toboolean(L, -1)) { /* is it there? */ - if (lua_touserdata(L, -1) == sentinel) /* check loops */ - luaL_error(L, "loop or previous error loading module " LUA_QS, name); - return 1; /* package is already loaded */ - } - /* else must load it; iterate over available loaders */ - lua_getfield(L, LUA_ENVIRONINDEX, "loaders"); - if (!lua_istable(L, -1)) - luaL_error(L, LUA_QL("package.loaders") " must be a table"); - lua_pushliteral(L, ""); /* error message accumulator */ - for (i=1; ; i++) { - lua_rawgeti(L, -2, i); /* get a loader */ - if (lua_isnil(L, -1)) - luaL_error(L, "module " LUA_QS " not found:%s", - name, lua_tostring(L, -2)); - lua_pushstring(L, name); - lua_call(L, 1, 1); /* call it */ - if (lua_isfunction(L, -1)) /* did it find module? */ - break; /* module loaded successfully */ - else if (lua_isstring(L, -1)) /* loader returned error message? */ - lua_concat(L, 2); /* accumulate it */ - else - lua_pop(L, 1); - } - lua_pushlightuserdata(L, sentinel); - lua_setfield(L, 2, name); /* _LOADED[name] = sentinel */ - lua_pushstring(L, name); /* pass name as argument to module */ - lua_call(L, 1, 1); /* run loaded module */ - if (!lua_isnil(L, -1)) /* non-nil return? */ - lua_setfield(L, 2, name); /* _LOADED[name] = returned value */ - lua_getfield(L, 2, name); - if (lua_touserdata(L, -1) == sentinel) { /* module did not set a value? */ - lua_pushboolean(L, 1); /* use true as result */ - lua_pushvalue(L, -1); /* extra copy to be returned */ - lua_setfield(L, 2, name); /* _LOADED[name] = true */ - } - return 1; -} - -/* }====================================================== */ - - - -/* -** {====================================================== -** 'module' function -** ======================================================= -*/ - - -static void setfenv (lua_State *L) { - lua_Debug ar; - if (lua_getstack(L, 1, &ar) == 0 || - lua_getinfo(L, "f", &ar) == 0 || /* get calling function */ - lua_iscfunction(L, -1)) - luaL_error(L, LUA_QL("module") " not called from a Lua function"); - lua_pushvalue(L, -2); - lua_setfenv(L, -2); - lua_pop(L, 1); -} - - -static void dooptions (lua_State *L, int n) { - int i; - for (i = 2; i <= n; i++) { - lua_pushvalue(L, i); /* get option (a function) */ - lua_pushvalue(L, -2); /* module */ - lua_call(L, 1, 0); - } -} - - -static void modinit (lua_State *L, const char *modname) { - const char *dot; - lua_pushvalue(L, -1); - lua_setfield(L, -2, "_M"); /* module._M = module */ - lua_pushstring(L, modname); - lua_setfield(L, -2, "_NAME"); - dot = strrchr(modname, '.'); /* look for last dot in module name */ - if (dot == NULL) dot = modname; - else dot++; - /* set _PACKAGE as package name (full module name minus last part) */ - lua_pushlstring(L, modname, dot - modname); - lua_setfield(L, -2, "_PACKAGE"); -} - - -static int ll_module (lua_State *L) { - const char *modname = luaL_checkstring(L, 1); - int loaded = lua_gettop(L) + 1; /* index of _LOADED table */ - lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); - lua_getfield(L, loaded, modname); /* get _LOADED[modname] */ - if (!lua_istable(L, -1)) { /* not found? */ - lua_pop(L, 1); /* remove previous result */ - /* try global variable (and create one if it does not exist) */ - if (luaL_findtable(L, LUA_GLOBALSINDEX, modname, 1) != NULL) - return luaL_error(L, "name conflict for module " LUA_QS, modname); - lua_pushvalue(L, -1); - lua_setfield(L, loaded, modname); /* _LOADED[modname] = new table */ - } - /* check whether table already has a _NAME field */ - lua_getfield(L, -1, "_NAME"); - if (!lua_isnil(L, -1)) /* is table an initialized module? */ - lua_pop(L, 1); - else { /* no; initialize it */ - lua_pop(L, 1); - modinit(L, modname); - } - lua_pushvalue(L, -1); - setfenv(L); - dooptions(L, loaded - 1); - return 0; -} - - -static int ll_seeall (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - if (!lua_getmetatable(L, 1)) { - lua_createtable(L, 0, 1); /* create new metatable */ - lua_pushvalue(L, -1); - lua_setmetatable(L, 1); - } - lua_pushvalue(L, LUA_GLOBALSINDEX); - lua_setfield(L, -2, "__index"); /* mt.__index = _G */ - return 0; -} - - -/* }====================================================== */ - - - -/* auxiliary mark (for internal use) */ -#define AUXMARK "\1" - -static void setpath (lua_State *L, const char *fieldname, const char *envname, - const char *def) { - const char *path = getenv(envname); - if (path == NULL) /* no environment variable? */ - lua_pushstring(L, def); /* use default */ - else { - /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */ - path = luaL_gsub(L, path, LUA_PATHSEP LUA_PATHSEP, - LUA_PATHSEP AUXMARK LUA_PATHSEP); - luaL_gsub(L, path, AUXMARK, def); - lua_remove(L, -2); - } - setprogdir(L); - lua_setfield(L, -2, fieldname); -} - - -static const luaL_Reg pk_funcs[] = { - {"loadlib", ll_loadlib}, - {"seeall", ll_seeall}, - {NULL, NULL} -}; - - -static const luaL_Reg ll_funcs[] = { - {"module", ll_module}, - {"require", ll_require}, - {NULL, NULL} -}; - - -static const lua_CFunction loaders[] = - {loader_preload, loader_Lua, loader_C, loader_Croot, NULL}; - - -LUALIB_API int luaopen_package (lua_State *L) { - int i; - /* create new type _LOADLIB */ - luaL_newmetatable(L, "_LOADLIB"); - lua_pushcfunction(L, gctm); - lua_setfield(L, -2, "__gc"); - /* create `package' table */ - luaL_register(L, LUA_LOADLIBNAME, pk_funcs); -#if defined(LUA_COMPAT_LOADLIB) - lua_getfield(L, -1, "loadlib"); - lua_setfield(L, LUA_GLOBALSINDEX, "loadlib"); -#endif - lua_pushvalue(L, -1); - lua_replace(L, LUA_ENVIRONINDEX); - /* create `loaders' table */ - lua_createtable(L, sizeof(loaders)/sizeof(loaders[0]) - 1, 0); - /* fill it with pre-defined loaders */ - for (i=0; loaders[i] != NULL; i++) { - lua_pushcfunction(L, loaders[i]); - lua_rawseti(L, -2, i+1); - } - lua_setfield(L, -2, "loaders"); /* put it in field `loaders' */ - setpath(L, "path", LUA_PATH, LUA_PATH_DEFAULT); /* set field `path' */ - setpath(L, "cpath", LUA_CPATH, LUA_CPATH_DEFAULT); /* set field `cpath' */ - /* store config information */ - lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATHSEP "\n" LUA_PATH_MARK "\n" - LUA_EXECDIR "\n" LUA_IGMARK); - lua_setfield(L, -2, "config"); - /* set field `loaded' */ - luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 2); - lua_setfield(L, -2, "loaded"); - /* set field `preload' */ - lua_newtable(L); - lua_setfield(L, -2, "preload"); - lua_pushvalue(L, LUA_GLOBALSINDEX); - luaL_register(L, NULL, ll_funcs); /* open lib into global table */ - lua_pop(L, 1); - return 1; /* return 'package' table */ -} - diff --git a/Utilities/lua-5.1.5/src/lobject.c b/Utilities/lua-5.1.5/src/lobject.c deleted file mode 100644 index 4ff50732a..000000000 --- a/Utilities/lua-5.1.5/src/lobject.c +++ /dev/null @@ -1,214 +0,0 @@ -/* -** $Id: lobject.c,v 2.22.1.1 2007/12/27 13:02:25 roberto Exp $ -** Some generic functions over Lua objects -** See Copyright Notice in lua.h -*/ - -#include -#include -#include -#include -#include - -#define lobject_c -#define LUA_CORE - -#include "lua.h" - -#include "ldo.h" -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" -#include "lstring.h" -#include "lvm.h" - - - -const TValue luaO_nilobject_ = {{NULL}, LUA_TNIL}; - - -/* -** converts an integer to a "floating point byte", represented as -** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if -** eeeee != 0 and (xxx) otherwise. -*/ -int luaO_int2fb (unsigned int x) { - int e = 0; /* expoent */ - while (x >= 16) { - x = (x+1) >> 1; - e++; - } - if (x < 8) return x; - else return ((e+1) << 3) | (cast_int(x) - 8); -} - - -/* converts back */ -int luaO_fb2int (int x) { - int e = (x >> 3) & 31; - if (e == 0) return x; - else return ((x & 7)+8) << (e - 1); -} - - -int luaO_log2 (unsigned int x) { - static const lu_byte log_2[256] = { - 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,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, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 - }; - int l = -1; - while (x >= 256) { l += 8; x >>= 8; } - return l + log_2[x]; - -} - - -int luaO_rawequalObj (const TValue *t1, const TValue *t2) { - if (ttype(t1) != ttype(t2)) return 0; - else switch (ttype(t1)) { - case LUA_TNIL: - return 1; - case LUA_TNUMBER: - return luai_numeq(nvalue(t1), nvalue(t2)); - case LUA_TBOOLEAN: - return bvalue(t1) == bvalue(t2); /* boolean true must be 1 !! */ - case LUA_TLIGHTUSERDATA: - return pvalue(t1) == pvalue(t2); - default: - lua_assert(iscollectable(t1)); - return gcvalue(t1) == gcvalue(t2); - } -} - - -int luaO_str2d (const char *s, lua_Number *result) { - char *endptr; - *result = lua_str2number(s, &endptr); - if (endptr == s) return 0; /* conversion failed */ - if (*endptr == 'x' || *endptr == 'X') /* maybe an hexadecimal constant? */ - *result = cast_num(strtoul(s, &endptr, 16)); - if (*endptr == '\0') return 1; /* most common case */ - while (isspace(cast(unsigned char, *endptr))) endptr++; - if (*endptr != '\0') return 0; /* invalid trailing characters? */ - return 1; -} - - - -static void pushstr (lua_State *L, const char *str) { - setsvalue2s(L, L->top, luaS_new(L, str)); - incr_top(L); -} - - -/* this function handles only `%d', `%c', %f, %p, and `%s' formats */ -const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { - int n = 1; - pushstr(L, ""); - for (;;) { - const char *e = strchr(fmt, '%'); - if (e == NULL) break; - setsvalue2s(L, L->top, luaS_newlstr(L, fmt, e-fmt)); - incr_top(L); - switch (*(e+1)) { - case 's': { - const char *s = va_arg(argp, char *); - if (s == NULL) s = "(null)"; - pushstr(L, s); - break; - } - case 'c': { - char buff[2]; - buff[0] = cast(char, va_arg(argp, int)); - buff[1] = '\0'; - pushstr(L, buff); - break; - } - case 'd': { - setnvalue(L->top, cast_num(va_arg(argp, int))); - incr_top(L); - break; - } - case 'f': { - setnvalue(L->top, cast_num(va_arg(argp, l_uacNumber))); - incr_top(L); - break; - } - case 'p': { - char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */ - sprintf(buff, "%p", va_arg(argp, void *)); - pushstr(L, buff); - break; - } - case '%': { - pushstr(L, "%"); - break; - } - default: { - char buff[3]; - buff[0] = '%'; - buff[1] = *(e+1); - buff[2] = '\0'; - pushstr(L, buff); - break; - } - } - n += 2; - fmt = e+2; - } - pushstr(L, fmt); - luaV_concat(L, n+1, cast_int(L->top - L->base) - 1); - L->top -= n; - return svalue(L->top - 1); -} - - -const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) { - const char *msg; - va_list argp; - va_start(argp, fmt); - msg = luaO_pushvfstring(L, fmt, argp); - va_end(argp); - return msg; -} - - -void luaO_chunkid (char *out, const char *source, size_t bufflen) { - if (*source == '=') { - strncpy(out, source+1, bufflen); /* remove first char */ - out[bufflen-1] = '\0'; /* ensures null termination */ - } - else { /* out = "source", or "...source" */ - if (*source == '@') { - size_t l; - source++; /* skip the `@' */ - bufflen -= sizeof(" '...' "); - l = strlen(source); - strcpy(out, ""); - if (l > bufflen) { - source += (l-bufflen); /* get last part of file name */ - strcat(out, "..."); - } - strcat(out, source); - } - else { /* out = [string "string"] */ - size_t len = strcspn(source, "\n\r"); /* stop at first newline */ - bufflen -= sizeof(" [string \"...\"] "); - if (len > bufflen) len = bufflen; - strcpy(out, "[string \""); - if (source[len] != '\0') { /* must truncate? */ - strncat(out, source, len); - strcat(out, "..."); - } - else - strcat(out, source); - strcat(out, "\"]"); - } - } -} diff --git a/Utilities/lua-5.1.5/src/lobject.h b/Utilities/lua-5.1.5/src/lobject.h deleted file mode 100644 index f1e447ef3..000000000 --- a/Utilities/lua-5.1.5/src/lobject.h +++ /dev/null @@ -1,381 +0,0 @@ -/* -** $Id: lobject.h,v 2.20.1.2 2008/08/06 13:29:48 roberto Exp $ -** Type definitions for Lua objects -** See Copyright Notice in lua.h -*/ - - -#ifndef lobject_h -#define lobject_h - - -#include - - -#include "llimits.h" -#include "lua.h" - - -/* tags for values visible from Lua */ -#define LAST_TAG LUA_TTHREAD - -#define NUM_TAGS (LAST_TAG+1) - - -/* -** Extra tags for non-values -*/ -#define LUA_TPROTO (LAST_TAG+1) -#define LUA_TUPVAL (LAST_TAG+2) -#define LUA_TDEADKEY (LAST_TAG+3) - - -/* -** Union of all collectable objects -*/ -typedef union GCObject GCObject; - - -/* -** Common Header for all collectable objects (in macro form, to be -** included in other objects) -*/ -#define CommonHeader GCObject *next; lu_byte tt; lu_byte marked - - -/* -** Common header in struct form -*/ -typedef struct GCheader { - CommonHeader; -} GCheader; - - - - -/* -** Union of all Lua values -*/ -typedef union { - GCObject *gc; - void *p; - lua_Number n; - int b; -} Value; - - -/* -** Tagged Values -*/ - -#define TValuefields Value value; int tt - -typedef struct lua_TValue { - TValuefields; -} TValue; - - -/* Macros to test type */ -#define ttisnil(o) (ttype(o) == LUA_TNIL) -#define ttisnumber(o) (ttype(o) == LUA_TNUMBER) -#define ttisstring(o) (ttype(o) == LUA_TSTRING) -#define ttistable(o) (ttype(o) == LUA_TTABLE) -#define ttisfunction(o) (ttype(o) == LUA_TFUNCTION) -#define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN) -#define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA) -#define ttisthread(o) (ttype(o) == LUA_TTHREAD) -#define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA) - -/* Macros to access values */ -#define ttype(o) ((o)->tt) -#define gcvalue(o) check_exp(iscollectable(o), (o)->value.gc) -#define pvalue(o) check_exp(ttislightuserdata(o), (o)->value.p) -#define nvalue(o) check_exp(ttisnumber(o), (o)->value.n) -#define rawtsvalue(o) check_exp(ttisstring(o), &(o)->value.gc->ts) -#define tsvalue(o) (&rawtsvalue(o)->tsv) -#define rawuvalue(o) check_exp(ttisuserdata(o), &(o)->value.gc->u) -#define uvalue(o) (&rawuvalue(o)->uv) -#define clvalue(o) check_exp(ttisfunction(o), &(o)->value.gc->cl) -#define hvalue(o) check_exp(ttistable(o), &(o)->value.gc->h) -#define bvalue(o) check_exp(ttisboolean(o), (o)->value.b) -#define thvalue(o) check_exp(ttisthread(o), &(o)->value.gc->th) - -#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0)) - -/* -** for internal debug only -*/ -#define checkconsistency(obj) \ - lua_assert(!iscollectable(obj) || (ttype(obj) == (obj)->value.gc->gch.tt)) - -#define checkliveness(g,obj) \ - lua_assert(!iscollectable(obj) || \ - ((ttype(obj) == (obj)->value.gc->gch.tt) && !isdead(g, (obj)->value.gc))) - - -/* Macros to set values */ -#define setnilvalue(obj) ((obj)->tt=LUA_TNIL) - -#define setnvalue(obj,x) \ - { TValue *i_o=(obj); i_o->value.n=(x); i_o->tt=LUA_TNUMBER; } - -#define setpvalue(obj,x) \ - { TValue *i_o=(obj); i_o->value.p=(x); i_o->tt=LUA_TLIGHTUSERDATA; } - -#define setbvalue(obj,x) \ - { TValue *i_o=(obj); i_o->value.b=(x); i_o->tt=LUA_TBOOLEAN; } - -#define setsvalue(L,obj,x) \ - { TValue *i_o=(obj); \ - i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TSTRING; \ - checkliveness(G(L),i_o); } - -#define setuvalue(L,obj,x) \ - { TValue *i_o=(obj); \ - i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TUSERDATA; \ - checkliveness(G(L),i_o); } - -#define setthvalue(L,obj,x) \ - { TValue *i_o=(obj); \ - i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTHREAD; \ - checkliveness(G(L),i_o); } - -#define setclvalue(L,obj,x) \ - { TValue *i_o=(obj); \ - i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TFUNCTION; \ - checkliveness(G(L),i_o); } - -#define sethvalue(L,obj,x) \ - { TValue *i_o=(obj); \ - i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTABLE; \ - checkliveness(G(L),i_o); } - -#define setptvalue(L,obj,x) \ - { TValue *i_o=(obj); \ - i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TPROTO; \ - checkliveness(G(L),i_o); } - - - - -#define setobj(L,obj1,obj2) \ - { const TValue *o2=(obj2); TValue *o1=(obj1); \ - o1->value = o2->value; o1->tt=o2->tt; \ - checkliveness(G(L),o1); } - - -/* -** different types of sets, according to destination -*/ - -/* from stack to (same) stack */ -#define setobjs2s setobj -/* to stack (not from same stack) */ -#define setobj2s setobj -#define setsvalue2s setsvalue -#define sethvalue2s sethvalue -#define setptvalue2s setptvalue -/* from table to same table */ -#define setobjt2t setobj -/* to table */ -#define setobj2t setobj -/* to new object */ -#define setobj2n setobj -#define setsvalue2n setsvalue - -#define setttype(obj, tt) (ttype(obj) = (tt)) - - -#define iscollectable(o) (ttype(o) >= LUA_TSTRING) - - - -typedef TValue *StkId; /* index to stack elements */ - - -/* -** String headers for string table -*/ -typedef union TString { - L_Umaxalign dummy; /* ensures maximum alignment for strings */ - struct { - CommonHeader; - lu_byte reserved; - unsigned int hash; - size_t len; - } tsv; -} TString; - - -#define getstr(ts) cast(const char *, (ts) + 1) -#define svalue(o) getstr(rawtsvalue(o)) - - - -typedef union Udata { - L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ - struct { - CommonHeader; - struct Table *metatable; - struct Table *env; - size_t len; - } uv; -} Udata; - - - - -/* -** Function Prototypes -*/ -typedef struct Proto { - CommonHeader; - TValue *k; /* constants used by the function */ - Instruction *code; - struct Proto **p; /* functions defined inside the function */ - int *lineinfo; /* map from opcodes to source lines */ - struct LocVar *locvars; /* information about local variables */ - TString **upvalues; /* upvalue names */ - TString *source; - int sizeupvalues; - int sizek; /* size of `k' */ - int sizecode; - int sizelineinfo; - int sizep; /* size of `p' */ - int sizelocvars; - int linedefined; - int lastlinedefined; - GCObject *gclist; - lu_byte nups; /* number of upvalues */ - lu_byte numparams; - lu_byte is_vararg; - lu_byte maxstacksize; -} Proto; - - -/* masks for new-style vararg */ -#define VARARG_HASARG 1 -#define VARARG_ISVARARG 2 -#define VARARG_NEEDSARG 4 - - -typedef struct LocVar { - TString *varname; - int startpc; /* first point where variable is active */ - int endpc; /* first point where variable is dead */ -} LocVar; - - - -/* -** Upvalues -*/ - -typedef struct UpVal { - CommonHeader; - TValue *v; /* points to stack or to its own value */ - union { - TValue value; /* the value (when closed) */ - struct { /* double linked list (when open) */ - struct UpVal *prev; - struct UpVal *next; - } l; - } u; -} UpVal; - - -/* -** Closures -*/ - -#define ClosureHeader \ - CommonHeader; lu_byte isC; lu_byte nupvalues; GCObject *gclist; \ - struct Table *env - -typedef struct CClosure { - ClosureHeader; - lua_CFunction f; - TValue upvalue[1]; -} CClosure; - - -typedef struct LClosure { - ClosureHeader; - struct Proto *p; - UpVal *upvals[1]; -} LClosure; - - -typedef union Closure { - CClosure c; - LClosure l; -} Closure; - - -#define iscfunction(o) (ttype(o) == LUA_TFUNCTION && clvalue(o)->c.isC) -#define isLfunction(o) (ttype(o) == LUA_TFUNCTION && !clvalue(o)->c.isC) - - -/* -** Tables -*/ - -typedef union TKey { - struct { - TValuefields; - struct Node *next; /* for chaining */ - } nk; - TValue tvk; -} TKey; - - -typedef struct Node { - TValue i_val; - TKey i_key; -} Node; - - -typedef struct Table { - CommonHeader; - lu_byte flags; /* 1<

lsizenode)) - - -#define luaO_nilobject (&luaO_nilobject_) - -LUAI_DATA const TValue luaO_nilobject_; - -#define ceillog2(x) (luaO_log2((x)-1) + 1) - -LUAI_FUNC int luaO_log2 (unsigned int x); -LUAI_FUNC int luaO_int2fb (unsigned int x); -LUAI_FUNC int luaO_fb2int (int x); -LUAI_FUNC int luaO_rawequalObj (const TValue *t1, const TValue *t2); -LUAI_FUNC int luaO_str2d (const char *s, lua_Number *result); -LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt, - va_list argp); -LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...); -LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len); - - -#endif - diff --git a/Utilities/lua-5.1.5/src/lopcodes.c b/Utilities/lua-5.1.5/src/lopcodes.c deleted file mode 100644 index 4cc745230..000000000 --- a/Utilities/lua-5.1.5/src/lopcodes.c +++ /dev/null @@ -1,102 +0,0 @@ -/* -** $Id: lopcodes.c,v 1.37.1.1 2007/12/27 13:02:25 roberto Exp $ -** See Copyright Notice in lua.h -*/ - - -#define lopcodes_c -#define LUA_CORE - - -#include "lopcodes.h" - - -/* ORDER OP */ - -const char *const luaP_opnames[NUM_OPCODES+1] = { - "MOVE", - "LOADK", - "LOADBOOL", - "LOADNIL", - "GETUPVAL", - "GETGLOBAL", - "GETTABLE", - "SETGLOBAL", - "SETUPVAL", - "SETTABLE", - "NEWTABLE", - "SELF", - "ADD", - "SUB", - "MUL", - "DIV", - "MOD", - "POW", - "UNM", - "NOT", - "LEN", - "CONCAT", - "JMP", - "EQ", - "LT", - "LE", - "TEST", - "TESTSET", - "CALL", - "TAILCALL", - "RETURN", - "FORLOOP", - "FORPREP", - "TFORLOOP", - "SETLIST", - "CLOSE", - "CLOSURE", - "VARARG", - NULL -}; - - -#define opmode(t,a,b,c,m) (((t)<<7) | ((a)<<6) | ((b)<<4) | ((c)<<2) | (m)) - -const lu_byte luaP_opmodes[NUM_OPCODES] = { -/* T A B C mode opcode */ - opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_MOVE */ - ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_LOADK */ - ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */ - ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LOADNIL */ - ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */ - ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_GETGLOBAL */ - ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */ - ,opmode(0, 0, OpArgK, OpArgN, iABx) /* OP_SETGLOBAL */ - ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_SETUPVAL */ - ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABLE */ - ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_NEWTABLE */ - ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_SELF */ - ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ADD */ - ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SUB */ - ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MUL */ - ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_DIV */ - ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MOD */ - ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_POW */ - ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_UNM */ - ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_NOT */ - ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LEN */ - ,opmode(0, 1, OpArgR, OpArgR, iABC) /* OP_CONCAT */ - ,opmode(0, 0, OpArgR, OpArgN, iAsBx) /* OP_JMP */ - ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */ - ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */ - ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */ - ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TEST */ - ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */ - ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */ - ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */ - ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_RETURN */ - ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORLOOP */ - ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORPREP */ - ,opmode(1, 0, OpArgN, OpArgU, iABC) /* OP_TFORLOOP */ - ,opmode(0, 0, OpArgU, OpArgU, iABC) /* OP_SETLIST */ - ,opmode(0, 0, OpArgN, OpArgN, iABC) /* OP_CLOSE */ - ,opmode(0, 1, OpArgU, OpArgN, iABx) /* OP_CLOSURE */ - ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_VARARG */ -}; - diff --git a/Utilities/lua-5.1.5/src/lopcodes.h b/Utilities/lua-5.1.5/src/lopcodes.h deleted file mode 100644 index 41224d6ee..000000000 --- a/Utilities/lua-5.1.5/src/lopcodes.h +++ /dev/null @@ -1,268 +0,0 @@ -/* -** $Id: lopcodes.h,v 1.125.1.1 2007/12/27 13:02:25 roberto Exp $ -** Opcodes for Lua virtual machine -** See Copyright Notice in lua.h -*/ - -#ifndef lopcodes_h -#define lopcodes_h - -#include "llimits.h" - - -/*=========================================================================== - We assume that instructions are unsigned numbers. - All instructions have an opcode in the first 6 bits. - Instructions can have the following fields: - `A' : 8 bits - `B' : 9 bits - `C' : 9 bits - `Bx' : 18 bits (`B' and `C' together) - `sBx' : signed Bx - - A signed argument is represented in excess K; that is, the number - value is the unsigned value minus K. K is exactly the maximum value - for that argument (so that -max is represented by 0, and +max is - represented by 2*max), which is half the maximum for the corresponding - unsigned argument. -===========================================================================*/ - - -enum OpMode {iABC, iABx, iAsBx}; /* basic instruction format */ - - -/* -** size and position of opcode arguments. -*/ -#define SIZE_C 9 -#define SIZE_B 9 -#define SIZE_Bx (SIZE_C + SIZE_B) -#define SIZE_A 8 - -#define SIZE_OP 6 - -#define POS_OP 0 -#define POS_A (POS_OP + SIZE_OP) -#define POS_C (POS_A + SIZE_A) -#define POS_B (POS_C + SIZE_C) -#define POS_Bx POS_C - - -/* -** limits for opcode arguments. -** we use (signed) int to manipulate most arguments, -** so they must fit in LUAI_BITSINT-1 bits (-1 for sign) -*/ -#if SIZE_Bx < LUAI_BITSINT-1 -#define MAXARG_Bx ((1<>1) /* `sBx' is signed */ -#else -#define MAXARG_Bx MAX_INT -#define MAXARG_sBx MAX_INT -#endif - - -#define MAXARG_A ((1<>POS_OP) & MASK1(SIZE_OP,0))) -#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \ - ((cast(Instruction, o)<>POS_A) & MASK1(SIZE_A,0))) -#define SETARG_A(i,u) ((i) = (((i)&MASK0(SIZE_A,POS_A)) | \ - ((cast(Instruction, u)<>POS_B) & MASK1(SIZE_B,0))) -#define SETARG_B(i,b) ((i) = (((i)&MASK0(SIZE_B,POS_B)) | \ - ((cast(Instruction, b)<>POS_C) & MASK1(SIZE_C,0))) -#define SETARG_C(i,b) ((i) = (((i)&MASK0(SIZE_C,POS_C)) | \ - ((cast(Instruction, b)<>POS_Bx) & MASK1(SIZE_Bx,0))) -#define SETARG_Bx(i,b) ((i) = (((i)&MASK0(SIZE_Bx,POS_Bx)) | \ - ((cast(Instruction, b)< C) then pc++ */ -OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */ - -OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */ -OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */ -OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */ - -OP_FORLOOP,/* A sBx R(A)+=R(A+2); - if R(A) =) R(A)*/ -OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx], R(A), ... ,R(A+n)) */ - -OP_VARARG/* A B R(A), R(A+1), ..., R(A+B-1) = vararg */ -} OpCode; - - -#define NUM_OPCODES (cast(int, OP_VARARG) + 1) - - - -/*=========================================================================== - Notes: - (*) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1, - and can be 0: OP_CALL then sets `top' to last_result+1, so - next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use `top'. - - (*) In OP_VARARG, if (B == 0) then use actual number of varargs and - set top (like in OP_CALL with C == 0). - - (*) In OP_RETURN, if (B == 0) then return up to `top' - - (*) In OP_SETLIST, if (B == 0) then B = `top'; - if (C == 0) then next `instruction' is real C - - (*) For comparisons, A specifies what condition the test should accept - (true or false). - - (*) All `skips' (pc++) assume that next instruction is a jump -===========================================================================*/ - - -/* -** masks for instruction properties. The format is: -** bits 0-1: op mode -** bits 2-3: C arg mode -** bits 4-5: B arg mode -** bit 6: instruction set register A -** bit 7: operator is a test -*/ - -enum OpArgMask { - OpArgN, /* argument is not used */ - OpArgU, /* argument is used */ - OpArgR, /* argument is a register or a jump offset */ - OpArgK /* argument is a constant or register/constant */ -}; - -LUAI_DATA const lu_byte luaP_opmodes[NUM_OPCODES]; - -#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 3)) -#define getBMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 4) & 3)) -#define getCMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 2) & 3)) -#define testAMode(m) (luaP_opmodes[m] & (1 << 6)) -#define testTMode(m) (luaP_opmodes[m] & (1 << 7)) - - -LUAI_DATA const char *const luaP_opnames[NUM_OPCODES+1]; /* opcode names */ - - -/* number of list items to accumulate before a SETLIST instruction */ -#define LFIELDS_PER_FLUSH 50 - - -#endif diff --git a/Utilities/lua-5.1.5/src/loslib.c b/Utilities/lua-5.1.5/src/loslib.c deleted file mode 100644 index da06a572a..000000000 --- a/Utilities/lua-5.1.5/src/loslib.c +++ /dev/null @@ -1,243 +0,0 @@ -/* -** $Id: loslib.c,v 1.19.1.3 2008/01/18 16:38:18 roberto Exp $ -** Standard Operating System library -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include -#include -#include - -#define loslib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - -static int os_pushresult (lua_State *L, int i, const char *filename) { - int en = errno; /* calls to Lua API may change this value */ - if (i) { - lua_pushboolean(L, 1); - return 1; - } - else { - lua_pushnil(L); - lua_pushfstring(L, "%s: %s", filename, strerror(en)); - lua_pushinteger(L, en); - return 3; - } -} - - -static int os_execute (lua_State *L) { - lua_pushinteger(L, system(luaL_optstring(L, 1, NULL))); - return 1; -} - - -static int os_remove (lua_State *L) { - const char *filename = luaL_checkstring(L, 1); - return os_pushresult(L, remove(filename) == 0, filename); -} - - -static int os_rename (lua_State *L) { - const char *fromname = luaL_checkstring(L, 1); - const char *toname = luaL_checkstring(L, 2); - return os_pushresult(L, rename(fromname, toname) == 0, fromname); -} - - -static int os_tmpname (lua_State *L) { - char buff[LUA_TMPNAMBUFSIZE]; - int err; - lua_tmpnam(buff, err); - if (err) - return luaL_error(L, "unable to generate a unique filename"); - lua_pushstring(L, buff); - return 1; -} - - -static int os_getenv (lua_State *L) { - lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */ - return 1; -} - - -static int os_clock (lua_State *L) { - lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC); - return 1; -} - - -/* -** {====================================================== -** Time/Date operations -** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S, -** wday=%w+1, yday=%j, isdst=? } -** ======================================================= -*/ - -static void setfield (lua_State *L, const char *key, int value) { - lua_pushinteger(L, value); - lua_setfield(L, -2, key); -} - -static void setboolfield (lua_State *L, const char *key, int value) { - if (value < 0) /* undefined? */ - return; /* does not set field */ - lua_pushboolean(L, value); - lua_setfield(L, -2, key); -} - -static int getboolfield (lua_State *L, const char *key) { - int res; - lua_getfield(L, -1, key); - res = lua_isnil(L, -1) ? -1 : lua_toboolean(L, -1); - lua_pop(L, 1); - return res; -} - - -static int getfield (lua_State *L, const char *key, int d) { - int res; - lua_getfield(L, -1, key); - if (lua_isnumber(L, -1)) - res = (int)lua_tointeger(L, -1); - else { - if (d < 0) - return luaL_error(L, "field " LUA_QS " missing in date table", key); - res = d; - } - lua_pop(L, 1); - return res; -} - - -static int os_date (lua_State *L) { - const char *s = luaL_optstring(L, 1, "%c"); - time_t t = luaL_opt(L, (time_t)luaL_checknumber, 2, time(NULL)); - struct tm *stm; - if (*s == '!') { /* UTC? */ - stm = gmtime(&t); - s++; /* skip `!' */ - } - else - stm = localtime(&t); - if (stm == NULL) /* invalid date? */ - lua_pushnil(L); - else if (strcmp(s, "*t") == 0) { - lua_createtable(L, 0, 9); /* 9 = number of fields */ - setfield(L, "sec", stm->tm_sec); - setfield(L, "min", stm->tm_min); - setfield(L, "hour", stm->tm_hour); - setfield(L, "day", stm->tm_mday); - setfield(L, "month", stm->tm_mon+1); - setfield(L, "year", stm->tm_year+1900); - setfield(L, "wday", stm->tm_wday+1); - setfield(L, "yday", stm->tm_yday+1); - setboolfield(L, "isdst", stm->tm_isdst); - } - else { - char cc[3]; - luaL_Buffer b; - cc[0] = '%'; cc[2] = '\0'; - luaL_buffinit(L, &b); - for (; *s; s++) { - if (*s != '%' || *(s + 1) == '\0') /* no conversion specifier? */ - luaL_addchar(&b, *s); - else { - size_t reslen; - char buff[200]; /* should be big enough for any conversion result */ - cc[1] = *(++s); - reslen = strftime(buff, sizeof(buff), cc, stm); - luaL_addlstring(&b, buff, reslen); - } - } - luaL_pushresult(&b); - } - return 1; -} - - -static int os_time (lua_State *L) { - time_t t; - if (lua_isnoneornil(L, 1)) /* called without args? */ - t = time(NULL); /* get current time */ - else { - struct tm ts; - luaL_checktype(L, 1, LUA_TTABLE); - lua_settop(L, 1); /* make sure table is at the top */ - ts.tm_sec = getfield(L, "sec", 0); - ts.tm_min = getfield(L, "min", 0); - ts.tm_hour = getfield(L, "hour", 12); - ts.tm_mday = getfield(L, "day", -1); - ts.tm_mon = getfield(L, "month", -1) - 1; - ts.tm_year = getfield(L, "year", -1) - 1900; - ts.tm_isdst = getboolfield(L, "isdst"); - t = mktime(&ts); - } - if (t == (time_t)(-1)) - lua_pushnil(L); - else - lua_pushnumber(L, (lua_Number)t); - return 1; -} - - -static int os_difftime (lua_State *L) { - lua_pushnumber(L, difftime((time_t)(luaL_checknumber(L, 1)), - (time_t)(luaL_optnumber(L, 2, 0)))); - return 1; -} - -/* }====================================================== */ - - -static int os_setlocale (lua_State *L) { - static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, - LC_NUMERIC, LC_TIME}; - static const char *const catnames[] = {"all", "collate", "ctype", "monetary", - "numeric", "time", NULL}; - const char *l = luaL_optstring(L, 1, NULL); - int op = luaL_checkoption(L, 2, "all", catnames); - lua_pushstring(L, setlocale(cat[op], l)); - return 1; -} - - -static int os_exit (lua_State *L) { - exit(luaL_optint(L, 1, EXIT_SUCCESS)); -} - -static const luaL_Reg syslib[] = { - {"clock", os_clock}, - {"date", os_date}, - {"difftime", os_difftime}, - {"execute", os_execute}, - {"exit", os_exit}, - {"getenv", os_getenv}, - {"remove", os_remove}, - {"rename", os_rename}, - {"setlocale", os_setlocale}, - {"time", os_time}, - {"tmpname", os_tmpname}, - {NULL, NULL} -}; - -/* }====================================================== */ - - - -LUALIB_API int luaopen_os (lua_State *L) { - luaL_register(L, LUA_OSLIBNAME, syslib); - return 1; -} - diff --git a/Utilities/lua-5.1.5/src/lparser.c b/Utilities/lua-5.1.5/src/lparser.c deleted file mode 100644 index dda7488dc..000000000 --- a/Utilities/lua-5.1.5/src/lparser.c +++ /dev/null @@ -1,1339 +0,0 @@ -/* -** $Id: lparser.c,v 2.42.1.4 2011/10/21 19:31:42 roberto Exp $ -** Lua Parser -** See Copyright Notice in lua.h -*/ - - -#include - -#define lparser_c -#define LUA_CORE - -#include "lua.h" - -#include "lcode.h" -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "llex.h" -#include "lmem.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lparser.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" - - - -#define hasmultret(k) ((k) == VCALL || (k) == VVARARG) - -#define getlocvar(fs, i) ((fs)->f->locvars[(fs)->actvar[i]]) - -#define luaY_checklimit(fs,v,l,m) if ((v)>(l)) errorlimit(fs,l,m) - - -/* -** nodes for block list (list of active blocks) -*/ -typedef struct BlockCnt { - struct BlockCnt *previous; /* chain */ - int breaklist; /* list of jumps out of this loop */ - lu_byte nactvar; /* # active locals outside the breakable structure */ - lu_byte upval; /* true if some variable in the block is an upvalue */ - lu_byte isbreakable; /* true if `block' is a loop */ -} BlockCnt; - - - -/* -** prototypes for recursive non-terminal functions -*/ -static void chunk (LexState *ls); -static void expr (LexState *ls, expdesc *v); - - -static void anchor_token (LexState *ls) { - if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) { - TString *ts = ls->t.seminfo.ts; - luaX_newstring(ls, getstr(ts), ts->tsv.len); - } -} - - -static void error_expected (LexState *ls, int token) { - luaX_syntaxerror(ls, - luaO_pushfstring(ls->L, LUA_QS " expected", luaX_token2str(ls, token))); -} - - -static void errorlimit (FuncState *fs, int limit, const char *what) { - const char *msg = (fs->f->linedefined == 0) ? - luaO_pushfstring(fs->L, "main function has more than %d %s", limit, what) : - luaO_pushfstring(fs->L, "function at line %d has more than %d %s", - fs->f->linedefined, limit, what); - luaX_lexerror(fs->ls, msg, 0); -} - - -static int testnext (LexState *ls, int c) { - if (ls->t.token == c) { - luaX_next(ls); - return 1; - } - else return 0; -} - - -static void check (LexState *ls, int c) { - if (ls->t.token != c) - error_expected(ls, c); -} - -static void checknext (LexState *ls, int c) { - check(ls, c); - luaX_next(ls); -} - - -#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); } - - - -static void check_match (LexState *ls, int what, int who, int where) { - if (!testnext(ls, what)) { - if (where == ls->linenumber) - error_expected(ls, what); - else { - luaX_syntaxerror(ls, luaO_pushfstring(ls->L, - LUA_QS " expected (to close " LUA_QS " at line %d)", - luaX_token2str(ls, what), luaX_token2str(ls, who), where)); - } - } -} - - -static TString *str_checkname (LexState *ls) { - TString *ts; - check(ls, TK_NAME); - ts = ls->t.seminfo.ts; - luaX_next(ls); - return ts; -} - - -static void init_exp (expdesc *e, expkind k, int i) { - e->f = e->t = NO_JUMP; - e->k = k; - e->u.s.info = i; -} - - -static void codestring (LexState *ls, expdesc *e, TString *s) { - init_exp(e, VK, luaK_stringK(ls->fs, s)); -} - - -static void checkname(LexState *ls, expdesc *e) { - codestring(ls, e, str_checkname(ls)); -} - - -static int registerlocalvar (LexState *ls, TString *varname) { - FuncState *fs = ls->fs; - Proto *f = fs->f; - int oldsize = f->sizelocvars; - luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars, - LocVar, SHRT_MAX, "too many local variables"); - while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL; - f->locvars[fs->nlocvars].varname = varname; - luaC_objbarrier(ls->L, f, varname); - return fs->nlocvars++; -} - - -#define new_localvarliteral(ls,v,n) \ - new_localvar(ls, luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char))-1), n) - - -static void new_localvar (LexState *ls, TString *name, int n) { - FuncState *fs = ls->fs; - luaY_checklimit(fs, fs->nactvar+n+1, LUAI_MAXVARS, "local variables"); - fs->actvar[fs->nactvar+n] = cast(unsigned short, registerlocalvar(ls, name)); -} - - -static void adjustlocalvars (LexState *ls, int nvars) { - FuncState *fs = ls->fs; - fs->nactvar = cast_byte(fs->nactvar + nvars); - for (; nvars; nvars--) { - getlocvar(fs, fs->nactvar - nvars).startpc = fs->pc; - } -} - - -static void removevars (LexState *ls, int tolevel) { - FuncState *fs = ls->fs; - while (fs->nactvar > tolevel) - getlocvar(fs, --fs->nactvar).endpc = fs->pc; -} - - -static int indexupvalue (FuncState *fs, TString *name, expdesc *v) { - int i; - Proto *f = fs->f; - int oldsize = f->sizeupvalues; - for (i=0; inups; i++) { - if (fs->upvalues[i].k == v->k && fs->upvalues[i].info == v->u.s.info) { - lua_assert(f->upvalues[i] == name); - return i; - } - } - /* new one */ - luaY_checklimit(fs, f->nups + 1, LUAI_MAXUPVALUES, "upvalues"); - luaM_growvector(fs->L, f->upvalues, f->nups, f->sizeupvalues, - TString *, MAX_INT, ""); - while (oldsize < f->sizeupvalues) f->upvalues[oldsize++] = NULL; - f->upvalues[f->nups] = name; - luaC_objbarrier(fs->L, f, name); - lua_assert(v->k == VLOCAL || v->k == VUPVAL); - fs->upvalues[f->nups].k = cast_byte(v->k); - fs->upvalues[f->nups].info = cast_byte(v->u.s.info); - return f->nups++; -} - - -static int searchvar (FuncState *fs, TString *n) { - int i; - for (i=fs->nactvar-1; i >= 0; i--) { - if (n == getlocvar(fs, i).varname) - return i; - } - return -1; /* not found */ -} - - -static void markupval (FuncState *fs, int level) { - BlockCnt *bl = fs->bl; - while (bl && bl->nactvar > level) bl = bl->previous; - if (bl) bl->upval = 1; -} - - -static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) { - if (fs == NULL) { /* no more levels? */ - init_exp(var, VGLOBAL, NO_REG); /* default is global variable */ - return VGLOBAL; - } - else { - int v = searchvar(fs, n); /* look up at current level */ - if (v >= 0) { - init_exp(var, VLOCAL, v); - if (!base) - markupval(fs, v); /* local will be used as an upval */ - return VLOCAL; - } - else { /* not found at current level; try upper one */ - if (singlevaraux(fs->prev, n, var, 0) == VGLOBAL) - return VGLOBAL; - var->u.s.info = indexupvalue(fs, n, var); /* else was LOCAL or UPVAL */ - var->k = VUPVAL; /* upvalue in this level */ - return VUPVAL; - } - } -} - - -static void singlevar (LexState *ls, expdesc *var) { - TString *varname = str_checkname(ls); - FuncState *fs = ls->fs; - if (singlevaraux(fs, varname, var, 1) == VGLOBAL) - var->u.s.info = luaK_stringK(fs, varname); /* info points to global name */ -} - - -static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) { - FuncState *fs = ls->fs; - int extra = nvars - nexps; - if (hasmultret(e->k)) { - extra++; /* includes call itself */ - if (extra < 0) extra = 0; - luaK_setreturns(fs, e, extra); /* last exp. provides the difference */ - if (extra > 1) luaK_reserveregs(fs, extra-1); - } - else { - if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */ - if (extra > 0) { - int reg = fs->freereg; - luaK_reserveregs(fs, extra); - luaK_nil(fs, reg, extra); - } - } -} - - -static void enterlevel (LexState *ls) { - if (++ls->L->nCcalls > LUAI_MAXCCALLS) - luaX_lexerror(ls, "chunk has too many syntax levels", 0); -} - - -#define leavelevel(ls) ((ls)->L->nCcalls--) - - -static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) { - bl->breaklist = NO_JUMP; - bl->isbreakable = isbreakable; - bl->nactvar = fs->nactvar; - bl->upval = 0; - bl->previous = fs->bl; - fs->bl = bl; - lua_assert(fs->freereg == fs->nactvar); -} - - -static void leaveblock (FuncState *fs) { - BlockCnt *bl = fs->bl; - fs->bl = bl->previous; - removevars(fs->ls, bl->nactvar); - if (bl->upval) - luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0); - /* a block either controls scope or breaks (never both) */ - lua_assert(!bl->isbreakable || !bl->upval); - lua_assert(bl->nactvar == fs->nactvar); - fs->freereg = fs->nactvar; /* free registers */ - luaK_patchtohere(fs, bl->breaklist); -} - - -static void pushclosure (LexState *ls, FuncState *func, expdesc *v) { - FuncState *fs = ls->fs; - Proto *f = fs->f; - int oldsize = f->sizep; - int i; - luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *, - MAXARG_Bx, "constant table overflow"); - while (oldsize < f->sizep) f->p[oldsize++] = NULL; - f->p[fs->np++] = func->f; - luaC_objbarrier(ls->L, f, func->f); - init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1)); - for (i=0; if->nups; i++) { - OpCode o = (func->upvalues[i].k == VLOCAL) ? OP_MOVE : OP_GETUPVAL; - luaK_codeABC(fs, o, 0, func->upvalues[i].info, 0); - } -} - - -static void open_func (LexState *ls, FuncState *fs) { - lua_State *L = ls->L; - Proto *f = luaF_newproto(L); - fs->f = f; - fs->prev = ls->fs; /* linked list of funcstates */ - fs->ls = ls; - fs->L = L; - ls->fs = fs; - fs->pc = 0; - fs->lasttarget = -1; - fs->jpc = NO_JUMP; - fs->freereg = 0; - fs->nk = 0; - fs->np = 0; - fs->nlocvars = 0; - fs->nactvar = 0; - fs->bl = NULL; - f->source = ls->source; - f->maxstacksize = 2; /* registers 0/1 are always valid */ - fs->h = luaH_new(L, 0, 0); - /* anchor table of constants and prototype (to avoid being collected) */ - sethvalue2s(L, L->top, fs->h); - incr_top(L); - setptvalue2s(L, L->top, f); - incr_top(L); -} - - -static void close_func (LexState *ls) { - lua_State *L = ls->L; - FuncState *fs = ls->fs; - Proto *f = fs->f; - removevars(ls, 0); - luaK_ret(fs, 0, 0); /* final return */ - luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction); - f->sizecode = fs->pc; - luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int); - f->sizelineinfo = fs->pc; - luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue); - f->sizek = fs->nk; - luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *); - f->sizep = fs->np; - luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar); - f->sizelocvars = fs->nlocvars; - luaM_reallocvector(L, f->upvalues, f->sizeupvalues, f->nups, TString *); - f->sizeupvalues = f->nups; - lua_assert(luaG_checkcode(f)); - lua_assert(fs->bl == NULL); - ls->fs = fs->prev; - /* last token read was anchored in defunct function; must reanchor it */ - if (fs) anchor_token(ls); - L->top -= 2; /* remove table and prototype from the stack */ -} - - -Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) { - struct LexState lexstate; - struct FuncState funcstate; - lexstate.buff = buff; - luaX_setinput(L, &lexstate, z, luaS_new(L, name)); - open_func(&lexstate, &funcstate); - funcstate.f->is_vararg = VARARG_ISVARARG; /* main func. is always vararg */ - luaX_next(&lexstate); /* read first token */ - chunk(&lexstate); - check(&lexstate, TK_EOS); - close_func(&lexstate); - lua_assert(funcstate.prev == NULL); - lua_assert(funcstate.f->nups == 0); - lua_assert(lexstate.fs == NULL); - return funcstate.f; -} - - - -/*============================================================*/ -/* GRAMMAR RULES */ -/*============================================================*/ - - -static void field (LexState *ls, expdesc *v) { - /* field -> ['.' | ':'] NAME */ - FuncState *fs = ls->fs; - expdesc key; - luaK_exp2anyreg(fs, v); - luaX_next(ls); /* skip the dot or colon */ - checkname(ls, &key); - luaK_indexed(fs, v, &key); -} - - -static void yindex (LexState *ls, expdesc *v) { - /* index -> '[' expr ']' */ - luaX_next(ls); /* skip the '[' */ - expr(ls, v); - luaK_exp2val(ls->fs, v); - checknext(ls, ']'); -} - - -/* -** {====================================================================== -** Rules for Constructors -** ======================================================================= -*/ - - -struct ConsControl { - expdesc v; /* last list item read */ - expdesc *t; /* table descriptor */ - int nh; /* total number of `record' elements */ - int na; /* total number of array elements */ - int tostore; /* number of array elements pending to be stored */ -}; - - -static void recfield (LexState *ls, struct ConsControl *cc) { - /* recfield -> (NAME | `['exp1`]') = exp1 */ - FuncState *fs = ls->fs; - int reg = ls->fs->freereg; - expdesc key, val; - int rkkey; - if (ls->t.token == TK_NAME) { - luaY_checklimit(fs, cc->nh, MAX_INT, "items in a constructor"); - checkname(ls, &key); - } - else /* ls->t.token == '[' */ - yindex(ls, &key); - cc->nh++; - checknext(ls, '='); - rkkey = luaK_exp2RK(fs, &key); - expr(ls, &val); - luaK_codeABC(fs, OP_SETTABLE, cc->t->u.s.info, rkkey, luaK_exp2RK(fs, &val)); - fs->freereg = reg; /* free registers */ -} - - -static void closelistfield (FuncState *fs, struct ConsControl *cc) { - if (cc->v.k == VVOID) return; /* there is no list item */ - luaK_exp2nextreg(fs, &cc->v); - cc->v.k = VVOID; - if (cc->tostore == LFIELDS_PER_FLUSH) { - luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore); /* flush */ - cc->tostore = 0; /* no more items pending */ - } -} - - -static void lastlistfield (FuncState *fs, struct ConsControl *cc) { - if (cc->tostore == 0) return; - if (hasmultret(cc->v.k)) { - luaK_setmultret(fs, &cc->v); - luaK_setlist(fs, cc->t->u.s.info, cc->na, LUA_MULTRET); - cc->na--; /* do not count last expression (unknown number of elements) */ - } - else { - if (cc->v.k != VVOID) - luaK_exp2nextreg(fs, &cc->v); - luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore); - } -} - - -static void listfield (LexState *ls, struct ConsControl *cc) { - expr(ls, &cc->v); - luaY_checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor"); - cc->na++; - cc->tostore++; -} - - -static void constructor (LexState *ls, expdesc *t) { - /* constructor -> ?? */ - FuncState *fs = ls->fs; - int line = ls->linenumber; - int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0); - struct ConsControl cc; - cc.na = cc.nh = cc.tostore = 0; - cc.t = t; - init_exp(t, VRELOCABLE, pc); - init_exp(&cc.v, VVOID, 0); /* no value (yet) */ - luaK_exp2nextreg(ls->fs, t); /* fix it at stack top (for gc) */ - checknext(ls, '{'); - do { - lua_assert(cc.v.k == VVOID || cc.tostore > 0); - if (ls->t.token == '}') break; - closelistfield(fs, &cc); - switch(ls->t.token) { - case TK_NAME: { /* may be listfields or recfields */ - luaX_lookahead(ls); - if (ls->lookahead.token != '=') /* expression? */ - listfield(ls, &cc); - else - recfield(ls, &cc); - break; - } - case '[': { /* constructor_item -> recfield */ - recfield(ls, &cc); - break; - } - default: { /* constructor_part -> listfield */ - listfield(ls, &cc); - break; - } - } - } while (testnext(ls, ',') || testnext(ls, ';')); - check_match(ls, '}', '{', line); - lastlistfield(fs, &cc); - SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */ - SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */ -} - -/* }====================================================================== */ - - - -static void parlist (LexState *ls) { - /* parlist -> [ param { `,' param } ] */ - FuncState *fs = ls->fs; - Proto *f = fs->f; - int nparams = 0; - f->is_vararg = 0; - if (ls->t.token != ')') { /* is `parlist' not empty? */ - do { - switch (ls->t.token) { - case TK_NAME: { /* param -> NAME */ - new_localvar(ls, str_checkname(ls), nparams++); - break; - } - case TK_DOTS: { /* param -> `...' */ - luaX_next(ls); -#if defined(LUA_COMPAT_VARARG) - /* use `arg' as default name */ - new_localvarliteral(ls, "arg", nparams++); - f->is_vararg = VARARG_HASARG | VARARG_NEEDSARG; -#endif - f->is_vararg |= VARARG_ISVARARG; - break; - } - default: luaX_syntaxerror(ls, " or " LUA_QL("...") " expected"); - } - } while (!f->is_vararg && testnext(ls, ',')); - } - adjustlocalvars(ls, nparams); - f->numparams = cast_byte(fs->nactvar - (f->is_vararg & VARARG_HASARG)); - luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */ -} - - -static void body (LexState *ls, expdesc *e, int needself, int line) { - /* body -> `(' parlist `)' chunk END */ - FuncState new_fs; - open_func(ls, &new_fs); - new_fs.f->linedefined = line; - checknext(ls, '('); - if (needself) { - new_localvarliteral(ls, "self", 0); - adjustlocalvars(ls, 1); - } - parlist(ls); - checknext(ls, ')'); - chunk(ls); - new_fs.f->lastlinedefined = ls->linenumber; - check_match(ls, TK_END, TK_FUNCTION, line); - close_func(ls); - pushclosure(ls, &new_fs, e); -} - - -static int explist1 (LexState *ls, expdesc *v) { - /* explist1 -> expr { `,' expr } */ - int n = 1; /* at least one expression */ - expr(ls, v); - while (testnext(ls, ',')) { - luaK_exp2nextreg(ls->fs, v); - expr(ls, v); - n++; - } - return n; -} - - -static void funcargs (LexState *ls, expdesc *f) { - FuncState *fs = ls->fs; - expdesc args; - int base, nparams; - int line = ls->linenumber; - switch (ls->t.token) { - case '(': { /* funcargs -> `(' [ explist1 ] `)' */ - if (line != ls->lastline) - luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)"); - luaX_next(ls); - if (ls->t.token == ')') /* arg list is empty? */ - args.k = VVOID; - else { - explist1(ls, &args); - luaK_setmultret(fs, &args); - } - check_match(ls, ')', '(', line); - break; - } - case '{': { /* funcargs -> constructor */ - constructor(ls, &args); - break; - } - case TK_STRING: { /* funcargs -> STRING */ - codestring(ls, &args, ls->t.seminfo.ts); - luaX_next(ls); /* must use `seminfo' before `next' */ - break; - } - default: { - luaX_syntaxerror(ls, "function arguments expected"); - return; - } - } - lua_assert(f->k == VNONRELOC); - base = f->u.s.info; /* base register for call */ - if (hasmultret(args.k)) - nparams = LUA_MULTRET; /* open call */ - else { - if (args.k != VVOID) - luaK_exp2nextreg(fs, &args); /* close last argument */ - nparams = fs->freereg - (base+1); - } - init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2)); - luaK_fixline(fs, line); - fs->freereg = base+1; /* call remove function and arguments and leaves - (unless changed) one result */ -} - - - - -/* -** {====================================================================== -** Expression parsing -** ======================================================================= -*/ - - -static void prefixexp (LexState *ls, expdesc *v) { - /* prefixexp -> NAME | '(' expr ')' */ - switch (ls->t.token) { - case '(': { - int line = ls->linenumber; - luaX_next(ls); - expr(ls, v); - check_match(ls, ')', '(', line); - luaK_dischargevars(ls->fs, v); - return; - } - case TK_NAME: { - singlevar(ls, v); - return; - } - default: { - luaX_syntaxerror(ls, "unexpected symbol"); - return; - } - } -} - - -static void primaryexp (LexState *ls, expdesc *v) { - /* primaryexp -> - prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */ - FuncState *fs = ls->fs; - prefixexp(ls, v); - for (;;) { - switch (ls->t.token) { - case '.': { /* field */ - field(ls, v); - break; - } - case '[': { /* `[' exp1 `]' */ - expdesc key; - luaK_exp2anyreg(fs, v); - yindex(ls, &key); - luaK_indexed(fs, v, &key); - break; - } - case ':': { /* `:' NAME funcargs */ - expdesc key; - luaX_next(ls); - checkname(ls, &key); - luaK_self(fs, v, &key); - funcargs(ls, v); - break; - } - case '(': case TK_STRING: case '{': { /* funcargs */ - luaK_exp2nextreg(fs, v); - funcargs(ls, v); - break; - } - default: return; - } - } -} - - -static void simpleexp (LexState *ls, expdesc *v) { - /* simpleexp -> NUMBER | STRING | NIL | true | false | ... | - constructor | FUNCTION body | primaryexp */ - switch (ls->t.token) { - case TK_NUMBER: { - init_exp(v, VKNUM, 0); - v->u.nval = ls->t.seminfo.r; - break; - } - case TK_STRING: { - codestring(ls, v, ls->t.seminfo.ts); - break; - } - case TK_NIL: { - init_exp(v, VNIL, 0); - break; - } - case TK_TRUE: { - init_exp(v, VTRUE, 0); - break; - } - case TK_FALSE: { - init_exp(v, VFALSE, 0); - break; - } - case TK_DOTS: { /* vararg */ - FuncState *fs = ls->fs; - check_condition(ls, fs->f->is_vararg, - "cannot use " LUA_QL("...") " outside a vararg function"); - fs->f->is_vararg &= ~VARARG_NEEDSARG; /* don't need 'arg' */ - init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0)); - break; - } - case '{': { /* constructor */ - constructor(ls, v); - return; - } - case TK_FUNCTION: { - luaX_next(ls); - body(ls, v, 0, ls->linenumber); - return; - } - default: { - primaryexp(ls, v); - return; - } - } - luaX_next(ls); -} - - -static UnOpr getunopr (int op) { - switch (op) { - case TK_NOT: return OPR_NOT; - case '-': return OPR_MINUS; - case '#': return OPR_LEN; - default: return OPR_NOUNOPR; - } -} - - -static BinOpr getbinopr (int op) { - switch (op) { - case '+': return OPR_ADD; - case '-': return OPR_SUB; - case '*': return OPR_MUL; - case '/': return OPR_DIV; - case '%': return OPR_MOD; - case '^': return OPR_POW; - case TK_CONCAT: return OPR_CONCAT; - case TK_NE: return OPR_NE; - case TK_EQ: return OPR_EQ; - case '<': return OPR_LT; - case TK_LE: return OPR_LE; - case '>': return OPR_GT; - case TK_GE: return OPR_GE; - case TK_AND: return OPR_AND; - case TK_OR: return OPR_OR; - default: return OPR_NOBINOPR; - } -} - - -static const struct { - lu_byte left; /* left priority for each binary operator */ - lu_byte right; /* right priority */ -} priority[] = { /* ORDER OPR */ - {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `/' `%' */ - {10, 9}, {5, 4}, /* power and concat (right associative) */ - {3, 3}, {3, 3}, /* equality and inequality */ - {3, 3}, {3, 3}, {3, 3}, {3, 3}, /* order */ - {2, 2}, {1, 1} /* logical (and/or) */ -}; - -#define UNARY_PRIORITY 8 /* priority for unary operators */ - - -/* -** subexpr -> (simpleexp | unop subexpr) { binop subexpr } -** where `binop' is any binary operator with a priority higher than `limit' -*/ -static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) { - BinOpr op; - UnOpr uop; - enterlevel(ls); - uop = getunopr(ls->t.token); - if (uop != OPR_NOUNOPR) { - luaX_next(ls); - subexpr(ls, v, UNARY_PRIORITY); - luaK_prefix(ls->fs, uop, v); - } - else simpleexp(ls, v); - /* expand while operators have priorities higher than `limit' */ - op = getbinopr(ls->t.token); - while (op != OPR_NOBINOPR && priority[op].left > limit) { - expdesc v2; - BinOpr nextop; - luaX_next(ls); - luaK_infix(ls->fs, op, v); - /* read sub-expression with higher priority */ - nextop = subexpr(ls, &v2, priority[op].right); - luaK_posfix(ls->fs, op, v, &v2); - op = nextop; - } - leavelevel(ls); - return op; /* return first untreated operator */ -} - - -static void expr (LexState *ls, expdesc *v) { - subexpr(ls, v, 0); -} - -/* }==================================================================== */ - - - -/* -** {====================================================================== -** Rules for Statements -** ======================================================================= -*/ - - -static int block_follow (int token) { - switch (token) { - case TK_ELSE: case TK_ELSEIF: case TK_END: - case TK_UNTIL: case TK_EOS: - return 1; - default: return 0; - } -} - - -static void block (LexState *ls) { - /* block -> chunk */ - FuncState *fs = ls->fs; - BlockCnt bl; - enterblock(fs, &bl, 0); - chunk(ls); - lua_assert(bl.breaklist == NO_JUMP); - leaveblock(fs); -} - - -/* -** structure to chain all variables in the left-hand side of an -** assignment -*/ -struct LHS_assign { - struct LHS_assign *prev; - expdesc v; /* variable (global, local, upvalue, or indexed) */ -}; - - -/* -** check whether, in an assignment to a local variable, the local variable -** is needed in a previous assignment (to a table). If so, save original -** local value in a safe place and use this safe copy in the previous -** assignment. -*/ -static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) { - FuncState *fs = ls->fs; - int extra = fs->freereg; /* eventual position to save local variable */ - int conflict = 0; - for (; lh; lh = lh->prev) { - if (lh->v.k == VINDEXED) { - if (lh->v.u.s.info == v->u.s.info) { /* conflict? */ - conflict = 1; - lh->v.u.s.info = extra; /* previous assignment will use safe copy */ - } - if (lh->v.u.s.aux == v->u.s.info) { /* conflict? */ - conflict = 1; - lh->v.u.s.aux = extra; /* previous assignment will use safe copy */ - } - } - } - if (conflict) { - luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.s.info, 0); /* make copy */ - luaK_reserveregs(fs, 1); - } -} - - -static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) { - expdesc e; - check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED, - "syntax error"); - if (testnext(ls, ',')) { /* assignment -> `,' primaryexp assignment */ - struct LHS_assign nv; - nv.prev = lh; - primaryexp(ls, &nv.v); - if (nv.v.k == VLOCAL) - check_conflict(ls, lh, &nv.v); - luaY_checklimit(ls->fs, nvars, LUAI_MAXCCALLS - ls->L->nCcalls, - "variables in assignment"); - assignment(ls, &nv, nvars+1); - } - else { /* assignment -> `=' explist1 */ - int nexps; - checknext(ls, '='); - nexps = explist1(ls, &e); - if (nexps != nvars) { - adjust_assign(ls, nvars, nexps, &e); - if (nexps > nvars) - ls->fs->freereg -= nexps - nvars; /* remove extra values */ - } - else { - luaK_setoneret(ls->fs, &e); /* close last expression */ - luaK_storevar(ls->fs, &lh->v, &e); - return; /* avoid default */ - } - } - init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */ - luaK_storevar(ls->fs, &lh->v, &e); -} - - -static int cond (LexState *ls) { - /* cond -> exp */ - expdesc v; - expr(ls, &v); /* read condition */ - if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */ - luaK_goiftrue(ls->fs, &v); - return v.f; -} - - -static void breakstat (LexState *ls) { - FuncState *fs = ls->fs; - BlockCnt *bl = fs->bl; - int upval = 0; - while (bl && !bl->isbreakable) { - upval |= bl->upval; - bl = bl->previous; - } - if (!bl) - luaX_syntaxerror(ls, "no loop to break"); - if (upval) - luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0); - luaK_concat(fs, &bl->breaklist, luaK_jump(fs)); -} - - -static void whilestat (LexState *ls, int line) { - /* whilestat -> WHILE cond DO block END */ - FuncState *fs = ls->fs; - int whileinit; - int condexit; - BlockCnt bl; - luaX_next(ls); /* skip WHILE */ - whileinit = luaK_getlabel(fs); - condexit = cond(ls); - enterblock(fs, &bl, 1); - checknext(ls, TK_DO); - block(ls); - luaK_patchlist(fs, luaK_jump(fs), whileinit); - check_match(ls, TK_END, TK_WHILE, line); - leaveblock(fs); - luaK_patchtohere(fs, condexit); /* false conditions finish the loop */ -} - - -static void repeatstat (LexState *ls, int line) { - /* repeatstat -> REPEAT block UNTIL cond */ - int condexit; - FuncState *fs = ls->fs; - int repeat_init = luaK_getlabel(fs); - BlockCnt bl1, bl2; - enterblock(fs, &bl1, 1); /* loop block */ - enterblock(fs, &bl2, 0); /* scope block */ - luaX_next(ls); /* skip REPEAT */ - chunk(ls); - check_match(ls, TK_UNTIL, TK_REPEAT, line); - condexit = cond(ls); /* read condition (inside scope block) */ - if (!bl2.upval) { /* no upvalues? */ - leaveblock(fs); /* finish scope */ - luaK_patchlist(ls->fs, condexit, repeat_init); /* close the loop */ - } - else { /* complete semantics when there are upvalues */ - breakstat(ls); /* if condition then break */ - luaK_patchtohere(ls->fs, condexit); /* else... */ - leaveblock(fs); /* finish scope... */ - luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init); /* and repeat */ - } - leaveblock(fs); /* finish loop */ -} - - -static int exp1 (LexState *ls) { - expdesc e; - int k; - expr(ls, &e); - k = e.k; - luaK_exp2nextreg(ls->fs, &e); - return k; -} - - -static void forbody (LexState *ls, int base, int line, int nvars, int isnum) { - /* forbody -> DO block */ - BlockCnt bl; - FuncState *fs = ls->fs; - int prep, endfor; - adjustlocalvars(ls, 3); /* control variables */ - checknext(ls, TK_DO); - prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs); - enterblock(fs, &bl, 0); /* scope for declared variables */ - adjustlocalvars(ls, nvars); - luaK_reserveregs(fs, nvars); - block(ls); - leaveblock(fs); /* end of scope for declared variables */ - luaK_patchtohere(fs, prep); - endfor = (isnum) ? luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP) : - luaK_codeABC(fs, OP_TFORLOOP, base, 0, nvars); - luaK_fixline(fs, line); /* pretend that `OP_FOR' starts the loop */ - luaK_patchlist(fs, (isnum ? endfor : luaK_jump(fs)), prep + 1); -} - - -static void fornum (LexState *ls, TString *varname, int line) { - /* fornum -> NAME = exp1,exp1[,exp1] forbody */ - FuncState *fs = ls->fs; - int base = fs->freereg; - new_localvarliteral(ls, "(for index)", 0); - new_localvarliteral(ls, "(for limit)", 1); - new_localvarliteral(ls, "(for step)", 2); - new_localvar(ls, varname, 3); - checknext(ls, '='); - exp1(ls); /* initial value */ - checknext(ls, ','); - exp1(ls); /* limit */ - if (testnext(ls, ',')) - exp1(ls); /* optional step */ - else { /* default step = 1 */ - luaK_codeABx(fs, OP_LOADK, fs->freereg, luaK_numberK(fs, 1)); - luaK_reserveregs(fs, 1); - } - forbody(ls, base, line, 1, 1); -} - - -static void forlist (LexState *ls, TString *indexname) { - /* forlist -> NAME {,NAME} IN explist1 forbody */ - FuncState *fs = ls->fs; - expdesc e; - int nvars = 0; - int line; - int base = fs->freereg; - /* create control variables */ - new_localvarliteral(ls, "(for generator)", nvars++); - new_localvarliteral(ls, "(for state)", nvars++); - new_localvarliteral(ls, "(for control)", nvars++); - /* create declared variables */ - new_localvar(ls, indexname, nvars++); - while (testnext(ls, ',')) - new_localvar(ls, str_checkname(ls), nvars++); - checknext(ls, TK_IN); - line = ls->linenumber; - adjust_assign(ls, 3, explist1(ls, &e), &e); - luaK_checkstack(fs, 3); /* extra space to call generator */ - forbody(ls, base, line, nvars - 3, 0); -} - - -static void forstat (LexState *ls, int line) { - /* forstat -> FOR (fornum | forlist) END */ - FuncState *fs = ls->fs; - TString *varname; - BlockCnt bl; - enterblock(fs, &bl, 1); /* scope for loop and control variables */ - luaX_next(ls); /* skip `for' */ - varname = str_checkname(ls); /* first variable name */ - switch (ls->t.token) { - case '=': fornum(ls, varname, line); break; - case ',': case TK_IN: forlist(ls, varname); break; - default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected"); - } - check_match(ls, TK_END, TK_FOR, line); - leaveblock(fs); /* loop scope (`break' jumps to this point) */ -} - - -static int test_then_block (LexState *ls) { - /* test_then_block -> [IF | ELSEIF] cond THEN block */ - int condexit; - luaX_next(ls); /* skip IF or ELSEIF */ - condexit = cond(ls); - checknext(ls, TK_THEN); - block(ls); /* `then' part */ - return condexit; -} - - -static void ifstat (LexState *ls, int line) { - /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ - FuncState *fs = ls->fs; - int flist; - int escapelist = NO_JUMP; - flist = test_then_block(ls); /* IF cond THEN block */ - while (ls->t.token == TK_ELSEIF) { - luaK_concat(fs, &escapelist, luaK_jump(fs)); - luaK_patchtohere(fs, flist); - flist = test_then_block(ls); /* ELSEIF cond THEN block */ - } - if (ls->t.token == TK_ELSE) { - luaK_concat(fs, &escapelist, luaK_jump(fs)); - luaK_patchtohere(fs, flist); - luaX_next(ls); /* skip ELSE (after patch, for correct line info) */ - block(ls); /* `else' part */ - } - else - luaK_concat(fs, &escapelist, flist); - luaK_patchtohere(fs, escapelist); - check_match(ls, TK_END, TK_IF, line); -} - - -static void localfunc (LexState *ls) { - expdesc v, b; - FuncState *fs = ls->fs; - new_localvar(ls, str_checkname(ls), 0); - init_exp(&v, VLOCAL, fs->freereg); - luaK_reserveregs(fs, 1); - adjustlocalvars(ls, 1); - body(ls, &b, 0, ls->linenumber); - luaK_storevar(fs, &v, &b); - /* debug information will only see the variable after this point! */ - getlocvar(fs, fs->nactvar - 1).startpc = fs->pc; -} - - -static void localstat (LexState *ls) { - /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */ - int nvars = 0; - int nexps; - expdesc e; - do { - new_localvar(ls, str_checkname(ls), nvars++); - } while (testnext(ls, ',')); - if (testnext(ls, '=')) - nexps = explist1(ls, &e); - else { - e.k = VVOID; - nexps = 0; - } - adjust_assign(ls, nvars, nexps, &e); - adjustlocalvars(ls, nvars); -} - - -static int funcname (LexState *ls, expdesc *v) { - /* funcname -> NAME {field} [`:' NAME] */ - int needself = 0; - singlevar(ls, v); - while (ls->t.token == '.') - field(ls, v); - if (ls->t.token == ':') { - needself = 1; - field(ls, v); - } - return needself; -} - - -static void funcstat (LexState *ls, int line) { - /* funcstat -> FUNCTION funcname body */ - int needself; - expdesc v, b; - luaX_next(ls); /* skip FUNCTION */ - needself = funcname(ls, &v); - body(ls, &b, needself, line); - luaK_storevar(ls->fs, &v, &b); - luaK_fixline(ls->fs, line); /* definition `happens' in the first line */ -} - - -static void exprstat (LexState *ls) { - /* stat -> func | assignment */ - FuncState *fs = ls->fs; - struct LHS_assign v; - primaryexp(ls, &v.v); - if (v.v.k == VCALL) /* stat -> func */ - SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */ - else { /* stat -> assignment */ - v.prev = NULL; - assignment(ls, &v, 1); - } -} - - -static void retstat (LexState *ls) { - /* stat -> RETURN explist */ - FuncState *fs = ls->fs; - expdesc e; - int first, nret; /* registers with returned values */ - luaX_next(ls); /* skip RETURN */ - if (block_follow(ls->t.token) || ls->t.token == ';') - first = nret = 0; /* return no values */ - else { - nret = explist1(ls, &e); /* optional return values */ - if (hasmultret(e.k)) { - luaK_setmultret(fs, &e); - if (e.k == VCALL && nret == 1) { /* tail call? */ - SET_OPCODE(getcode(fs,&e), OP_TAILCALL); - lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar); - } - first = fs->nactvar; - nret = LUA_MULTRET; /* return all values */ - } - else { - if (nret == 1) /* only one single value? */ - first = luaK_exp2anyreg(fs, &e); - else { - luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */ - first = fs->nactvar; /* return all `active' values */ - lua_assert(nret == fs->freereg - first); - } - } - } - luaK_ret(fs, first, nret); -} - - -static int statement (LexState *ls) { - int line = ls->linenumber; /* may be needed for error messages */ - switch (ls->t.token) { - case TK_IF: { /* stat -> ifstat */ - ifstat(ls, line); - return 0; - } - case TK_WHILE: { /* stat -> whilestat */ - whilestat(ls, line); - return 0; - } - case TK_DO: { /* stat -> DO block END */ - luaX_next(ls); /* skip DO */ - block(ls); - check_match(ls, TK_END, TK_DO, line); - return 0; - } - case TK_FOR: { /* stat -> forstat */ - forstat(ls, line); - return 0; - } - case TK_REPEAT: { /* stat -> repeatstat */ - repeatstat(ls, line); - return 0; - } - case TK_FUNCTION: { - funcstat(ls, line); /* stat -> funcstat */ - return 0; - } - case TK_LOCAL: { /* stat -> localstat */ - luaX_next(ls); /* skip LOCAL */ - if (testnext(ls, TK_FUNCTION)) /* local function? */ - localfunc(ls); - else - localstat(ls); - return 0; - } - case TK_RETURN: { /* stat -> retstat */ - retstat(ls); - return 1; /* must be last statement */ - } - case TK_BREAK: { /* stat -> breakstat */ - luaX_next(ls); /* skip BREAK */ - breakstat(ls); - return 1; /* must be last statement */ - } - default: { - exprstat(ls); - return 0; /* to avoid warnings */ - } - } -} - - -static void chunk (LexState *ls) { - /* chunk -> { stat [`;'] } */ - int islast = 0; - enterlevel(ls); - while (!islast && !block_follow(ls->t.token)) { - islast = statement(ls); - testnext(ls, ';'); - lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg && - ls->fs->freereg >= ls->fs->nactvar); - ls->fs->freereg = ls->fs->nactvar; /* free registers */ - } - leavelevel(ls); -} - -/* }====================================================================== */ diff --git a/Utilities/lua-5.1.5/src/lparser.h b/Utilities/lua-5.1.5/src/lparser.h deleted file mode 100644 index 18836afd1..000000000 --- a/Utilities/lua-5.1.5/src/lparser.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -** $Id: lparser.h,v 1.57.1.1 2007/12/27 13:02:25 roberto Exp $ -** Lua Parser -** See Copyright Notice in lua.h -*/ - -#ifndef lparser_h -#define lparser_h - -#include "llimits.h" -#include "lobject.h" -#include "lzio.h" - - -/* -** Expression descriptor -*/ - -typedef enum { - VVOID, /* no value */ - VNIL, - VTRUE, - VFALSE, - VK, /* info = index of constant in `k' */ - VKNUM, /* nval = numerical value */ - VLOCAL, /* info = local register */ - VUPVAL, /* info = index of upvalue in `upvalues' */ - VGLOBAL, /* info = index of table; aux = index of global name in `k' */ - VINDEXED, /* info = table register; aux = index register (or `k') */ - VJMP, /* info = instruction pc */ - VRELOCABLE, /* info = instruction pc */ - VNONRELOC, /* info = result register */ - VCALL, /* info = instruction pc */ - VVARARG /* info = instruction pc */ -} expkind; - -typedef struct expdesc { - expkind k; - union { - struct { int info, aux; } s; - lua_Number nval; - } u; - int t; /* patch list of `exit when true' */ - int f; /* patch list of `exit when false' */ -} expdesc; - - -typedef struct upvaldesc { - lu_byte k; - lu_byte info; -} upvaldesc; - - -struct BlockCnt; /* defined in lparser.c */ - - -/* state needed to generate code for a given function */ -typedef struct FuncState { - Proto *f; /* current function header */ - Table *h; /* table to find (and reuse) elements in `k' */ - struct FuncState *prev; /* enclosing function */ - struct LexState *ls; /* lexical state */ - struct lua_State *L; /* copy of the Lua state */ - struct BlockCnt *bl; /* chain of current blocks */ - int pc; /* next position to code (equivalent to `ncode') */ - int lasttarget; /* `pc' of last `jump target' */ - int jpc; /* list of pending jumps to `pc' */ - int freereg; /* first free register */ - int nk; /* number of elements in `k' */ - int np; /* number of elements in `p' */ - short nlocvars; /* number of elements in `locvars' */ - lu_byte nactvar; /* number of active local variables */ - upvaldesc upvalues[LUAI_MAXUPVALUES]; /* upvalues */ - unsigned short actvar[LUAI_MAXVARS]; /* declared-variable stack */ -} FuncState; - - -LUAI_FUNC Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, - const char *name); - - -#endif diff --git a/Utilities/lua-5.1.5/src/lstate.c b/Utilities/lua-5.1.5/src/lstate.c deleted file mode 100644 index 4313b83a0..000000000 --- a/Utilities/lua-5.1.5/src/lstate.c +++ /dev/null @@ -1,214 +0,0 @@ -/* -** $Id: lstate.c,v 2.36.1.2 2008/01/03 15:20:39 roberto Exp $ -** Global State -** See Copyright Notice in lua.h -*/ - - -#include - -#define lstate_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lgc.h" -#include "llex.h" -#include "lmem.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" - - -#define state_size(x) (sizeof(x) + LUAI_EXTRASPACE) -#define fromstate(l) (cast(lu_byte *, (l)) - LUAI_EXTRASPACE) -#define tostate(l) (cast(lua_State *, cast(lu_byte *, l) + LUAI_EXTRASPACE)) - - -/* -** Main thread combines a thread state and the global state -*/ -typedef struct LG { - lua_State l; - global_State g; -} LG; - - - -static void stack_init (lua_State *L1, lua_State *L) { - /* initialize CallInfo array */ - L1->base_ci = luaM_newvector(L, BASIC_CI_SIZE, CallInfo); - L1->ci = L1->base_ci; - L1->size_ci = BASIC_CI_SIZE; - L1->end_ci = L1->base_ci + L1->size_ci - 1; - /* initialize stack array */ - L1->stack = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, TValue); - L1->stacksize = BASIC_STACK_SIZE + EXTRA_STACK; - L1->top = L1->stack; - L1->stack_last = L1->stack+(L1->stacksize - EXTRA_STACK)-1; - /* initialize first ci */ - L1->ci->func = L1->top; - setnilvalue(L1->top++); /* `function' entry for this `ci' */ - L1->base = L1->ci->base = L1->top; - L1->ci->top = L1->top + LUA_MINSTACK; -} - - -static void freestack (lua_State *L, lua_State *L1) { - luaM_freearray(L, L1->base_ci, L1->size_ci, CallInfo); - luaM_freearray(L, L1->stack, L1->stacksize, TValue); -} - - -/* -** open parts that may cause memory-allocation errors -*/ -static void f_luaopen (lua_State *L, void *ud) { - global_State *g = G(L); - UNUSED(ud); - stack_init(L, L); /* init stack */ - sethvalue(L, gt(L), luaH_new(L, 0, 2)); /* table of globals */ - sethvalue(L, registry(L), luaH_new(L, 0, 2)); /* registry */ - luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */ - luaT_init(L); - luaX_init(L); - luaS_fix(luaS_newliteral(L, MEMERRMSG)); - g->GCthreshold = 4*g->totalbytes; -} - - -static void preinit_state (lua_State *L, global_State *g) { - G(L) = g; - L->stack = NULL; - L->stacksize = 0; - L->errorJmp = NULL; - L->hook = NULL; - L->hookmask = 0; - L->basehookcount = 0; - L->allowhook = 1; - resethookcount(L); - L->openupval = NULL; - L->size_ci = 0; - L->nCcalls = L->baseCcalls = 0; - L->status = 0; - L->base_ci = L->ci = NULL; - L->savedpc = NULL; - L->errfunc = 0; - setnilvalue(gt(L)); -} - - -static void close_state (lua_State *L) { - global_State *g = G(L); - luaF_close(L, L->stack); /* close all upvalues for this thread */ - luaC_freeall(L); /* collect all objects */ - lua_assert(g->rootgc == obj2gco(L)); - lua_assert(g->strt.nuse == 0); - luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size, TString *); - luaZ_freebuffer(L, &g->buff); - freestack(L, L); - lua_assert(g->totalbytes == sizeof(LG)); - (*g->frealloc)(g->ud, fromstate(L), state_size(LG), 0); -} - - -lua_State *luaE_newthread (lua_State *L) { - lua_State *L1 = tostate(luaM_malloc(L, state_size(lua_State))); - luaC_link(L, obj2gco(L1), LUA_TTHREAD); - preinit_state(L1, G(L)); - stack_init(L1, L); /* init stack */ - setobj2n(L, gt(L1), gt(L)); /* share table of globals */ - L1->hookmask = L->hookmask; - L1->basehookcount = L->basehookcount; - L1->hook = L->hook; - resethookcount(L1); - lua_assert(iswhite(obj2gco(L1))); - return L1; -} - - -void luaE_freethread (lua_State *L, lua_State *L1) { - luaF_close(L1, L1->stack); /* close all upvalues for this thread */ - lua_assert(L1->openupval == NULL); - luai_userstatefree(L1); - freestack(L, L1); - luaM_freemem(L, fromstate(L1), state_size(lua_State)); -} - - -LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { - int i; - lua_State *L; - global_State *g; - void *l = (*f)(ud, NULL, 0, state_size(LG)); - if (l == NULL) return NULL; - L = tostate(l); - g = &((LG *)L)->g; - L->next = NULL; - L->tt = LUA_TTHREAD; - g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT); - L->marked = luaC_white(g); - set2bits(L->marked, FIXEDBIT, SFIXEDBIT); - preinit_state(L, g); - g->frealloc = f; - g->ud = ud; - g->mainthread = L; - g->uvhead.u.l.prev = &g->uvhead; - g->uvhead.u.l.next = &g->uvhead; - g->GCthreshold = 0; /* mark it as unfinished state */ - g->strt.size = 0; - g->strt.nuse = 0; - g->strt.hash = NULL; - setnilvalue(registry(L)); - luaZ_initbuffer(L, &g->buff); - g->panic = NULL; - g->gcstate = GCSpause; - g->rootgc = obj2gco(L); - g->sweepstrgc = 0; - g->sweepgc = &g->rootgc; - g->gray = NULL; - g->grayagain = NULL; - g->weak = NULL; - g->tmudata = NULL; - g->totalbytes = sizeof(LG); - g->gcpause = LUAI_GCPAUSE; - g->gcstepmul = LUAI_GCMUL; - g->gcdept = 0; - for (i=0; imt[i] = NULL; - if (luaD_rawrunprotected(L, f_luaopen, NULL) != 0) { - /* memory allocation error: free partial state */ - close_state(L); - L = NULL; - } - else - luai_userstateopen(L); - return L; -} - - -static void callallgcTM (lua_State *L, void *ud) { - UNUSED(ud); - luaC_callGCTM(L); /* call GC metamethods for all udata */ -} - - -LUA_API void lua_close (lua_State *L) { - L = G(L)->mainthread; /* only the main thread can be closed */ - lua_lock(L); - luaF_close(L, L->stack); /* close all upvalues for this thread */ - luaC_separateudata(L, 1); /* separate udata that have GC metamethods */ - L->errfunc = 0; /* no error function during GC metamethods */ - do { /* repeat until no more errors */ - L->ci = L->base_ci; - L->base = L->top = L->ci->base; - L->nCcalls = L->baseCcalls = 0; - } while (luaD_rawrunprotected(L, callallgcTM, NULL) != 0); - lua_assert(G(L)->tmudata == NULL); - luai_userstateclose(L); - close_state(L); -} - diff --git a/Utilities/lua-5.1.5/src/lstate.h b/Utilities/lua-5.1.5/src/lstate.h deleted file mode 100644 index 3bc575b6b..000000000 --- a/Utilities/lua-5.1.5/src/lstate.h +++ /dev/null @@ -1,169 +0,0 @@ -/* -** $Id: lstate.h,v 2.24.1.2 2008/01/03 15:20:39 roberto Exp $ -** Global State -** See Copyright Notice in lua.h -*/ - -#ifndef lstate_h -#define lstate_h - -#include "lua.h" - -#include "lobject.h" -#include "ltm.h" -#include "lzio.h" - - - -struct lua_longjmp; /* defined in ldo.c */ - - -/* table of globals */ -#define gt(L) (&L->l_gt) - -/* registry */ -#define registry(L) (&G(L)->l_registry) - - -/* extra stack space to handle TM calls and some other extras */ -#define EXTRA_STACK 5 - - -#define BASIC_CI_SIZE 8 - -#define BASIC_STACK_SIZE (2*LUA_MINSTACK) - - - -typedef struct stringtable { - GCObject **hash; - lu_int32 nuse; /* number of elements */ - int size; -} stringtable; - - -/* -** informations about a call -*/ -typedef struct CallInfo { - StkId base; /* base for this function */ - StkId func; /* function index in the stack */ - StkId top; /* top for this function */ - const Instruction *savedpc; - int nresults; /* expected number of results from this function */ - int tailcalls; /* number of tail calls lost under this entry */ -} CallInfo; - - - -#define curr_func(L) (clvalue(L->ci->func)) -#define ci_func(ci) (clvalue((ci)->func)) -#define f_isLua(ci) (!ci_func(ci)->c.isC) -#define isLua(ci) (ttisfunction((ci)->func) && f_isLua(ci)) - - -/* -** `global state', shared by all threads of this state -*/ -typedef struct global_State { - stringtable strt; /* hash table for strings */ - lua_Alloc frealloc; /* function to reallocate memory */ - void *ud; /* auxiliary data to `frealloc' */ - lu_byte currentwhite; - lu_byte gcstate; /* state of garbage collector */ - int sweepstrgc; /* position of sweep in `strt' */ - GCObject *rootgc; /* list of all collectable objects */ - GCObject **sweepgc; /* position of sweep in `rootgc' */ - GCObject *gray; /* list of gray objects */ - GCObject *grayagain; /* list of objects to be traversed atomically */ - GCObject *weak; /* list of weak tables (to be cleared) */ - GCObject *tmudata; /* last element of list of userdata to be GC */ - Mbuffer buff; /* temporary buffer for string concatentation */ - lu_mem GCthreshold; - lu_mem totalbytes; /* number of bytes currently allocated */ - lu_mem estimate; /* an estimate of number of bytes actually in use */ - lu_mem gcdept; /* how much GC is `behind schedule' */ - int gcpause; /* size of pause between successive GCs */ - int gcstepmul; /* GC `granularity' */ - lua_CFunction panic; /* to be called in unprotected errors */ - TValue l_registry; - struct lua_State *mainthread; - UpVal uvhead; /* head of double-linked list of all open upvalues */ - struct Table *mt[NUM_TAGS]; /* metatables for basic types */ - TString *tmname[TM_N]; /* array with tag-method names */ -} global_State; - - -/* -** `per thread' state -*/ -struct lua_State { - CommonHeader; - lu_byte status; - StkId top; /* first free slot in the stack */ - StkId base; /* base of current function */ - global_State *l_G; - CallInfo *ci; /* call info for current function */ - const Instruction *savedpc; /* `savedpc' of current function */ - StkId stack_last; /* last free slot in the stack */ - StkId stack; /* stack base */ - CallInfo *end_ci; /* points after end of ci array*/ - CallInfo *base_ci; /* array of CallInfo's */ - int stacksize; - int size_ci; /* size of array `base_ci' */ - unsigned short nCcalls; /* number of nested C calls */ - unsigned short baseCcalls; /* nested C calls when resuming coroutine */ - lu_byte hookmask; - lu_byte allowhook; - int basehookcount; - int hookcount; - lua_Hook hook; - TValue l_gt; /* table of globals */ - TValue env; /* temporary place for environments */ - GCObject *openupval; /* list of open upvalues in this stack */ - GCObject *gclist; - struct lua_longjmp *errorJmp; /* current error recover point */ - ptrdiff_t errfunc; /* current error handling function (stack index) */ -}; - - -#define G(L) (L->l_G) - - -/* -** Union of all collectable objects -*/ -union GCObject { - GCheader gch; - union TString ts; - union Udata u; - union Closure cl; - struct Table h; - struct Proto p; - struct UpVal uv; - struct lua_State th; /* thread */ -}; - - -/* macros to convert a GCObject into a specific value */ -#define rawgco2ts(o) check_exp((o)->gch.tt == LUA_TSTRING, &((o)->ts)) -#define gco2ts(o) (&rawgco2ts(o)->tsv) -#define rawgco2u(o) check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u)) -#define gco2u(o) (&rawgco2u(o)->uv) -#define gco2cl(o) check_exp((o)->gch.tt == LUA_TFUNCTION, &((o)->cl)) -#define gco2h(o) check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h)) -#define gco2p(o) check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p)) -#define gco2uv(o) check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv)) -#define ngcotouv(o) \ - check_exp((o) == NULL || (o)->gch.tt == LUA_TUPVAL, &((o)->uv)) -#define gco2th(o) check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th)) - -/* macro to convert any Lua object into a GCObject */ -#define obj2gco(v) (cast(GCObject *, (v))) - - -LUAI_FUNC lua_State *luaE_newthread (lua_State *L); -LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1); - -#endif - diff --git a/Utilities/lua-5.1.5/src/lstring.c b/Utilities/lua-5.1.5/src/lstring.c deleted file mode 100644 index 49113151c..000000000 --- a/Utilities/lua-5.1.5/src/lstring.c +++ /dev/null @@ -1,111 +0,0 @@ -/* -** $Id: lstring.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $ -** String table (keeps all strings handled by Lua) -** See Copyright Notice in lua.h -*/ - - -#include - -#define lstring_c -#define LUA_CORE - -#include "lua.h" - -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" -#include "lstring.h" - - - -void luaS_resize (lua_State *L, int newsize) { - GCObject **newhash; - stringtable *tb; - int i; - if (G(L)->gcstate == GCSsweepstring) - return; /* cannot resize during GC traverse */ - newhash = luaM_newvector(L, newsize, GCObject *); - tb = &G(L)->strt; - for (i=0; isize; i++) { - GCObject *p = tb->hash[i]; - while (p) { /* for each node in the list */ - GCObject *next = p->gch.next; /* save next */ - unsigned int h = gco2ts(p)->hash; - int h1 = lmod(h, newsize); /* new position */ - lua_assert(cast_int(h%newsize) == lmod(h, newsize)); - p->gch.next = newhash[h1]; /* chain it */ - newhash[h1] = p; - p = next; - } - } - luaM_freearray(L, tb->hash, tb->size, TString *); - tb->size = newsize; - tb->hash = newhash; -} - - -static TString *newlstr (lua_State *L, const char *str, size_t l, - unsigned int h) { - TString *ts; - stringtable *tb; - if (l+1 > (MAX_SIZET - sizeof(TString))/sizeof(char)) - luaM_toobig(L); - ts = cast(TString *, luaM_malloc(L, (l+1)*sizeof(char)+sizeof(TString))); - ts->tsv.len = l; - ts->tsv.hash = h; - ts->tsv.marked = luaC_white(G(L)); - ts->tsv.tt = LUA_TSTRING; - ts->tsv.reserved = 0; - memcpy(ts+1, str, l*sizeof(char)); - ((char *)(ts+1))[l] = '\0'; /* ending 0 */ - tb = &G(L)->strt; - h = lmod(h, tb->size); - ts->tsv.next = tb->hash[h]; /* chain new entry */ - tb->hash[h] = obj2gco(ts); - tb->nuse++; - if (tb->nuse > cast(lu_int32, tb->size) && tb->size <= MAX_INT/2) - luaS_resize(L, tb->size*2); /* too crowded */ - return ts; -} - - -TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { - GCObject *o; - unsigned int h = cast(unsigned int, l); /* seed */ - size_t step = (l>>5)+1; /* if string is too long, don't hash all its chars */ - size_t l1; - for (l1=l; l1>=step; l1-=step) /* compute hash */ - h = h ^ ((h<<5)+(h>>2)+cast(unsigned char, str[l1-1])); - for (o = G(L)->strt.hash[lmod(h, G(L)->strt.size)]; - o != NULL; - o = o->gch.next) { - TString *ts = rawgco2ts(o); - if (ts->tsv.len == l && (memcmp(str, getstr(ts), l) == 0)) { - /* string may be dead */ - if (isdead(G(L), o)) changewhite(o); - return ts; - } - } - return newlstr(L, str, l, h); /* not found */ -} - - -Udata *luaS_newudata (lua_State *L, size_t s, Table *e) { - Udata *u; - if (s > MAX_SIZET - sizeof(Udata)) - luaM_toobig(L); - u = cast(Udata *, luaM_malloc(L, s + sizeof(Udata))); - u->uv.marked = luaC_white(G(L)); /* is not finalized */ - u->uv.tt = LUA_TUSERDATA; - u->uv.len = s; - u->uv.metatable = NULL; - u->uv.env = e; - /* chain it on udata list (after main thread) */ - u->uv.next = G(L)->mainthread->next; - G(L)->mainthread->next = obj2gco(u); - return u; -} - diff --git a/Utilities/lua-5.1.5/src/lstring.h b/Utilities/lua-5.1.5/src/lstring.h deleted file mode 100644 index 73a2ff8b3..000000000 --- a/Utilities/lua-5.1.5/src/lstring.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -** $Id: lstring.h,v 1.43.1.1 2007/12/27 13:02:25 roberto Exp $ -** String table (keep all strings handled by Lua) -** See Copyright Notice in lua.h -*/ - -#ifndef lstring_h -#define lstring_h - - -#include "lgc.h" -#include "lobject.h" -#include "lstate.h" - - -#define sizestring(s) (sizeof(union TString)+((s)->len+1)*sizeof(char)) - -#define sizeudata(u) (sizeof(union Udata)+(u)->len) - -#define luaS_new(L, s) (luaS_newlstr(L, s, strlen(s))) -#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \ - (sizeof(s)/sizeof(char))-1)) - -#define luaS_fix(s) l_setbit((s)->tsv.marked, FIXEDBIT) - -LUAI_FUNC void luaS_resize (lua_State *L, int newsize); -LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e); -LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l); - - -#endif diff --git a/Utilities/lua-5.1.5/src/lstrlib.c b/Utilities/lua-5.1.5/src/lstrlib.c deleted file mode 100644 index 7a03489be..000000000 --- a/Utilities/lua-5.1.5/src/lstrlib.c +++ /dev/null @@ -1,871 +0,0 @@ -/* -** $Id: lstrlib.c,v 1.132.1.5 2010/05/14 15:34:19 roberto Exp $ -** Standard library for string operations and pattern-matching -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include -#include -#include - -#define lstrlib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - -/* macro to `unsign' a character */ -#define uchar(c) ((unsigned char)(c)) - - - -static int str_len (lua_State *L) { - size_t l; - luaL_checklstring(L, 1, &l); - lua_pushinteger(L, l); - return 1; -} - - -static ptrdiff_t posrelat (ptrdiff_t pos, size_t len) { - /* relative string position: negative means back from end */ - if (pos < 0) pos += (ptrdiff_t)len + 1; - return (pos >= 0) ? pos : 0; -} - - -static int str_sub (lua_State *L) { - size_t l; - const char *s = luaL_checklstring(L, 1, &l); - ptrdiff_t start = posrelat(luaL_checkinteger(L, 2), l); - ptrdiff_t end = posrelat(luaL_optinteger(L, 3, -1), l); - if (start < 1) start = 1; - if (end > (ptrdiff_t)l) end = (ptrdiff_t)l; - if (start <= end) - lua_pushlstring(L, s+start-1, end-start+1); - else lua_pushliteral(L, ""); - return 1; -} - - -static int str_reverse (lua_State *L) { - size_t l; - luaL_Buffer b; - const char *s = luaL_checklstring(L, 1, &l); - luaL_buffinit(L, &b); - while (l--) luaL_addchar(&b, s[l]); - luaL_pushresult(&b); - return 1; -} - - -static int str_lower (lua_State *L) { - size_t l; - size_t i; - luaL_Buffer b; - const char *s = luaL_checklstring(L, 1, &l); - luaL_buffinit(L, &b); - for (i=0; i 0) - luaL_addlstring(&b, s, l); - luaL_pushresult(&b); - return 1; -} - - -static int str_byte (lua_State *L) { - size_t l; - const char *s = luaL_checklstring(L, 1, &l); - ptrdiff_t posi = posrelat(luaL_optinteger(L, 2, 1), l); - ptrdiff_t pose = posrelat(luaL_optinteger(L, 3, posi), l); - int n, i; - if (posi <= 0) posi = 1; - if ((size_t)pose > l) pose = l; - if (posi > pose) return 0; /* empty interval; return no values */ - n = (int)(pose - posi + 1); - if (posi + n <= pose) /* overflow? */ - luaL_error(L, "string slice too long"); - luaL_checkstack(L, n, "string slice too long"); - for (i=0; i= ms->level || ms->capture[l].len == CAP_UNFINISHED) - return luaL_error(ms->L, "invalid capture index"); - return l; -} - - -static int capture_to_close (MatchState *ms) { - int level = ms->level; - for (level--; level>=0; level--) - if (ms->capture[level].len == CAP_UNFINISHED) return level; - return luaL_error(ms->L, "invalid pattern capture"); -} - - -static const char *classend (MatchState *ms, const char *p) { - switch (*p++) { - case L_ESC: { - if (*p == '\0') - luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")"); - return p+1; - } - case '[': { - if (*p == '^') p++; - do { /* look for a `]' */ - if (*p == '\0') - luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")"); - if (*(p++) == L_ESC && *p != '\0') - p++; /* skip escapes (e.g. `%]') */ - } while (*p != ']'); - return p+1; - } - default: { - return p; - } - } -} - - -static int match_class (int c, int cl) { - int res; - switch (tolower(cl)) { - case 'a' : res = isalpha(c); break; - case 'c' : res = iscntrl(c); break; - case 'd' : res = isdigit(c); break; - case 'l' : res = islower(c); break; - case 'p' : res = ispunct(c); break; - case 's' : res = isspace(c); break; - case 'u' : res = isupper(c); break; - case 'w' : res = isalnum(c); break; - case 'x' : res = isxdigit(c); break; - case 'z' : res = (c == 0); break; - default: return (cl == c); - } - return (islower(cl) ? res : !res); -} - - -static int matchbracketclass (int c, const char *p, const char *ec) { - int sig = 1; - if (*(p+1) == '^') { - sig = 0; - p++; /* skip the `^' */ - } - while (++p < ec) { - if (*p == L_ESC) { - p++; - if (match_class(c, uchar(*p))) - return sig; - } - else if ((*(p+1) == '-') && (p+2 < ec)) { - p+=2; - if (uchar(*(p-2)) <= c && c <= uchar(*p)) - return sig; - } - else if (uchar(*p) == c) return sig; - } - return !sig; -} - - -static int singlematch (int c, const char *p, const char *ep) { - switch (*p) { - case '.': return 1; /* matches any char */ - case L_ESC: return match_class(c, uchar(*(p+1))); - case '[': return matchbracketclass(c, p, ep-1); - default: return (uchar(*p) == c); - } -} - - -static const char *match (MatchState *ms, const char *s, const char *p); - - -static const char *matchbalance (MatchState *ms, const char *s, - const char *p) { - if (*p == 0 || *(p+1) == 0) - luaL_error(ms->L, "unbalanced pattern"); - if (*s != *p) return NULL; - else { - int b = *p; - int e = *(p+1); - int cont = 1; - while (++s < ms->src_end) { - if (*s == e) { - if (--cont == 0) return s+1; - } - else if (*s == b) cont++; - } - } - return NULL; /* string ends out of balance */ -} - - -static const char *max_expand (MatchState *ms, const char *s, - const char *p, const char *ep) { - ptrdiff_t i = 0; /* counts maximum expand for item */ - while ((s+i)src_end && singlematch(uchar(*(s+i)), p, ep)) - i++; - /* keeps trying to match with the maximum repetitions */ - while (i>=0) { - const char *res = match(ms, (s+i), ep+1); - if (res) return res; - i--; /* else didn't match; reduce 1 repetition to try again */ - } - return NULL; -} - - -static const char *min_expand (MatchState *ms, const char *s, - const char *p, const char *ep) { - for (;;) { - const char *res = match(ms, s, ep+1); - if (res != NULL) - return res; - else if (ssrc_end && singlematch(uchar(*s), p, ep)) - s++; /* try with one more repetition */ - else return NULL; - } -} - - -static const char *start_capture (MatchState *ms, const char *s, - const char *p, int what) { - const char *res; - int level = ms->level; - if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures"); - ms->capture[level].init = s; - ms->capture[level].len = what; - ms->level = level+1; - if ((res=match(ms, s, p)) == NULL) /* match failed? */ - ms->level--; /* undo capture */ - return res; -} - - -static const char *end_capture (MatchState *ms, const char *s, - const char *p) { - int l = capture_to_close(ms); - const char *res; - ms->capture[l].len = s - ms->capture[l].init; /* close capture */ - if ((res = match(ms, s, p)) == NULL) /* match failed? */ - ms->capture[l].len = CAP_UNFINISHED; /* undo capture */ - return res; -} - - -static const char *match_capture (MatchState *ms, const char *s, int l) { - size_t len; - l = check_capture(ms, l); - len = ms->capture[l].len; - if ((size_t)(ms->src_end-s) >= len && - memcmp(ms->capture[l].init, s, len) == 0) - return s+len; - else return NULL; -} - - -static const char *match (MatchState *ms, const char *s, const char *p) { - init: /* using goto's to optimize tail recursion */ - switch (*p) { - case '(': { /* start capture */ - if (*(p+1) == ')') /* position capture? */ - return start_capture(ms, s, p+2, CAP_POSITION); - else - return start_capture(ms, s, p+1, CAP_UNFINISHED); - } - case ')': { /* end capture */ - return end_capture(ms, s, p+1); - } - case L_ESC: { - switch (*(p+1)) { - case 'b': { /* balanced string? */ - s = matchbalance(ms, s, p+2); - if (s == NULL) return NULL; - p+=4; goto init; /* else return match(ms, s, p+4); */ - } - case 'f': { /* frontier? */ - const char *ep; char previous; - p += 2; - if (*p != '[') - luaL_error(ms->L, "missing " LUA_QL("[") " after " - LUA_QL("%%f") " in pattern"); - ep = classend(ms, p); /* points to what is next */ - previous = (s == ms->src_init) ? '\0' : *(s-1); - if (matchbracketclass(uchar(previous), p, ep-1) || - !matchbracketclass(uchar(*s), p, ep-1)) return NULL; - p=ep; goto init; /* else return match(ms, s, ep); */ - } - default: { - if (isdigit(uchar(*(p+1)))) { /* capture results (%0-%9)? */ - s = match_capture(ms, s, uchar(*(p+1))); - if (s == NULL) return NULL; - p+=2; goto init; /* else return match(ms, s, p+2) */ - } - goto dflt; /* case default */ - } - } - } - case '\0': { /* end of pattern */ - return s; /* match succeeded */ - } - case '$': { - if (*(p+1) == '\0') /* is the `$' the last char in pattern? */ - return (s == ms->src_end) ? s : NULL; /* check end of string */ - else goto dflt; - } - default: dflt: { /* it is a pattern item */ - const char *ep = classend(ms, p); /* points to what is next */ - int m = ssrc_end && singlematch(uchar(*s), p, ep); - switch (*ep) { - case '?': { /* optional */ - const char *res; - if (m && ((res=match(ms, s+1, ep+1)) != NULL)) - return res; - p=ep+1; goto init; /* else return match(ms, s, ep+1); */ - } - case '*': { /* 0 or more repetitions */ - return max_expand(ms, s, p, ep); - } - case '+': { /* 1 or more repetitions */ - return (m ? max_expand(ms, s+1, p, ep) : NULL); - } - case '-': { /* 0 or more repetitions (minimum) */ - return min_expand(ms, s, p, ep); - } - default: { - if (!m) return NULL; - s++; p=ep; goto init; /* else return match(ms, s+1, ep); */ - } - } - } - } -} - - - -static const char *lmemfind (const char *s1, size_t l1, - const char *s2, size_t l2) { - if (l2 == 0) return s1; /* empty strings are everywhere */ - else if (l2 > l1) return NULL; /* avoids a negative `l1' */ - else { - const char *init; /* to search for a `*s2' inside `s1' */ - l2--; /* 1st char will be checked by `memchr' */ - l1 = l1-l2; /* `s2' cannot be found after that */ - while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { - init++; /* 1st char is already checked */ - if (memcmp(init, s2+1, l2) == 0) - return init-1; - else { /* correct `l1' and `s1' to try again */ - l1 -= init-s1; - s1 = init; - } - } - return NULL; /* not found */ - } -} - - -static void push_onecapture (MatchState *ms, int i, const char *s, - const char *e) { - if (i >= ms->level) { - if (i == 0) /* ms->level == 0, too */ - lua_pushlstring(ms->L, s, e - s); /* add whole match */ - else - luaL_error(ms->L, "invalid capture index"); - } - else { - ptrdiff_t l = ms->capture[i].len; - if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture"); - if (l == CAP_POSITION) - lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1); - else - lua_pushlstring(ms->L, ms->capture[i].init, l); - } -} - - -static int push_captures (MatchState *ms, const char *s, const char *e) { - int i; - int nlevels = (ms->level == 0 && s) ? 1 : ms->level; - luaL_checkstack(ms->L, nlevels, "too many captures"); - for (i = 0; i < nlevels; i++) - push_onecapture(ms, i, s, e); - return nlevels; /* number of strings pushed */ -} - - -static int str_find_aux (lua_State *L, int find) { - size_t l1, l2; - const char *s = luaL_checklstring(L, 1, &l1); - const char *p = luaL_checklstring(L, 2, &l2); - ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1; - if (init < 0) init = 0; - else if ((size_t)(init) > l1) init = (ptrdiff_t)l1; - if (find && (lua_toboolean(L, 4) || /* explicit request? */ - strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */ - /* do a plain search */ - const char *s2 = lmemfind(s+init, l1-init, p, l2); - if (s2) { - lua_pushinteger(L, s2-s+1); - lua_pushinteger(L, s2-s+l2); - return 2; - } - } - else { - MatchState ms; - int anchor = (*p == '^') ? (p++, 1) : 0; - const char *s1=s+init; - ms.L = L; - ms.src_init = s; - ms.src_end = s+l1; - do { - const char *res; - ms.level = 0; - if ((res=match(&ms, s1, p)) != NULL) { - if (find) { - lua_pushinteger(L, s1-s+1); /* start */ - lua_pushinteger(L, res-s); /* end */ - return push_captures(&ms, NULL, 0) + 2; - } - else - return push_captures(&ms, s1, res); - } - } while (s1++ < ms.src_end && !anchor); - } - lua_pushnil(L); /* not found */ - return 1; -} - - -static int str_find (lua_State *L) { - return str_find_aux(L, 1); -} - - -static int str_match (lua_State *L) { - return str_find_aux(L, 0); -} - - -static int gmatch_aux (lua_State *L) { - MatchState ms; - size_t ls; - const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls); - const char *p = lua_tostring(L, lua_upvalueindex(2)); - const char *src; - ms.L = L; - ms.src_init = s; - ms.src_end = s+ls; - for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3)); - src <= ms.src_end; - src++) { - const char *e; - ms.level = 0; - if ((e = match(&ms, src, p)) != NULL) { - lua_Integer newstart = e-s; - if (e == src) newstart++; /* empty match? go at least one position */ - lua_pushinteger(L, newstart); - lua_replace(L, lua_upvalueindex(3)); - return push_captures(&ms, src, e); - } - } - return 0; /* not found */ -} - - -static int gmatch (lua_State *L) { - luaL_checkstring(L, 1); - luaL_checkstring(L, 2); - lua_settop(L, 2); - lua_pushinteger(L, 0); - lua_pushcclosure(L, gmatch_aux, 3); - return 1; -} - - -static int gfind_nodef (lua_State *L) { - return luaL_error(L, LUA_QL("string.gfind") " was renamed to " - LUA_QL("string.gmatch")); -} - - -static void add_s (MatchState *ms, luaL_Buffer *b, const char *s, - const char *e) { - size_t l, i; - const char *news = lua_tolstring(ms->L, 3, &l); - for (i = 0; i < l; i++) { - if (news[i] != L_ESC) - luaL_addchar(b, news[i]); - else { - i++; /* skip ESC */ - if (!isdigit(uchar(news[i]))) - luaL_addchar(b, news[i]); - else if (news[i] == '0') - luaL_addlstring(b, s, e - s); - else { - push_onecapture(ms, news[i] - '1', s, e); - luaL_addvalue(b); /* add capture to accumulated result */ - } - } - } -} - - -static void add_value (MatchState *ms, luaL_Buffer *b, const char *s, - const char *e) { - lua_State *L = ms->L; - switch (lua_type(L, 3)) { - case LUA_TNUMBER: - case LUA_TSTRING: { - add_s(ms, b, s, e); - return; - } - case LUA_TFUNCTION: { - int n; - lua_pushvalue(L, 3); - n = push_captures(ms, s, e); - lua_call(L, n, 1); - break; - } - case LUA_TTABLE: { - push_onecapture(ms, 0, s, e); - lua_gettable(L, 3); - break; - } - } - if (!lua_toboolean(L, -1)) { /* nil or false? */ - lua_pop(L, 1); - lua_pushlstring(L, s, e - s); /* keep original text */ - } - else if (!lua_isstring(L, -1)) - luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); - luaL_addvalue(b); /* add result to accumulator */ -} - - -static int str_gsub (lua_State *L) { - size_t srcl; - const char *src = luaL_checklstring(L, 1, &srcl); - const char *p = luaL_checkstring(L, 2); - int tr = lua_type(L, 3); - int max_s = luaL_optint(L, 4, srcl+1); - int anchor = (*p == '^') ? (p++, 1) : 0; - int n = 0; - MatchState ms; - luaL_Buffer b; - luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING || - tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3, - "string/function/table expected"); - luaL_buffinit(L, &b); - ms.L = L; - ms.src_init = src; - ms.src_end = src+srcl; - while (n < max_s) { - const char *e; - ms.level = 0; - e = match(&ms, src, p); - if (e) { - n++; - add_value(&ms, &b, src, e); - } - if (e && e>src) /* non empty match? */ - src = e; /* skip it */ - else if (src < ms.src_end) - luaL_addchar(&b, *src++); - else break; - if (anchor) break; - } - luaL_addlstring(&b, src, ms.src_end-src); - luaL_pushresult(&b); - lua_pushinteger(L, n); /* number of substitutions */ - return 2; -} - -/* }====================================================== */ - - -/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */ -#define MAX_ITEM 512 -/* valid flags in a format specification */ -#define FLAGS "-+ #0" -/* -** maximum size of each format specification (such as '%-099.99d') -** (+10 accounts for %99.99x plus margin of error) -*/ -#define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10) - - -static void addquoted (lua_State *L, luaL_Buffer *b, int arg) { - size_t l; - const char *s = luaL_checklstring(L, arg, &l); - luaL_addchar(b, '"'); - while (l--) { - switch (*s) { - case '"': case '\\': case '\n': { - luaL_addchar(b, '\\'); - luaL_addchar(b, *s); - break; - } - case '\r': { - luaL_addlstring(b, "\\r", 2); - break; - } - case '\0': { - luaL_addlstring(b, "\\000", 4); - break; - } - default: { - luaL_addchar(b, *s); - break; - } - } - s++; - } - luaL_addchar(b, '"'); -} - -static const char *scanformat (lua_State *L, const char *strfrmt, char *form) { - const char *p = strfrmt; - while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */ - if ((size_t)(p - strfrmt) >= sizeof(FLAGS)) - luaL_error(L, "invalid format (repeated flags)"); - if (isdigit(uchar(*p))) p++; /* skip width */ - if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ - if (*p == '.') { - p++; - if (isdigit(uchar(*p))) p++; /* skip precision */ - if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ - } - if (isdigit(uchar(*p))) - luaL_error(L, "invalid format (width or precision too long)"); - *(form++) = '%'; - strncpy(form, strfrmt, p - strfrmt + 1); - form += p - strfrmt + 1; - *form = '\0'; - return p; -} - - -static void addintlen (char *form) { - size_t l = strlen(form); - char spec = form[l - 1]; - strcpy(form + l - 1, LUA_INTFRMLEN); - form[l + sizeof(LUA_INTFRMLEN) - 2] = spec; - form[l + sizeof(LUA_INTFRMLEN) - 1] = '\0'; -} - - -static int str_format (lua_State *L) { - int top = lua_gettop(L); - int arg = 1; - size_t sfl; - const char *strfrmt = luaL_checklstring(L, arg, &sfl); - const char *strfrmt_end = strfrmt+sfl; - luaL_Buffer b; - luaL_buffinit(L, &b); - while (strfrmt < strfrmt_end) { - if (*strfrmt != L_ESC) - luaL_addchar(&b, *strfrmt++); - else if (*++strfrmt == L_ESC) - luaL_addchar(&b, *strfrmt++); /* %% */ - else { /* format item */ - char form[MAX_FORMAT]; /* to store the format (`%...') */ - char buff[MAX_ITEM]; /* to store the formatted item */ - if (++arg > top) - luaL_argerror(L, arg, "no value"); - strfrmt = scanformat(L, strfrmt, form); - switch (*strfrmt++) { - case 'c': { - sprintf(buff, form, (int)luaL_checknumber(L, arg)); - break; - } - case 'd': case 'i': { - addintlen(form); - sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg)); - break; - } - case 'o': case 'u': case 'x': case 'X': { - addintlen(form); - sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg)); - break; - } - case 'e': case 'E': case 'f': - case 'g': case 'G': { - sprintf(buff, form, (double)luaL_checknumber(L, arg)); - break; - } - case 'q': { - addquoted(L, &b, arg); - continue; /* skip the 'addsize' at the end */ - } - case 's': { - size_t l; - const char *s = luaL_checklstring(L, arg, &l); - if (!strchr(form, '.') && l >= 100) { - /* no precision and string is too long to be formatted; - keep original string */ - lua_pushvalue(L, arg); - luaL_addvalue(&b); - continue; /* skip the `addsize' at the end */ - } - else { - sprintf(buff, form, s); - break; - } - } - default: { /* also treat cases `pnLlh' */ - return luaL_error(L, "invalid option " LUA_QL("%%%c") " to " - LUA_QL("format"), *(strfrmt - 1)); - } - } - luaL_addlstring(&b, buff, strlen(buff)); - } - } - luaL_pushresult(&b); - return 1; -} - - -static const luaL_Reg strlib[] = { - {"byte", str_byte}, - {"char", str_char}, - {"dump", str_dump}, - {"find", str_find}, - {"format", str_format}, - {"gfind", gfind_nodef}, - {"gmatch", gmatch}, - {"gsub", str_gsub}, - {"len", str_len}, - {"lower", str_lower}, - {"match", str_match}, - {"rep", str_rep}, - {"reverse", str_reverse}, - {"sub", str_sub}, - {"upper", str_upper}, - {NULL, NULL} -}; - - -static void createmetatable (lua_State *L) { - lua_createtable(L, 0, 1); /* create metatable for strings */ - lua_pushliteral(L, ""); /* dummy string */ - lua_pushvalue(L, -2); - lua_setmetatable(L, -2); /* set string metatable */ - lua_pop(L, 1); /* pop dummy string */ - lua_pushvalue(L, -2); /* string library... */ - lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */ - lua_pop(L, 1); /* pop metatable */ -} - - -/* -** Open string library -*/ -LUALIB_API int luaopen_string (lua_State *L) { - luaL_register(L, LUA_STRLIBNAME, strlib); -#if defined(LUA_COMPAT_GFIND) - lua_getfield(L, -1, "gmatch"); - lua_setfield(L, -2, "gfind"); -#endif - createmetatable(L); - return 1; -} - diff --git a/Utilities/lua-5.1.5/src/ltable.c b/Utilities/lua-5.1.5/src/ltable.c deleted file mode 100644 index ec84f4fab..000000000 --- a/Utilities/lua-5.1.5/src/ltable.c +++ /dev/null @@ -1,588 +0,0 @@ -/* -** $Id: ltable.c,v 2.32.1.2 2007/12/28 15:32:23 roberto Exp $ -** Lua tables (hash) -** See Copyright Notice in lua.h -*/ - - -/* -** Implementation of tables (aka arrays, objects, or hash tables). -** Tables keep its elements in two parts: an array part and a hash part. -** Non-negative integer keys are all candidates to be kept in the array -** part. The actual size of the array is the largest `n' such that at -** least half the slots between 0 and n are in use. -** Hash uses a mix of chained scatter table with Brent's variation. -** A main invariant of these tables is that, if an element is not -** in its main position (i.e. the `original' position that its hash gives -** to it), then the colliding element is in its own main position. -** Hence even when the load factor reaches 100%, performance remains good. -*/ - -#include -#include - -#define ltable_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lgc.h" -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" -#include "ltable.h" - - -/* -** max size of array part is 2^MAXBITS -*/ -#if LUAI_BITSINT > 26 -#define MAXBITS 26 -#else -#define MAXBITS (LUAI_BITSINT-2) -#endif - -#define MAXASIZE (1 << MAXBITS) - - -#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) - -#define hashstr(t,str) hashpow2(t, (str)->tsv.hash) -#define hashboolean(t,p) hashpow2(t, p) - - -/* -** for some types, it is better to avoid modulus by power of 2, as -** they tend to have many 2 factors. -*/ -#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1)))) - - -#define hashpointer(t,p) hashmod(t, IntPoint(p)) - - -/* -** number of ints inside a lua_Number -*/ -#define numints cast_int(sizeof(lua_Number)/sizeof(int)) - - - -#define dummynode (&dummynode_) - -static const Node dummynode_ = { - {{NULL}, LUA_TNIL}, /* value */ - {{{NULL}, LUA_TNIL, NULL}} /* key */ -}; - - -/* -** hash for lua_Numbers -*/ -static Node *hashnum (const Table *t, lua_Number n) { - unsigned int a[numints]; - int i; - if (luai_numeq(n, 0)) /* avoid problems with -0 */ - return gnode(t, 0); - memcpy(a, &n, sizeof(a)); - for (i = 1; i < numints; i++) a[0] += a[i]; - return hashmod(t, a[0]); -} - - - -/* -** returns the `main' position of an element in a table (that is, the index -** of its hash value) -*/ -static Node *mainposition (const Table *t, const TValue *key) { - switch (ttype(key)) { - case LUA_TNUMBER: - return hashnum(t, nvalue(key)); - case LUA_TSTRING: - return hashstr(t, rawtsvalue(key)); - case LUA_TBOOLEAN: - return hashboolean(t, bvalue(key)); - case LUA_TLIGHTUSERDATA: - return hashpointer(t, pvalue(key)); - default: - return hashpointer(t, gcvalue(key)); - } -} - - -/* -** returns the index for `key' if `key' is an appropriate key to live in -** the array part of the table, -1 otherwise. -*/ -static int arrayindex (const TValue *key) { - if (ttisnumber(key)) { - lua_Number n = nvalue(key); - int k; - lua_number2int(k, n); - if (luai_numeq(cast_num(k), n)) - return k; - } - return -1; /* `key' did not match some condition */ -} - - -/* -** returns the index of a `key' for table traversals. First goes all -** elements in the array part, then elements in the hash part. The -** beginning of a traversal is signalled by -1. -*/ -static int findindex (lua_State *L, Table *t, StkId key) { - int i; - if (ttisnil(key)) return -1; /* first iteration */ - i = arrayindex(key); - if (0 < i && i <= t->sizearray) /* is `key' inside array part? */ - return i-1; /* yes; that's the index (corrected to C) */ - else { - Node *n = mainposition(t, key); - do { /* check whether `key' is somewhere in the chain */ - /* key may be dead already, but it is ok to use it in `next' */ - if (luaO_rawequalObj(key2tval(n), key) || - (ttype(gkey(n)) == LUA_TDEADKEY && iscollectable(key) && - gcvalue(gkey(n)) == gcvalue(key))) { - i = cast_int(n - gnode(t, 0)); /* key index in hash table */ - /* hash elements are numbered after array ones */ - return i + t->sizearray; - } - else n = gnext(n); - } while (n); - luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */ - return 0; /* to avoid warnings */ - } -} - - -int luaH_next (lua_State *L, Table *t, StkId key) { - int i = findindex(L, t, key); /* find original element */ - for (i++; i < t->sizearray; i++) { /* try first array part */ - if (!ttisnil(&t->array[i])) { /* a non-nil value? */ - setnvalue(key, cast_num(i+1)); - setobj2s(L, key+1, &t->array[i]); - return 1; - } - } - for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */ - if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */ - setobj2s(L, key, key2tval(gnode(t, i))); - setobj2s(L, key+1, gval(gnode(t, i))); - return 1; - } - } - return 0; /* no more elements */ -} - - -/* -** {============================================================= -** Rehash -** ============================================================== -*/ - - -static int computesizes (int nums[], int *narray) { - int i; - int twotoi; /* 2^i */ - int a = 0; /* number of elements smaller than 2^i */ - int na = 0; /* number of elements to go to array part */ - int n = 0; /* optimal size for array part */ - for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) { - if (nums[i] > 0) { - a += nums[i]; - if (a > twotoi/2) { /* more than half elements present? */ - n = twotoi; /* optimal size (till now) */ - na = a; /* all elements smaller than n will go to array part */ - } - } - if (a == *narray) break; /* all elements already counted */ - } - *narray = n; - lua_assert(*narray/2 <= na && na <= *narray); - return na; -} - - -static int countint (const TValue *key, int *nums) { - int k = arrayindex(key); - if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */ - nums[ceillog2(k)]++; /* count as such */ - return 1; - } - else - return 0; -} - - -static int numusearray (const Table *t, int *nums) { - int lg; - int ttlg; /* 2^lg */ - int ause = 0; /* summation of `nums' */ - int i = 1; /* count to traverse all array keys */ - for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */ - int lc = 0; /* counter */ - int lim = ttlg; - if (lim > t->sizearray) { - lim = t->sizearray; /* adjust upper limit */ - if (i > lim) - break; /* no more elements to count */ - } - /* count elements in range (2^(lg-1), 2^lg] */ - for (; i <= lim; i++) { - if (!ttisnil(&t->array[i-1])) - lc++; - } - nums[lg] += lc; - ause += lc; - } - return ause; -} - - -static int numusehash (const Table *t, int *nums, int *pnasize) { - int totaluse = 0; /* total number of elements */ - int ause = 0; /* summation of `nums' */ - int i = sizenode(t); - while (i--) { - Node *n = &t->node[i]; - if (!ttisnil(gval(n))) { - ause += countint(key2tval(n), nums); - totaluse++; - } - } - *pnasize += ause; - return totaluse; -} - - -static void setarrayvector (lua_State *L, Table *t, int size) { - int i; - luaM_reallocvector(L, t->array, t->sizearray, size, TValue); - for (i=t->sizearray; iarray[i]); - t->sizearray = size; -} - - -static void setnodevector (lua_State *L, Table *t, int size) { - int lsize; - if (size == 0) { /* no elements to hash part? */ - t->node = cast(Node *, dummynode); /* use common `dummynode' */ - lsize = 0; - } - else { - int i; - lsize = ceillog2(size); - if (lsize > MAXBITS) - luaG_runerror(L, "table overflow"); - size = twoto(lsize); - t->node = luaM_newvector(L, size, Node); - for (i=0; ilsizenode = cast_byte(lsize); - t->lastfree = gnode(t, size); /* all positions are free */ -} - - -static void resize (lua_State *L, Table *t, int nasize, int nhsize) { - int i; - int oldasize = t->sizearray; - int oldhsize = t->lsizenode; - Node *nold = t->node; /* save old hash ... */ - if (nasize > oldasize) /* array part must grow? */ - setarrayvector(L, t, nasize); - /* create new hash part with appropriate size */ - setnodevector(L, t, nhsize); - if (nasize < oldasize) { /* array part must shrink? */ - t->sizearray = nasize; - /* re-insert elements from vanishing slice */ - for (i=nasize; iarray[i])) - setobjt2t(L, luaH_setnum(L, t, i+1), &t->array[i]); - } - /* shrink array */ - luaM_reallocvector(L, t->array, oldasize, nasize, TValue); - } - /* re-insert elements from hash part */ - for (i = twoto(oldhsize) - 1; i >= 0; i--) { - Node *old = nold+i; - if (!ttisnil(gval(old))) - setobjt2t(L, luaH_set(L, t, key2tval(old)), gval(old)); - } - if (nold != dummynode) - luaM_freearray(L, nold, twoto(oldhsize), Node); /* free old array */ -} - - -void luaH_resizearray (lua_State *L, Table *t, int nasize) { - int nsize = (t->node == dummynode) ? 0 : sizenode(t); - resize(L, t, nasize, nsize); -} - - -static void rehash (lua_State *L, Table *t, const TValue *ek) { - int nasize, na; - int nums[MAXBITS+1]; /* nums[i] = number of keys between 2^(i-1) and 2^i */ - int i; - int totaluse; - for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */ - nasize = numusearray(t, nums); /* count keys in array part */ - totaluse = nasize; /* all those keys are integer keys */ - totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */ - /* count extra key */ - nasize += countint(ek, nums); - totaluse++; - /* compute new size for array part */ - na = computesizes(nums, &nasize); - /* resize the table to new computed sizes */ - resize(L, t, nasize, totaluse - na); -} - - - -/* -** }============================================================= -*/ - - -Table *luaH_new (lua_State *L, int narray, int nhash) { - Table *t = luaM_new(L, Table); - luaC_link(L, obj2gco(t), LUA_TTABLE); - t->metatable = NULL; - t->flags = cast_byte(~0); - /* temporary values (kept only if some malloc fails) */ - t->array = NULL; - t->sizearray = 0; - t->lsizenode = 0; - t->node = cast(Node *, dummynode); - setarrayvector(L, t, narray); - setnodevector(L, t, nhash); - return t; -} - - -void luaH_free (lua_State *L, Table *t) { - if (t->node != dummynode) - luaM_freearray(L, t->node, sizenode(t), Node); - luaM_freearray(L, t->array, t->sizearray, TValue); - luaM_free(L, t); -} - - -static Node *getfreepos (Table *t) { - while (t->lastfree-- > t->node) { - if (ttisnil(gkey(t->lastfree))) - return t->lastfree; - } - return NULL; /* could not find a free place */ -} - - - -/* -** inserts a new key into a hash table; first, check whether key's main -** position is free. If not, check whether colliding node is in its main -** position or not: if it is not, move colliding node to an empty place and -** put new key in its main position; otherwise (colliding node is in its main -** position), new key goes to an empty position. -*/ -static TValue *newkey (lua_State *L, Table *t, const TValue *key) { - Node *mp = mainposition(t, key); - if (!ttisnil(gval(mp)) || mp == dummynode) { - Node *othern; - Node *n = getfreepos(t); /* get a free place */ - if (n == NULL) { /* cannot find a free place? */ - rehash(L, t, key); /* grow table */ - return luaH_set(L, t, key); /* re-insert key into grown table */ - } - lua_assert(n != dummynode); - othern = mainposition(t, key2tval(mp)); - if (othern != mp) { /* is colliding node out of its main position? */ - /* yes; move colliding node into free position */ - while (gnext(othern) != mp) othern = gnext(othern); /* find previous */ - gnext(othern) = n; /* redo the chain with `n' in place of `mp' */ - *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */ - gnext(mp) = NULL; /* now `mp' is free */ - setnilvalue(gval(mp)); - } - else { /* colliding node is in its own main position */ - /* new node will go into free position */ - gnext(n) = gnext(mp); /* chain new position */ - gnext(mp) = n; - mp = n; - } - } - gkey(mp)->value = key->value; gkey(mp)->tt = key->tt; - luaC_barriert(L, t, key); - lua_assert(ttisnil(gval(mp))); - return gval(mp); -} - - -/* -** search function for integers -*/ -const TValue *luaH_getnum (Table *t, int key) { - /* (1 <= key && key <= t->sizearray) */ - if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray)) - return &t->array[key-1]; - else { - lua_Number nk = cast_num(key); - Node *n = hashnum(t, nk); - do { /* check whether `key' is somewhere in the chain */ - if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk)) - return gval(n); /* that's it */ - else n = gnext(n); - } while (n); - return luaO_nilobject; - } -} - - -/* -** search function for strings -*/ -const TValue *luaH_getstr (Table *t, TString *key) { - Node *n = hashstr(t, key); - do { /* check whether `key' is somewhere in the chain */ - if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key) - return gval(n); /* that's it */ - else n = gnext(n); - } while (n); - return luaO_nilobject; -} - - -/* -** main search function -*/ -const TValue *luaH_get (Table *t, const TValue *key) { - switch (ttype(key)) { - case LUA_TNIL: return luaO_nilobject; - case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key)); - case LUA_TNUMBER: { - int k; - lua_Number n = nvalue(key); - lua_number2int(k, n); - if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */ - return luaH_getnum(t, k); /* use specialized version */ - /* else go through */ - } - default: { - Node *n = mainposition(t, key); - do { /* check whether `key' is somewhere in the chain */ - if (luaO_rawequalObj(key2tval(n), key)) - return gval(n); /* that's it */ - else n = gnext(n); - } while (n); - return luaO_nilobject; - } - } -} - - -TValue *luaH_set (lua_State *L, Table *t, const TValue *key) { - const TValue *p = luaH_get(t, key); - t->flags = 0; - if (p != luaO_nilobject) - return cast(TValue *, p); - else { - if (ttisnil(key)) luaG_runerror(L, "table index is nil"); - else if (ttisnumber(key) && luai_numisnan(nvalue(key))) - luaG_runerror(L, "table index is NaN"); - return newkey(L, t, key); - } -} - - -TValue *luaH_setnum (lua_State *L, Table *t, int key) { - const TValue *p = luaH_getnum(t, key); - if (p != luaO_nilobject) - return cast(TValue *, p); - else { - TValue k; - setnvalue(&k, cast_num(key)); - return newkey(L, t, &k); - } -} - - -TValue *luaH_setstr (lua_State *L, Table *t, TString *key) { - const TValue *p = luaH_getstr(t, key); - if (p != luaO_nilobject) - return cast(TValue *, p); - else { - TValue k; - setsvalue(L, &k, key); - return newkey(L, t, &k); - } -} - - -static int unbound_search (Table *t, unsigned int j) { - unsigned int i = j; /* i is zero or a present index */ - j++; - /* find `i' and `j' such that i is present and j is not */ - while (!ttisnil(luaH_getnum(t, j))) { - i = j; - j *= 2; - if (j > cast(unsigned int, MAX_INT)) { /* overflow? */ - /* table was built with bad purposes: resort to linear search */ - i = 1; - while (!ttisnil(luaH_getnum(t, i))) i++; - return i - 1; - } - } - /* now do a binary search between them */ - while (j - i > 1) { - unsigned int m = (i+j)/2; - if (ttisnil(luaH_getnum(t, m))) j = m; - else i = m; - } - return i; -} - - -/* -** Try to find a boundary in table `t'. A `boundary' is an integer index -** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil). -*/ -int luaH_getn (Table *t) { - unsigned int j = t->sizearray; - if (j > 0 && ttisnil(&t->array[j - 1])) { - /* there is a boundary in the array part: (binary) search for it */ - unsigned int i = 0; - while (j - i > 1) { - unsigned int m = (i+j)/2; - if (ttisnil(&t->array[m - 1])) j = m; - else i = m; - } - return i; - } - /* else must find a boundary in hash part */ - else if (t->node == dummynode) /* hash part is empty? */ - return j; /* that is easy... */ - else return unbound_search(t, j); -} - - - -#if defined(LUA_DEBUG) - -Node *luaH_mainposition (const Table *t, const TValue *key) { - return mainposition(t, key); -} - -int luaH_isdummy (Node *n) { return n == dummynode; } - -#endif diff --git a/Utilities/lua-5.1.5/src/ltable.h b/Utilities/lua-5.1.5/src/ltable.h deleted file mode 100644 index f5b9d5ead..000000000 --- a/Utilities/lua-5.1.5/src/ltable.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** $Id: ltable.h,v 2.10.1.1 2007/12/27 13:02:25 roberto Exp $ -** Lua tables (hash) -** See Copyright Notice in lua.h -*/ - -#ifndef ltable_h -#define ltable_h - -#include "lobject.h" - - -#define gnode(t,i) (&(t)->node[i]) -#define gkey(n) (&(n)->i_key.nk) -#define gval(n) (&(n)->i_val) -#define gnext(n) ((n)->i_key.nk.next) - -#define key2tval(n) (&(n)->i_key.tvk) - - -LUAI_FUNC const TValue *luaH_getnum (Table *t, int key); -LUAI_FUNC TValue *luaH_setnum (lua_State *L, Table *t, int key); -LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); -LUAI_FUNC TValue *luaH_setstr (lua_State *L, Table *t, TString *key); -LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); -LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key); -LUAI_FUNC Table *luaH_new (lua_State *L, int narray, int lnhash); -LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, int nasize); -LUAI_FUNC void luaH_free (lua_State *L, Table *t); -LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key); -LUAI_FUNC int luaH_getn (Table *t); - - -#if defined(LUA_DEBUG) -LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key); -LUAI_FUNC int luaH_isdummy (Node *n); -#endif - - -#endif diff --git a/Utilities/lua-5.1.5/src/ltablib.c b/Utilities/lua-5.1.5/src/ltablib.c deleted file mode 100644 index b6d9cb4ac..000000000 --- a/Utilities/lua-5.1.5/src/ltablib.c +++ /dev/null @@ -1,287 +0,0 @@ -/* -** $Id: ltablib.c,v 1.38.1.3 2008/02/14 16:46:58 roberto Exp $ -** Library for Table Manipulation -** See Copyright Notice in lua.h -*/ - - -#include - -#define ltablib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - -#define aux_getn(L,n) (luaL_checktype(L, n, LUA_TTABLE), luaL_getn(L, n)) - - -static int foreachi (lua_State *L) { - int i; - int n = aux_getn(L, 1); - luaL_checktype(L, 2, LUA_TFUNCTION); - for (i=1; i <= n; i++) { - lua_pushvalue(L, 2); /* function */ - lua_pushinteger(L, i); /* 1st argument */ - lua_rawgeti(L, 1, i); /* 2nd argument */ - lua_call(L, 2, 1); - if (!lua_isnil(L, -1)) - return 1; - lua_pop(L, 1); /* remove nil result */ - } - return 0; -} - - -static int foreach (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - luaL_checktype(L, 2, LUA_TFUNCTION); - lua_pushnil(L); /* first key */ - while (lua_next(L, 1)) { - lua_pushvalue(L, 2); /* function */ - lua_pushvalue(L, -3); /* key */ - lua_pushvalue(L, -3); /* value */ - lua_call(L, 2, 1); - if (!lua_isnil(L, -1)) - return 1; - lua_pop(L, 2); /* remove value and result */ - } - return 0; -} - - -static int maxn (lua_State *L) { - lua_Number max = 0; - luaL_checktype(L, 1, LUA_TTABLE); - lua_pushnil(L); /* first key */ - while (lua_next(L, 1)) { - lua_pop(L, 1); /* remove value */ - if (lua_type(L, -1) == LUA_TNUMBER) { - lua_Number v = lua_tonumber(L, -1); - if (v > max) max = v; - } - } - lua_pushnumber(L, max); - return 1; -} - - -static int getn (lua_State *L) { - lua_pushinteger(L, aux_getn(L, 1)); - return 1; -} - - -static int setn (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); -#ifndef luaL_setn - luaL_setn(L, 1, luaL_checkint(L, 2)); -#else - luaL_error(L, LUA_QL("setn") " is obsolete"); -#endif - lua_pushvalue(L, 1); - return 1; -} - - -static int tinsert (lua_State *L) { - int e = aux_getn(L, 1) + 1; /* first empty element */ - int pos; /* where to insert new element */ - switch (lua_gettop(L)) { - case 2: { /* called with only 2 arguments */ - pos = e; /* insert new element at the end */ - break; - } - case 3: { - int i; - pos = luaL_checkint(L, 2); /* 2nd argument is the position */ - if (pos > e) e = pos; /* `grow' array if necessary */ - for (i = e; i > pos; i--) { /* move up elements */ - lua_rawgeti(L, 1, i-1); - lua_rawseti(L, 1, i); /* t[i] = t[i-1] */ - } - break; - } - default: { - return luaL_error(L, "wrong number of arguments to " LUA_QL("insert")); - } - } - luaL_setn(L, 1, e); /* new size */ - lua_rawseti(L, 1, pos); /* t[pos] = v */ - return 0; -} - - -static int tremove (lua_State *L) { - int e = aux_getn(L, 1); - int pos = luaL_optint(L, 2, e); - if (!(1 <= pos && pos <= e)) /* position is outside bounds? */ - return 0; /* nothing to remove */ - luaL_setn(L, 1, e - 1); /* t.n = n-1 */ - lua_rawgeti(L, 1, pos); /* result = t[pos] */ - for ( ;pos= P */ - while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) { - if (i>u) luaL_error(L, "invalid order function for sorting"); - lua_pop(L, 1); /* remove a[i] */ - } - /* repeat --j until a[j] <= P */ - while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) { - if (j - -#define ltm_c -#define LUA_CORE - -#include "lua.h" - -#include "lobject.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" - - - -const char *const luaT_typenames[] = { - "nil", "boolean", "userdata", "number", - "string", "table", "function", "userdata", "thread", - "proto", "upval" -}; - - -void luaT_init (lua_State *L) { - static const char *const luaT_eventname[] = { /* ORDER TM */ - "__index", "__newindex", - "__gc", "__mode", "__eq", - "__add", "__sub", "__mul", "__div", "__mod", - "__pow", "__unm", "__len", "__lt", "__le", - "__concat", "__call" - }; - int i; - for (i=0; itmname[i] = luaS_new(L, luaT_eventname[i]); - luaS_fix(G(L)->tmname[i]); /* never collect these names */ - } -} - - -/* -** function to be used with macro "fasttm": optimized for absence of -** tag methods -*/ -const TValue *luaT_gettm (Table *events, TMS event, TString *ename) { - const TValue *tm = luaH_getstr(events, ename); - lua_assert(event <= TM_EQ); - if (ttisnil(tm)) { /* no tag method? */ - events->flags |= cast_byte(1u<metatable; - break; - case LUA_TUSERDATA: - mt = uvalue(o)->metatable; - break; - default: - mt = G(L)->mt[ttype(o)]; - } - return (mt ? luaH_getstr(mt, G(L)->tmname[event]) : luaO_nilobject); -} - diff --git a/Utilities/lua-5.1.5/src/ltm.h b/Utilities/lua-5.1.5/src/ltm.h deleted file mode 100644 index 64343b781..000000000 --- a/Utilities/lua-5.1.5/src/ltm.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -** $Id: ltm.h,v 2.6.1.1 2007/12/27 13:02:25 roberto Exp $ -** Tag methods -** See Copyright Notice in lua.h -*/ - -#ifndef ltm_h -#define ltm_h - - -#include "lobject.h" - - -/* -* WARNING: if you change the order of this enumeration, -* grep "ORDER TM" -*/ -typedef enum { - TM_INDEX, - TM_NEWINDEX, - TM_GC, - TM_MODE, - TM_EQ, /* last tag method with `fast' access */ - TM_ADD, - TM_SUB, - TM_MUL, - TM_DIV, - TM_MOD, - TM_POW, - TM_UNM, - TM_LEN, - TM_LT, - TM_LE, - TM_CONCAT, - TM_CALL, - TM_N /* number of elements in the enum */ -} TMS; - - - -#define gfasttm(g,et,e) ((et) == NULL ? NULL : \ - ((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e])) - -#define fasttm(l,et,e) gfasttm(G(l), et, e) - -LUAI_DATA const char *const luaT_typenames[]; - - -LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename); -LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, - TMS event); -LUAI_FUNC void luaT_init (lua_State *L); - -#endif diff --git a/Utilities/lua-5.1.5/src/lua.c b/Utilities/lua-5.1.5/src/lua.c deleted file mode 100644 index 3a4660932..000000000 --- a/Utilities/lua-5.1.5/src/lua.c +++ /dev/null @@ -1,392 +0,0 @@ -/* -** $Id: lua.c,v 1.160.1.2 2007/12/28 15:32:23 roberto Exp $ -** Lua stand-alone interpreter -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include -#include - -#define lua_c - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - - -static lua_State *globalL = NULL; - -static const char *progname = LUA_PROGNAME; - - - -static void lstop (lua_State *L, lua_Debug *ar) { - (void)ar; /* unused arg. */ - lua_sethook(L, NULL, 0, 0); - luaL_error(L, "interrupted!"); -} - - -static void laction (int i) { - signal(i, SIG_DFL); /* if another SIGINT happens before lstop, - terminate process (default action) */ - lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1); -} - - -static void print_usage (void) { - fprintf(stderr, - "usage: %s [options] [script [args]].\n" - "Available options are:\n" - " -e stat execute string " LUA_QL("stat") "\n" - " -l name require library " LUA_QL("name") "\n" - " -i enter interactive mode after executing " LUA_QL("script") "\n" - " -v show version information\n" - " -- stop handling options\n" - " - execute stdin and stop handling options\n" - , - progname); - fflush(stderr); -} - - -static void l_message (const char *pname, const char *msg) { - if (pname) fprintf(stderr, "%s: ", pname); - fprintf(stderr, "%s\n", msg); - fflush(stderr); -} - - -static int report (lua_State *L, int status) { - if (status && !lua_isnil(L, -1)) { - const char *msg = lua_tostring(L, -1); - if (msg == NULL) msg = "(error object is not a string)"; - l_message(progname, msg); - lua_pop(L, 1); - } - return status; -} - - -static int traceback (lua_State *L) { - if (!lua_isstring(L, 1)) /* 'message' not a string? */ - return 1; /* keep it intact */ - lua_getfield(L, LUA_GLOBALSINDEX, "debug"); - if (!lua_istable(L, -1)) { - lua_pop(L, 1); - return 1; - } - lua_getfield(L, -1, "traceback"); - if (!lua_isfunction(L, -1)) { - lua_pop(L, 2); - return 1; - } - lua_pushvalue(L, 1); /* pass error message */ - lua_pushinteger(L, 2); /* skip this function and traceback */ - lua_call(L, 2, 1); /* call debug.traceback */ - return 1; -} - - -static int docall (lua_State *L, int narg, int clear) { - int status; - int base = lua_gettop(L) - narg; /* function index */ - lua_pushcfunction(L, traceback); /* push traceback function */ - lua_insert(L, base); /* put it under chunk and args */ - signal(SIGINT, laction); - status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base); - signal(SIGINT, SIG_DFL); - lua_remove(L, base); /* remove traceback function */ - /* force a complete garbage collection in case of errors */ - if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0); - return status; -} - - -static void print_version (void) { - l_message(NULL, LUA_RELEASE " " LUA_COPYRIGHT); -} - - -static int getargs (lua_State *L, char **argv, int n) { - int narg; - int i; - int argc = 0; - while (argv[argc]) argc++; /* count total number of arguments */ - narg = argc - (n + 1); /* number of arguments to the script */ - luaL_checkstack(L, narg + 3, "too many arguments to script"); - for (i=n+1; i < argc; i++) - lua_pushstring(L, argv[i]); - lua_createtable(L, narg, n + 1); - for (i=0; i < argc; i++) { - lua_pushstring(L, argv[i]); - lua_rawseti(L, -2, i - n); - } - return narg; -} - - -static int dofile (lua_State *L, const char *name) { - int status = luaL_loadfile(L, name) || docall(L, 0, 1); - return report(L, status); -} - - -static int dostring (lua_State *L, const char *s, const char *name) { - int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1); - return report(L, status); -} - - -static int dolibrary (lua_State *L, const char *name) { - lua_getglobal(L, "require"); - lua_pushstring(L, name); - return report(L, docall(L, 1, 1)); -} - - -static const char *get_prompt (lua_State *L, int firstline) { - const char *p; - lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2"); - p = lua_tostring(L, -1); - if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2); - lua_pop(L, 1); /* remove global */ - return p; -} - - -static int incomplete (lua_State *L, int status) { - if (status == LUA_ERRSYNTAX) { - size_t lmsg; - const char *msg = lua_tolstring(L, -1, &lmsg); - const char *tp = msg + lmsg - (sizeof(LUA_QL("")) - 1); - if (strstr(msg, LUA_QL("")) == tp) { - lua_pop(L, 1); - return 1; - } - } - return 0; /* else... */ -} - - -static int pushline (lua_State *L, int firstline) { - char buffer[LUA_MAXINPUT]; - char *b = buffer; - size_t l; - const char *prmt = get_prompt(L, firstline); - if (lua_readline(L, b, prmt) == 0) - return 0; /* no input */ - l = strlen(b); - if (l > 0 && b[l-1] == '\n') /* line ends with newline? */ - b[l-1] = '\0'; /* remove it */ - if (firstline && b[0] == '=') /* first line starts with `=' ? */ - lua_pushfstring(L, "return %s", b+1); /* change it to `return' */ - else - lua_pushstring(L, b); - lua_freeline(L, b); - return 1; -} - - -static int loadline (lua_State *L) { - int status; - lua_settop(L, 0); - if (!pushline(L, 1)) - return -1; /* no input */ - for (;;) { /* repeat until gets a complete line */ - status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin"); - if (!incomplete(L, status)) break; /* cannot try to add lines? */ - if (!pushline(L, 0)) /* no more input? */ - return -1; - lua_pushliteral(L, "\n"); /* add a new line... */ - lua_insert(L, -2); /* ...between the two lines */ - lua_concat(L, 3); /* join them */ - } - lua_saveline(L, 1); - lua_remove(L, 1); /* remove line */ - return status; -} - - -static void dotty (lua_State *L) { - int status; - const char *oldprogname = progname; - progname = NULL; - while ((status = loadline(L)) != -1) { - if (status == 0) status = docall(L, 0, 0); - report(L, status); - if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */ - lua_getglobal(L, "print"); - lua_insert(L, 1); - if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0) - l_message(progname, lua_pushfstring(L, - "error calling " LUA_QL("print") " (%s)", - lua_tostring(L, -1))); - } - } - lua_settop(L, 0); /* clear stack */ - fputs("\n", stdout); - fflush(stdout); - progname = oldprogname; -} - - -static int handle_script (lua_State *L, char **argv, int n) { - int status; - const char *fname; - int narg = getargs(L, argv, n); /* collect arguments */ - lua_setglobal(L, "arg"); - fname = argv[n]; - if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0) - fname = NULL; /* stdin */ - status = luaL_loadfile(L, fname); - lua_insert(L, -(narg+1)); - if (status == 0) - status = docall(L, narg, 0); - else - lua_pop(L, narg); - return report(L, status); -} - - -/* check that argument has no extra characters at the end */ -#define notail(x) {if ((x)[2] != '\0') return -1;} - - -static int collectargs (char **argv, int *pi, int *pv, int *pe) { - int i; - for (i = 1; argv[i] != NULL; i++) { - if (argv[i][0] != '-') /* not an option? */ - return i; - switch (argv[i][1]) { /* option */ - case '-': - notail(argv[i]); - return (argv[i+1] != NULL ? i+1 : 0); - case '\0': - return i; - case 'i': - notail(argv[i]); - *pi = 1; /* go through */ - case 'v': - notail(argv[i]); - *pv = 1; - break; - case 'e': - *pe = 1; /* go through */ - case 'l': - if (argv[i][2] == '\0') { - i++; - if (argv[i] == NULL) return -1; - } - break; - default: return -1; /* invalid option */ - } - } - return 0; -} - - -static int runargs (lua_State *L, char **argv, int n) { - int i; - for (i = 1; i < n; i++) { - if (argv[i] == NULL) continue; - lua_assert(argv[i][0] == '-'); - switch (argv[i][1]) { /* option */ - case 'e': { - const char *chunk = argv[i] + 2; - if (*chunk == '\0') chunk = argv[++i]; - lua_assert(chunk != NULL); - if (dostring(L, chunk, "=(command line)") != 0) - return 1; - break; - } - case 'l': { - const char *filename = argv[i] + 2; - if (*filename == '\0') filename = argv[++i]; - lua_assert(filename != NULL); - if (dolibrary(L, filename)) - return 1; /* stop if file fails */ - break; - } - default: break; - } - } - return 0; -} - - -static int handle_luainit (lua_State *L) { - const char *init = getenv(LUA_INIT); - if (init == NULL) return 0; /* status OK */ - else if (init[0] == '@') - return dofile(L, init+1); - else - return dostring(L, init, "=" LUA_INIT); -} - - -struct Smain { - int argc; - char **argv; - int status; -}; - - -static int pmain (lua_State *L) { - struct Smain *s = (struct Smain *)lua_touserdata(L, 1); - char **argv = s->argv; - int script; - int has_i = 0, has_v = 0, has_e = 0; - globalL = L; - if (argv[0] && argv[0][0]) progname = argv[0]; - lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */ - luaL_openlibs(L); /* open libraries */ - lua_gc(L, LUA_GCRESTART, 0); - s->status = handle_luainit(L); - if (s->status != 0) return 0; - script = collectargs(argv, &has_i, &has_v, &has_e); - if (script < 0) { /* invalid args? */ - print_usage(); - s->status = 1; - return 0; - } - if (has_v) print_version(); - s->status = runargs(L, argv, (script > 0) ? script : s->argc); - if (s->status != 0) return 0; - if (script) - s->status = handle_script(L, argv, script); - if (s->status != 0) return 0; - if (has_i) - dotty(L); - else if (script == 0 && !has_e && !has_v) { - if (lua_stdin_is_tty()) { - print_version(); - dotty(L); - } - else dofile(L, NULL); /* executes stdin as a file */ - } - return 0; -} - - -int main (int argc, char **argv) { - int status; - struct Smain s; - lua_State *L = lua_open(); /* create state */ - if (L == NULL) { - l_message(argv[0], "cannot create state: not enough memory"); - return EXIT_FAILURE; - } - s.argc = argc; - s.argv = argv; - status = lua_cpcall(L, &pmain, &s); - report(L, status); - lua_close(L); - return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS; -} - diff --git a/Utilities/lua-5.1.5/src/lua.h b/Utilities/lua-5.1.5/src/lua.h deleted file mode 100644 index a4b73e743..000000000 --- a/Utilities/lua-5.1.5/src/lua.h +++ /dev/null @@ -1,388 +0,0 @@ -/* -** $Id: lua.h,v 1.218.1.7 2012/01/13 20:36:20 roberto Exp $ -** Lua - An Extensible Extension Language -** Lua.org, PUC-Rio, Brazil (http://www.lua.org) -** See Copyright Notice at the end of this file -*/ - - -#ifndef lua_h -#define lua_h - -#include -#include - - -#include "luaconf.h" - - -#define LUA_VERSION "Lua 5.1" -#define LUA_RELEASE "Lua 5.1.5" -#define LUA_VERSION_NUM 501 -#define LUA_COPYRIGHT "Copyright (C) 1994-2012 Lua.org, PUC-Rio" -#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes" - - -/* mark for precompiled code (`Lua') */ -#define LUA_SIGNATURE "\033Lua" - -/* option for multiple returns in `lua_pcall' and `lua_call' */ -#define LUA_MULTRET (-1) - - -/* -** pseudo-indices -*/ -#define LUA_REGISTRYINDEX (-10000) -#define LUA_ENVIRONINDEX (-10001) -#define LUA_GLOBALSINDEX (-10002) -#define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i)) - - -/* thread status; 0 is OK */ -#define LUA_YIELD 1 -#define LUA_ERRRUN 2 -#define LUA_ERRSYNTAX 3 -#define LUA_ERRMEM 4 -#define LUA_ERRERR 5 - - -typedef struct lua_State lua_State; - -typedef int (*lua_CFunction) (lua_State *L); - - -/* -** functions that read/write blocks when loading/dumping Lua chunks -*/ -typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); - -typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud); - - -/* -** prototype for memory-allocation functions -*/ -typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); - - -/* -** basic types -*/ -#define LUA_TNONE (-1) - -#define LUA_TNIL 0 -#define LUA_TBOOLEAN 1 -#define LUA_TLIGHTUSERDATA 2 -#define LUA_TNUMBER 3 -#define LUA_TSTRING 4 -#define LUA_TTABLE 5 -#define LUA_TFUNCTION 6 -#define LUA_TUSERDATA 7 -#define LUA_TTHREAD 8 - - - -/* minimum Lua stack available to a C function */ -#define LUA_MINSTACK 20 - - -/* -** generic extra include file -*/ -#if defined(LUA_USER_H) -#include LUA_USER_H -#endif - - -/* type of numbers in Lua */ -typedef LUA_NUMBER lua_Number; - - -/* type for integer functions */ -typedef LUA_INTEGER lua_Integer; - - - -/* -** state manipulation -*/ -LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud); -LUA_API void (lua_close) (lua_State *L); -LUA_API lua_State *(lua_newthread) (lua_State *L); - -LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); - - -/* -** basic stack manipulation -*/ -LUA_API int (lua_gettop) (lua_State *L); -LUA_API void (lua_settop) (lua_State *L, int idx); -LUA_API void (lua_pushvalue) (lua_State *L, int idx); -LUA_API void (lua_remove) (lua_State *L, int idx); -LUA_API void (lua_insert) (lua_State *L, int idx); -LUA_API void (lua_replace) (lua_State *L, int idx); -LUA_API int (lua_checkstack) (lua_State *L, int sz); - -LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n); - - -/* -** access functions (stack -> C) -*/ - -LUA_API int (lua_isnumber) (lua_State *L, int idx); -LUA_API int (lua_isstring) (lua_State *L, int idx); -LUA_API int (lua_iscfunction) (lua_State *L, int idx); -LUA_API int (lua_isuserdata) (lua_State *L, int idx); -LUA_API int (lua_type) (lua_State *L, int idx); -LUA_API const char *(lua_typename) (lua_State *L, int tp); - -LUA_API int (lua_equal) (lua_State *L, int idx1, int idx2); -LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); -LUA_API int (lua_lessthan) (lua_State *L, int idx1, int idx2); - -LUA_API lua_Number (lua_tonumber) (lua_State *L, int idx); -LUA_API lua_Integer (lua_tointeger) (lua_State *L, int idx); -LUA_API int (lua_toboolean) (lua_State *L, int idx); -LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len); -LUA_API size_t (lua_objlen) (lua_State *L, int idx); -LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx); -LUA_API void *(lua_touserdata) (lua_State *L, int idx); -LUA_API lua_State *(lua_tothread) (lua_State *L, int idx); -LUA_API const void *(lua_topointer) (lua_State *L, int idx); - - -/* -** push functions (C -> stack) -*/ -LUA_API void (lua_pushnil) (lua_State *L); -LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); -LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); -LUA_API void (lua_pushlstring) (lua_State *L, const char *s, size_t l); -LUA_API void (lua_pushstring) (lua_State *L, const char *s); -LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt, - va_list argp); -LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...); -LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); -LUA_API void (lua_pushboolean) (lua_State *L, int b); -LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p); -LUA_API int (lua_pushthread) (lua_State *L); - - -/* -** get functions (Lua -> stack) -*/ -LUA_API void (lua_gettable) (lua_State *L, int idx); -LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k); -LUA_API void (lua_rawget) (lua_State *L, int idx); -LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n); -LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); -LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz); -LUA_API int (lua_getmetatable) (lua_State *L, int objindex); -LUA_API void (lua_getfenv) (lua_State *L, int idx); - - -/* -** set functions (stack -> Lua) -*/ -LUA_API void (lua_settable) (lua_State *L, int idx); -LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); -LUA_API void (lua_rawset) (lua_State *L, int idx); -LUA_API void (lua_rawseti) (lua_State *L, int idx, int n); -LUA_API int (lua_setmetatable) (lua_State *L, int objindex); -LUA_API int (lua_setfenv) (lua_State *L, int idx); - - -/* -** `load' and `call' functions (load and run Lua code) -*/ -LUA_API void (lua_call) (lua_State *L, int nargs, int nresults); -LUA_API int (lua_pcall) (lua_State *L, int nargs, int nresults, int errfunc); -LUA_API int (lua_cpcall) (lua_State *L, lua_CFunction func, void *ud); -LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, - const char *chunkname); - -LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data); - - -/* -** coroutine functions -*/ -LUA_API int (lua_yield) (lua_State *L, int nresults); -LUA_API int (lua_resume) (lua_State *L, int narg); -LUA_API int (lua_status) (lua_State *L); - -/* -** garbage-collection function and options -*/ - -#define LUA_GCSTOP 0 -#define LUA_GCRESTART 1 -#define LUA_GCCOLLECT 2 -#define LUA_GCCOUNT 3 -#define LUA_GCCOUNTB 4 -#define LUA_GCSTEP 5 -#define LUA_GCSETPAUSE 6 -#define LUA_GCSETSTEPMUL 7 - -LUA_API int (lua_gc) (lua_State *L, int what, int data); - - -/* -** miscellaneous functions -*/ - -LUA_API int (lua_error) (lua_State *L); - -LUA_API int (lua_next) (lua_State *L, int idx); - -LUA_API void (lua_concat) (lua_State *L, int n); - -LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); -LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); - - - -/* -** =============================================================== -** some useful macros -** =============================================================== -*/ - -#define lua_pop(L,n) lua_settop(L, -(n)-1) - -#define lua_newtable(L) lua_createtable(L, 0, 0) - -#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) - -#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) - -#define lua_strlen(L,i) lua_objlen(L, (i)) - -#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) -#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) -#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) -#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) -#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) -#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) -#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) -#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) - -#define lua_pushliteral(L, s) \ - lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1) - -#define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, (s)) -#define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, (s)) - -#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) - - - -/* -** compatibility macros and functions -*/ - -#define lua_open() luaL_newstate() - -#define lua_getregistry(L) lua_pushvalue(L, LUA_REGISTRYINDEX) - -#define lua_getgccount(L) lua_gc(L, LUA_GCCOUNT, 0) - -#define lua_Chunkreader lua_Reader -#define lua_Chunkwriter lua_Writer - - -/* hack */ -LUA_API void lua_setlevel (lua_State *from, lua_State *to); - - -/* -** {====================================================================== -** Debug API -** ======================================================================= -*/ - - -/* -** Event codes -*/ -#define LUA_HOOKCALL 0 -#define LUA_HOOKRET 1 -#define LUA_HOOKLINE 2 -#define LUA_HOOKCOUNT 3 -#define LUA_HOOKTAILRET 4 - - -/* -** Event masks -*/ -#define LUA_MASKCALL (1 << LUA_HOOKCALL) -#define LUA_MASKRET (1 << LUA_HOOKRET) -#define LUA_MASKLINE (1 << LUA_HOOKLINE) -#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) - -typedef struct lua_Debug lua_Debug; /* activation record */ - - -/* Functions to be called by the debuger in specific events */ -typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); - - -LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar); -LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); -LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n); -LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n); - -LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count); -LUA_API lua_Hook lua_gethook (lua_State *L); -LUA_API int lua_gethookmask (lua_State *L); -LUA_API int lua_gethookcount (lua_State *L); - - -struct lua_Debug { - int event; - const char *name; /* (n) */ - const char *namewhat; /* (n) `global', `local', `field', `method' */ - const char *what; /* (S) `Lua', `C', `main', `tail' */ - const char *source; /* (S) */ - int currentline; /* (l) */ - int nups; /* (u) number of upvalues */ - int linedefined; /* (S) */ - int lastlinedefined; /* (S) */ - char short_src[LUA_IDSIZE]; /* (S) */ - /* private part */ - int i_ci; /* active function */ -}; - -/* }====================================================================== */ - - -/****************************************************************************** -* Copyright (C) 1994-2012 Lua.org, PUC-Rio. All rights reserved. -* -* 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. -******************************************************************************/ - - -#endif diff --git a/Utilities/lua-5.1.5/src/luaconf.h b/Utilities/lua-5.1.5/src/luaconf.h deleted file mode 100644 index e2cb26163..000000000 --- a/Utilities/lua-5.1.5/src/luaconf.h +++ /dev/null @@ -1,763 +0,0 @@ -/* -** $Id: luaconf.h,v 1.82.1.7 2008/02/11 16:25:08 roberto Exp $ -** Configuration file for Lua -** See Copyright Notice in lua.h -*/ - - -#ifndef lconfig_h -#define lconfig_h - -#include -#include - - -/* -** ================================================================== -** Search for "@@" to find all configurable definitions. -** =================================================================== -*/ - - -/* -@@ LUA_ANSI controls the use of non-ansi features. -** CHANGE it (define it) if you want Lua to avoid the use of any -** non-ansi feature or library. -*/ -#if defined(__STRICT_ANSI__) -#define LUA_ANSI -#endif - - -#if !defined(LUA_ANSI) && defined(_WIN32) -#define LUA_WIN -#endif - -#if defined(LUA_USE_LINUX) -#define LUA_USE_POSIX -#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ -#define LUA_USE_READLINE /* needs some extra libraries */ -#endif - -#if defined(LUA_USE_MACOSX) -#define LUA_USE_POSIX -#define LUA_DL_DYLD /* does not need extra library */ -#endif - - - -/* -@@ LUA_USE_POSIX includes all functionallity listed as X/Open System -@* Interfaces Extension (XSI). -** CHANGE it (define it) if your system is XSI compatible. -*/ -#if defined(LUA_USE_POSIX) -#define LUA_USE_MKSTEMP -#define LUA_USE_ISATTY -#define LUA_USE_POPEN -#define LUA_USE_ULONGJMP -#endif - - -/* -@@ LUA_PATH and LUA_CPATH are the names of the environment variables that -@* Lua check to set its paths. -@@ LUA_INIT is the name of the environment variable that Lua -@* checks for initialization code. -** CHANGE them if you want different names. -*/ -#define LUA_PATH "LUA_PATH" -#define LUA_CPATH "LUA_CPATH" -#define LUA_INIT "LUA_INIT" - - -/* -@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for -@* Lua libraries. -@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for -@* C libraries. -** CHANGE them if your machine has a non-conventional directory -** hierarchy or if you want to install your libraries in -** non-conventional directories. -*/ -#if defined(_WIN32) -/* -** In Windows, any exclamation mark ('!') in the path is replaced by the -** path of the directory of the executable file of the current process. -*/ -#define LUA_LDIR "!\\lua\\" -#define LUA_CDIR "!\\" -#define LUA_PATH_DEFAULT \ - ".\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ - LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua" -#define LUA_CPATH_DEFAULT \ - ".\\?.dll;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll" - -#else -#define LUA_ROOT "/usr/local/" -#define LUA_LDIR LUA_ROOT "share/lua/5.1/" -#define LUA_CDIR LUA_ROOT "lib/lua/5.1/" -#define LUA_PATH_DEFAULT \ - "./?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ - LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua" -#define LUA_CPATH_DEFAULT \ - "./?.so;" LUA_CDIR"?.so;" LUA_CDIR"loadall.so" -#endif - - -/* -@@ LUA_DIRSEP is the directory separator (for submodules). -** CHANGE it if your machine does not use "/" as the directory separator -** and is not Windows. (On Windows Lua automatically uses "\".) -*/ -#if defined(_WIN32) -#define LUA_DIRSEP "\\" -#else -#define LUA_DIRSEP "/" -#endif - - -/* -@@ LUA_PATHSEP is the character that separates templates in a path. -@@ LUA_PATH_MARK is the string that marks the substitution points in a -@* template. -@@ LUA_EXECDIR in a Windows path is replaced by the executable's -@* directory. -@@ LUA_IGMARK is a mark to ignore all before it when bulding the -@* luaopen_ function name. -** CHANGE them if for some reason your system cannot use those -** characters. (E.g., if one of those characters is a common character -** in file/directory names.) Probably you do not need to change them. -*/ -#define LUA_PATHSEP ";" -#define LUA_PATH_MARK "?" -#define LUA_EXECDIR "!" -#define LUA_IGMARK "-" - - -/* -@@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger. -** CHANGE that if ptrdiff_t is not adequate on your machine. (On most -** machines, ptrdiff_t gives a good choice between int or long.) -*/ -#define LUA_INTEGER ptrdiff_t - - -/* -@@ LUA_API is a mark for all core API functions. -@@ LUALIB_API is a mark for all standard library functions. -** CHANGE them if you need to define those functions in some special way. -** For instance, if you want to create one Windows DLL with the core and -** the libraries, you may want to use the following definition (define -** LUA_BUILD_AS_DLL to get it). -*/ -#if defined(LUA_BUILD_AS_DLL) - -#if defined(LUA_CORE) || defined(LUA_LIB) -#define LUA_API __declspec(dllexport) -#else -#define LUA_API __declspec(dllimport) -#endif - -#else - -#define LUA_API extern - -#endif - -/* more often than not the libs go together with the core */ -#define LUALIB_API LUA_API - - -/* -@@ LUAI_FUNC is a mark for all extern functions that are not to be -@* exported to outside modules. -@@ LUAI_DATA is a mark for all extern (const) variables that are not to -@* be exported to outside modules. -** CHANGE them if you need to mark them in some special way. Elf/gcc -** (versions 3.2 and later) mark them as "hidden" to optimize access -** when Lua is compiled as a shared library. -*/ -#if defined(luaall_c) -#define LUAI_FUNC static -#define LUAI_DATA /* empty */ - -#elif defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ - defined(__ELF__) -#define LUAI_FUNC __attribute__((visibility("hidden"))) extern -#define LUAI_DATA LUAI_FUNC - -#else -#define LUAI_FUNC extern -#define LUAI_DATA extern -#endif - - - -/* -@@ LUA_QL describes how error messages quote program elements. -** CHANGE it if you want a different appearance. -*/ -#define LUA_QL(x) "'" x "'" -#define LUA_QS LUA_QL("%s") - - -/* -@@ LUA_IDSIZE gives the maximum size for the description of the source -@* of a function in debug information. -** CHANGE it if you want a different size. -*/ -#define LUA_IDSIZE 60 - - -/* -** {================================================================== -** Stand-alone configuration -** =================================================================== -*/ - -#if defined(lua_c) || defined(luaall_c) - -/* -@@ lua_stdin_is_tty detects whether the standard input is a 'tty' (that -@* is, whether we're running lua interactively). -** CHANGE it if you have a better definition for non-POSIX/non-Windows -** systems. -*/ -#if defined(LUA_USE_ISATTY) -#include -#define lua_stdin_is_tty() isatty(0) -#elif defined(LUA_WIN) -#include -#include -#define lua_stdin_is_tty() _isatty(_fileno(stdin)) -#else -#define lua_stdin_is_tty() 1 /* assume stdin is a tty */ -#endif - - -/* -@@ LUA_PROMPT is the default prompt used by stand-alone Lua. -@@ LUA_PROMPT2 is the default continuation prompt used by stand-alone Lua. -** CHANGE them if you want different prompts. (You can also change the -** prompts dynamically, assigning to globals _PROMPT/_PROMPT2.) -*/ -#define LUA_PROMPT "> " -#define LUA_PROMPT2 ">> " - - -/* -@@ LUA_PROGNAME is the default name for the stand-alone Lua program. -** CHANGE it if your stand-alone interpreter has a different name and -** your system is not able to detect that name automatically. -*/ -#define LUA_PROGNAME "lua" - - -/* -@@ LUA_MAXINPUT is the maximum length for an input line in the -@* stand-alone interpreter. -** CHANGE it if you need longer lines. -*/ -#define LUA_MAXINPUT 512 - - -/* -@@ lua_readline defines how to show a prompt and then read a line from -@* the standard input. -@@ lua_saveline defines how to "save" a read line in a "history". -@@ lua_freeline defines how to free a line read by lua_readline. -** CHANGE them if you want to improve this functionality (e.g., by using -** GNU readline and history facilities). -*/ -#if defined(LUA_USE_READLINE) -#include -#include -#include -#define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL) -#define lua_saveline(L,idx) \ - if (lua_strlen(L,idx) > 0) /* non-empty line? */ \ - add_history(lua_tostring(L, idx)); /* add it to history */ -#define lua_freeline(L,b) ((void)L, free(b)) -#else -#define lua_readline(L,b,p) \ - ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \ - fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */ -#define lua_saveline(L,idx) { (void)L; (void)idx; } -#define lua_freeline(L,b) { (void)L; (void)b; } -#endif - -#endif - -/* }================================================================== */ - - -/* -@@ LUAI_GCPAUSE defines the default pause between garbage-collector cycles -@* as a percentage. -** CHANGE it if you want the GC to run faster or slower (higher values -** mean larger pauses which mean slower collection.) You can also change -** this value dynamically. -*/ -#define LUAI_GCPAUSE 200 /* 200% (wait memory to double before next GC) */ - - -/* -@@ LUAI_GCMUL defines the default speed of garbage collection relative to -@* memory allocation as a percentage. -** CHANGE it if you want to change the granularity of the garbage -** collection. (Higher values mean coarser collections. 0 represents -** infinity, where each step performs a full collection.) You can also -** change this value dynamically. -*/ -#define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */ - - - -/* -@@ LUA_COMPAT_GETN controls compatibility with old getn behavior. -** CHANGE it (define it) if you want exact compatibility with the -** behavior of setn/getn in Lua 5.0. -*/ -#undef LUA_COMPAT_GETN - -/* -@@ LUA_COMPAT_LOADLIB controls compatibility about global loadlib. -** CHANGE it to undefined as soon as you do not need a global 'loadlib' -** function (the function is still available as 'package.loadlib'). -*/ -#undef LUA_COMPAT_LOADLIB - -/* -@@ LUA_COMPAT_VARARG controls compatibility with old vararg feature. -** CHANGE it to undefined as soon as your programs use only '...' to -** access vararg parameters (instead of the old 'arg' table). -*/ -#define LUA_COMPAT_VARARG - -/* -@@ LUA_COMPAT_MOD controls compatibility with old math.mod function. -** CHANGE it to undefined as soon as your programs use 'math.fmod' or -** the new '%' operator instead of 'math.mod'. -*/ -#define LUA_COMPAT_MOD - -/* -@@ LUA_COMPAT_LSTR controls compatibility with old long string nesting -@* facility. -** CHANGE it to 2 if you want the old behaviour, or undefine it to turn -** off the advisory error when nesting [[...]]. -*/ -#define LUA_COMPAT_LSTR 1 - -/* -@@ LUA_COMPAT_GFIND controls compatibility with old 'string.gfind' name. -** CHANGE it to undefined as soon as you rename 'string.gfind' to -** 'string.gmatch'. -*/ -#define LUA_COMPAT_GFIND - -/* -@@ LUA_COMPAT_OPENLIB controls compatibility with old 'luaL_openlib' -@* behavior. -** CHANGE it to undefined as soon as you replace to 'luaL_register' -** your uses of 'luaL_openlib' -*/ -#define LUA_COMPAT_OPENLIB - - - -/* -@@ luai_apicheck is the assert macro used by the Lua-C API. -** CHANGE luai_apicheck if you want Lua to perform some checks in the -** parameters it gets from API calls. This may slow down the interpreter -** a bit, but may be quite useful when debugging C code that interfaces -** with Lua. A useful redefinition is to use assert.h. -*/ -#if defined(LUA_USE_APICHECK) -#include -#define luai_apicheck(L,o) { (void)L; assert(o); } -#else -#define luai_apicheck(L,o) { (void)L; } -#endif - - -/* -@@ LUAI_BITSINT defines the number of bits in an int. -** CHANGE here if Lua cannot automatically detect the number of bits of -** your machine. Probably you do not need to change this. -*/ -/* avoid overflows in comparison */ -#if INT_MAX-20 < 32760 -#define LUAI_BITSINT 16 -#elif INT_MAX > 2147483640L -/* int has at least 32 bits */ -#define LUAI_BITSINT 32 -#else -#error "you must define LUA_BITSINT with number of bits in an integer" -#endif - - -/* -@@ LUAI_UINT32 is an unsigned integer with at least 32 bits. -@@ LUAI_INT32 is an signed integer with at least 32 bits. -@@ LUAI_UMEM is an unsigned integer big enough to count the total -@* memory used by Lua. -@@ LUAI_MEM is a signed integer big enough to count the total memory -@* used by Lua. -** CHANGE here if for some weird reason the default definitions are not -** good enough for your machine. (The definitions in the 'else' -** part always works, but may waste space on machines with 64-bit -** longs.) Probably you do not need to change this. -*/ -#if LUAI_BITSINT >= 32 -#define LUAI_UINT32 unsigned int -#define LUAI_INT32 int -#define LUAI_MAXINT32 INT_MAX -#define LUAI_UMEM size_t -#define LUAI_MEM ptrdiff_t -#else -/* 16-bit ints */ -#define LUAI_UINT32 unsigned long -#define LUAI_INT32 long -#define LUAI_MAXINT32 LONG_MAX -#define LUAI_UMEM unsigned long -#define LUAI_MEM long -#endif - - -/* -@@ LUAI_MAXCALLS limits the number of nested calls. -** CHANGE it if you need really deep recursive calls. This limit is -** arbitrary; its only purpose is to stop infinite recursion before -** exhausting memory. -*/ -#define LUAI_MAXCALLS 20000 - - -/* -@@ LUAI_MAXCSTACK limits the number of Lua stack slots that a C function -@* can use. -** CHANGE it if you need lots of (Lua) stack space for your C -** functions. This limit is arbitrary; its only purpose is to stop C -** functions to consume unlimited stack space. (must be smaller than -** -LUA_REGISTRYINDEX) -*/ -#define LUAI_MAXCSTACK 8000 - - - -/* -** {================================================================== -** CHANGE (to smaller values) the following definitions if your system -** has a small C stack. (Or you may want to change them to larger -** values if your system has a large C stack and these limits are -** too rigid for you.) Some of these constants control the size of -** stack-allocated arrays used by the compiler or the interpreter, while -** others limit the maximum number of recursive calls that the compiler -** or the interpreter can perform. Values too large may cause a C stack -** overflow for some forms of deep constructs. -** =================================================================== -*/ - - -/* -@@ LUAI_MAXCCALLS is the maximum depth for nested C calls (short) and -@* syntactical nested non-terminals in a program. -*/ -#define LUAI_MAXCCALLS 200 - - -/* -@@ LUAI_MAXVARS is the maximum number of local variables per function -@* (must be smaller than 250). -*/ -#define LUAI_MAXVARS 200 - - -/* -@@ LUAI_MAXUPVALUES is the maximum number of upvalues per function -@* (must be smaller than 250). -*/ -#define LUAI_MAXUPVALUES 60 - - -/* -@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. -*/ -#define LUAL_BUFFERSIZE BUFSIZ - -/* }================================================================== */ - - - - -/* -** {================================================================== -@@ LUA_NUMBER is the type of numbers in Lua. -** CHANGE the following definitions only if you want to build Lua -** with a number type different from double. You may also need to -** change lua_number2int & lua_number2integer. -** =================================================================== -*/ - -#define LUA_NUMBER_DOUBLE -#define LUA_NUMBER double - -/* -@@ LUAI_UACNUMBER is the result of an 'usual argument conversion' -@* over a number. -*/ -#define LUAI_UACNUMBER double - - -/* -@@ LUA_NUMBER_SCAN is the format for reading numbers. -@@ LUA_NUMBER_FMT is the format for writing numbers. -@@ lua_number2str converts a number to a string. -@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion. -@@ lua_str2number converts a string to a number. -*/ -#define LUA_NUMBER_SCAN "%lf" -#define LUA_NUMBER_FMT "%.14g" -#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) -#define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */ -#define lua_str2number(s,p) strtod((s), (p)) - - -/* -@@ The luai_num* macros define the primitive operations over numbers. -*/ -#if defined(LUA_CORE) -#include -#define luai_numadd(a,b) ((a)+(b)) -#define luai_numsub(a,b) ((a)-(b)) -#define luai_nummul(a,b) ((a)*(b)) -#define luai_numdiv(a,b) ((a)/(b)) -#define luai_nummod(a,b) ((a) - floor((a)/(b))*(b)) -#define luai_numpow(a,b) (pow(a,b)) -#define luai_numunm(a) (-(a)) -#define luai_numeq(a,b) ((a)==(b)) -#define luai_numlt(a,b) ((a)<(b)) -#define luai_numle(a,b) ((a)<=(b)) -#define luai_numisnan(a) (!luai_numeq((a), (a))) -#endif - - -/* -@@ lua_number2int is a macro to convert lua_Number to int. -@@ lua_number2integer is a macro to convert lua_Number to lua_Integer. -** CHANGE them if you know a faster way to convert a lua_Number to -** int (with any rounding method and without throwing errors) in your -** system. In Pentium machines, a naive typecast from double to int -** in C is extremely slow, so any alternative is worth trying. -*/ - -/* On a Pentium, resort to a trick */ -#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) && !defined(__SSE2__) && \ - (defined(__i386) || defined (_M_IX86) || defined(__i386__)) - -/* On a Microsoft compiler, use assembler */ -#if defined(_MSC_VER) - -#define lua_number2int(i,d) __asm fld d __asm fistp i -#define lua_number2integer(i,n) lua_number2int(i, n) - -/* the next trick should work on any Pentium, but sometimes clashes - with a DirectX idiosyncrasy */ -#else - -union luai_Cast { double l_d; long l_l; }; -#define lua_number2int(i,d) \ - { volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; } -#define lua_number2integer(i,n) lua_number2int(i, n) - -#endif - - -/* this option always works, but may be slow */ -#else -#define lua_number2int(i,d) ((i)=(int)(d)) -#define lua_number2integer(i,d) ((i)=(lua_Integer)(d)) - -#endif - -/* }================================================================== */ - - -/* -@@ LUAI_USER_ALIGNMENT_T is a type that requires maximum alignment. -** CHANGE it if your system requires alignments larger than double. (For -** instance, if your system supports long doubles and they must be -** aligned in 16-byte boundaries, then you should add long double in the -** union.) Probably you do not need to change this. -*/ -#define LUAI_USER_ALIGNMENT_T union { double u; void *s; long l; } - - -/* -@@ LUAI_THROW/LUAI_TRY define how Lua does exception handling. -** CHANGE them if you prefer to use longjmp/setjmp even with C++ -** or if want/don't to use _longjmp/_setjmp instead of regular -** longjmp/setjmp. By default, Lua handles errors with exceptions when -** compiling as C++ code, with _longjmp/_setjmp when asked to use them, -** and with longjmp/setjmp otherwise. -*/ -#if defined(__cplusplus) -/* C++ exceptions */ -#define LUAI_THROW(L,c) throw(c) -#define LUAI_TRY(L,c,a) try { a } catch(...) \ - { if ((c)->status == 0) (c)->status = -1; } -#define luai_jmpbuf int /* dummy variable */ - -#elif defined(LUA_USE_ULONGJMP) -/* in Unix, try _longjmp/_setjmp (more efficient) */ -#define LUAI_THROW(L,c) _longjmp((c)->b, 1) -#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a } -#define luai_jmpbuf jmp_buf - -#else -/* default handling with long jumps */ -#define LUAI_THROW(L,c) longjmp((c)->b, 1) -#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a } -#define luai_jmpbuf jmp_buf - -#endif - - -/* -@@ LUA_MAXCAPTURES is the maximum number of captures that a pattern -@* can do during pattern-matching. -** CHANGE it if you need more captures. This limit is arbitrary. -*/ -#define LUA_MAXCAPTURES 32 - - -/* -@@ lua_tmpnam is the function that the OS library uses to create a -@* temporary name. -@@ LUA_TMPNAMBUFSIZE is the maximum size of a name created by lua_tmpnam. -** CHANGE them if you have an alternative to tmpnam (which is considered -** insecure) or if you want the original tmpnam anyway. By default, Lua -** uses tmpnam except when POSIX is available, where it uses mkstemp. -*/ -#if defined(loslib_c) || defined(luaall_c) - -#if defined(LUA_USE_MKSTEMP) -#include -#define LUA_TMPNAMBUFSIZE 32 -#define lua_tmpnam(b,e) { \ - strcpy(b, "/tmp/lua_XXXXXX"); \ - e = mkstemp(b); \ - if (e != -1) close(e); \ - e = (e == -1); } - -#else -#define LUA_TMPNAMBUFSIZE L_tmpnam -#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); } -#endif - -#endif - - -/* -@@ lua_popen spawns a new process connected to the current one through -@* the file streams. -** CHANGE it if you have a way to implement it in your system. -*/ -#if defined(LUA_USE_POPEN) - -#define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m)) -#define lua_pclose(L,file) ((void)L, (pclose(file) != -1)) - -#elif defined(LUA_WIN) - -#define lua_popen(L,c,m) ((void)L, _popen(c,m)) -#define lua_pclose(L,file) ((void)L, (_pclose(file) != -1)) - -#else - -#define lua_popen(L,c,m) ((void)((void)c, m), \ - luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0) -#define lua_pclose(L,file) ((void)((void)L, file), 0) - -#endif - -/* -@@ LUA_DL_* define which dynamic-library system Lua should use. -** CHANGE here if Lua has problems choosing the appropriate -** dynamic-library system for your platform (either Windows' DLL, Mac's -** dyld, or Unix's dlopen). If your system is some kind of Unix, there -** is a good chance that it has dlopen, so LUA_DL_DLOPEN will work for -** it. To use dlopen you also need to adapt the src/Makefile (probably -** adding -ldl to the linker options), so Lua does not select it -** automatically. (When you change the makefile to add -ldl, you must -** also add -DLUA_USE_DLOPEN.) -** If you do not want any kind of dynamic library, undefine all these -** options. -** By default, _WIN32 gets LUA_DL_DLL and MAC OS X gets LUA_DL_DYLD. -*/ -#if defined(LUA_USE_DLOPEN) -#define LUA_DL_DLOPEN -#endif - -#if defined(LUA_WIN) -#define LUA_DL_DLL -#endif - - -/* -@@ LUAI_EXTRASPACE allows you to add user-specific data in a lua_State -@* (the data goes just *before* the lua_State pointer). -** CHANGE (define) this if you really need that. This value must be -** a multiple of the maximum alignment required for your machine. -*/ -#define LUAI_EXTRASPACE 0 - - -/* -@@ luai_userstate* allow user-specific actions on threads. -** CHANGE them if you defined LUAI_EXTRASPACE and need to do something -** extra when a thread is created/deleted/resumed/yielded. -*/ -#define luai_userstateopen(L) ((void)L) -#define luai_userstateclose(L) ((void)L) -#define luai_userstatethread(L,L1) ((void)L) -#define luai_userstatefree(L) ((void)L) -#define luai_userstateresume(L,n) ((void)L) -#define luai_userstateyield(L,n) ((void)L) - - -/* -@@ LUA_INTFRMLEN is the length modifier for integer conversions -@* in 'string.format'. -@@ LUA_INTFRM_T is the integer type correspoding to the previous length -@* modifier. -** CHANGE them if your system supports long long or does not support long. -*/ - -#if defined(LUA_USELONGLONG) - -#define LUA_INTFRMLEN "ll" -#define LUA_INTFRM_T long long - -#else - -#define LUA_INTFRMLEN "l" -#define LUA_INTFRM_T long - -#endif - - - -/* =================================================================== */ - -/* -** Local configuration. You can use this space to add your redefinitions -** without modifying the main part of the file. -*/ - - - -#endif - diff --git a/Utilities/lua-5.1.5/src/lualib.h b/Utilities/lua-5.1.5/src/lualib.h deleted file mode 100644 index 469417f67..000000000 --- a/Utilities/lua-5.1.5/src/lualib.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -** $Id: lualib.h,v 1.36.1.1 2007/12/27 13:02:25 roberto Exp $ -** Lua standard libraries -** See Copyright Notice in lua.h -*/ - - -#ifndef lualib_h -#define lualib_h - -#include "lua.h" - - -/* Key to file-handle type */ -#define LUA_FILEHANDLE "FILE*" - - -#define LUA_COLIBNAME "coroutine" -LUALIB_API int (luaopen_base) (lua_State *L); - -#define LUA_TABLIBNAME "table" -LUALIB_API int (luaopen_table) (lua_State *L); - -#define LUA_IOLIBNAME "io" -LUALIB_API int (luaopen_io) (lua_State *L); - -#define LUA_OSLIBNAME "os" -LUALIB_API int (luaopen_os) (lua_State *L); - -#define LUA_STRLIBNAME "string" -LUALIB_API int (luaopen_string) (lua_State *L); - -#define LUA_MATHLIBNAME "math" -LUALIB_API int (luaopen_math) (lua_State *L); - -#define LUA_DBLIBNAME "debug" -LUALIB_API int (luaopen_debug) (lua_State *L); - -#define LUA_LOADLIBNAME "package" -LUALIB_API int (luaopen_package) (lua_State *L); - - -/* open all previous libraries */ -LUALIB_API void (luaL_openlibs) (lua_State *L); - - - -#ifndef lua_assert -#define lua_assert(x) ((void)0) -#endif - - -#endif diff --git a/Utilities/lua-5.1.5/src/lundump.c b/Utilities/lua-5.1.5/src/lundump.c deleted file mode 100644 index 8010a4579..000000000 --- a/Utilities/lua-5.1.5/src/lundump.c +++ /dev/null @@ -1,227 +0,0 @@ -/* -** $Id: lundump.c,v 2.7.1.4 2008/04/04 19:51:41 roberto Exp $ -** load precompiled Lua chunks -** See Copyright Notice in lua.h -*/ - -#include - -#define lundump_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lmem.h" -#include "lobject.h" -#include "lstring.h" -#include "lundump.h" -#include "lzio.h" - -typedef struct { - lua_State* L; - ZIO* Z; - Mbuffer* b; - const char* name; -} LoadState; - -#ifdef LUAC_TRUST_BINARIES -#define IF(c,s) -#define error(S,s) -#else -#define IF(c,s) if (c) error(S,s) - -static void error(LoadState* S, const char* why) -{ - luaO_pushfstring(S->L,"%s: %s in precompiled chunk",S->name,why); - luaD_throw(S->L,LUA_ERRSYNTAX); -} -#endif - -#define LoadMem(S,b,n,size) LoadBlock(S,b,(n)*(size)) -#define LoadByte(S) (lu_byte)LoadChar(S) -#define LoadVar(S,x) LoadMem(S,&x,1,sizeof(x)) -#define LoadVector(S,b,n,size) LoadMem(S,b,n,size) - -static void LoadBlock(LoadState* S, void* b, size_t size) -{ - size_t r=luaZ_read(S->Z,b,size); - IF (r!=0, "unexpected end"); -} - -static int LoadChar(LoadState* S) -{ - char x; - LoadVar(S,x); - return x; -} - -static int LoadInt(LoadState* S) -{ - int x; - LoadVar(S,x); - IF (x<0, "bad integer"); - return x; -} - -static lua_Number LoadNumber(LoadState* S) -{ - lua_Number x; - LoadVar(S,x); - return x; -} - -static TString* LoadString(LoadState* S) -{ - size_t size; - LoadVar(S,size); - if (size==0) - return NULL; - else - { - char* s=luaZ_openspace(S->L,S->b,size); - LoadBlock(S,s,size); - return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */ - } -} - -static void LoadCode(LoadState* S, Proto* f) -{ - int n=LoadInt(S); - f->code=luaM_newvector(S->L,n,Instruction); - f->sizecode=n; - LoadVector(S,f->code,n,sizeof(Instruction)); -} - -static Proto* LoadFunction(LoadState* S, TString* p); - -static void LoadConstants(LoadState* S, Proto* f) -{ - int i,n; - n=LoadInt(S); - f->k=luaM_newvector(S->L,n,TValue); - f->sizek=n; - for (i=0; ik[i]); - for (i=0; ik[i]; - int t=LoadChar(S); - switch (t) - { - case LUA_TNIL: - setnilvalue(o); - break; - case LUA_TBOOLEAN: - setbvalue(o,LoadChar(S)!=0); - break; - case LUA_TNUMBER: - setnvalue(o,LoadNumber(S)); - break; - case LUA_TSTRING: - setsvalue2n(S->L,o,LoadString(S)); - break; - default: - error(S,"bad constant"); - break; - } - } - n=LoadInt(S); - f->p=luaM_newvector(S->L,n,Proto*); - f->sizep=n; - for (i=0; ip[i]=NULL; - for (i=0; ip[i]=LoadFunction(S,f->source); -} - -static void LoadDebug(LoadState* S, Proto* f) -{ - int i,n; - n=LoadInt(S); - f->lineinfo=luaM_newvector(S->L,n,int); - f->sizelineinfo=n; - LoadVector(S,f->lineinfo,n,sizeof(int)); - n=LoadInt(S); - f->locvars=luaM_newvector(S->L,n,LocVar); - f->sizelocvars=n; - for (i=0; ilocvars[i].varname=NULL; - for (i=0; ilocvars[i].varname=LoadString(S); - f->locvars[i].startpc=LoadInt(S); - f->locvars[i].endpc=LoadInt(S); - } - n=LoadInt(S); - f->upvalues=luaM_newvector(S->L,n,TString*); - f->sizeupvalues=n; - for (i=0; iupvalues[i]=NULL; - for (i=0; iupvalues[i]=LoadString(S); -} - -static Proto* LoadFunction(LoadState* S, TString* p) -{ - Proto* f; - if (++S->L->nCcalls > LUAI_MAXCCALLS) error(S,"code too deep"); - f=luaF_newproto(S->L); - setptvalue2s(S->L,S->L->top,f); incr_top(S->L); - f->source=LoadString(S); if (f->source==NULL) f->source=p; - f->linedefined=LoadInt(S); - f->lastlinedefined=LoadInt(S); - f->nups=LoadByte(S); - f->numparams=LoadByte(S); - f->is_vararg=LoadByte(S); - f->maxstacksize=LoadByte(S); - LoadCode(S,f); - LoadConstants(S,f); - LoadDebug(S,f); - IF (!luaG_checkcode(f), "bad code"); - S->L->top--; - S->L->nCcalls--; - return f; -} - -static void LoadHeader(LoadState* S) -{ - char h[LUAC_HEADERSIZE]; - char s[LUAC_HEADERSIZE]; - luaU_header(h); - LoadBlock(S,s,LUAC_HEADERSIZE); - IF (memcmp(h,s,LUAC_HEADERSIZE)!=0, "bad header"); -} - -/* -** load precompiled chunk -*/ -Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name) -{ - LoadState S; - if (*name=='@' || *name=='=') - S.name=name+1; - else if (*name==LUA_SIGNATURE[0]) - S.name="binary string"; - else - S.name=name; - S.L=L; - S.Z=Z; - S.b=buff; - LoadHeader(&S); - return LoadFunction(&S,luaS_newliteral(L,"=?")); -} - -/* -* make header -*/ -void luaU_header (char* h) -{ - int x=1; - memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-1); - h+=sizeof(LUA_SIGNATURE)-1; - *h++=(char)LUAC_VERSION; - *h++=(char)LUAC_FORMAT; - *h++=(char)*(char*)&x; /* endianness */ - *h++=(char)sizeof(int); - *h++=(char)sizeof(size_t); - *h++=(char)sizeof(Instruction); - *h++=(char)sizeof(lua_Number); - *h++=(char)(((lua_Number)0.5)==0); /* is lua_Number integral? */ -} diff --git a/Utilities/lua-5.1.5/src/lundump.h b/Utilities/lua-5.1.5/src/lundump.h deleted file mode 100644 index c80189dbf..000000000 --- a/Utilities/lua-5.1.5/src/lundump.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -** $Id: lundump.h,v 1.37.1.1 2007/12/27 13:02:25 roberto Exp $ -** load precompiled Lua chunks -** See Copyright Notice in lua.h -*/ - -#ifndef lundump_h -#define lundump_h - -#include "lobject.h" -#include "lzio.h" - -/* load one chunk; from lundump.c */ -LUAI_FUNC Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name); - -/* make header; from lundump.c */ -LUAI_FUNC void luaU_header (char* h); - -/* dump one chunk; from ldump.c */ -LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip); - -#ifdef luac_c -/* print one chunk; from print.c */ -LUAI_FUNC void luaU_print (const Proto* f, int full); -#endif - -/* for header of binary files -- this is Lua 5.1 */ -#define LUAC_VERSION 0x51 - -/* for header of binary files -- this is the official format */ -#define LUAC_FORMAT 0 - -/* size of header of binary files */ -#define LUAC_HEADERSIZE 12 - -#endif diff --git a/Utilities/lua-5.1.5/src/lvm.c b/Utilities/lua-5.1.5/src/lvm.c deleted file mode 100644 index e0a0cd852..000000000 --- a/Utilities/lua-5.1.5/src/lvm.c +++ /dev/null @@ -1,767 +0,0 @@ -/* -** $Id: lvm.c,v 2.63.1.5 2011/08/17 20:43:11 roberto Exp $ -** Lua virtual machine -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include - -#define lvm_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lgc.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" -#include "lvm.h" - - - -/* limit for table tag-method chains (to avoid loops) */ -#define MAXTAGLOOP 100 - - -const TValue *luaV_tonumber (const TValue *obj, TValue *n) { - lua_Number num; - if (ttisnumber(obj)) return obj; - if (ttisstring(obj) && luaO_str2d(svalue(obj), &num)) { - setnvalue(n, num); - return n; - } - else - return NULL; -} - - -int luaV_tostring (lua_State *L, StkId obj) { - if (!ttisnumber(obj)) - return 0; - else { - char s[LUAI_MAXNUMBER2STR]; - lua_Number n = nvalue(obj); - lua_number2str(s, n); - setsvalue2s(L, obj, luaS_new(L, s)); - return 1; - } -} - - -static void traceexec (lua_State *L, const Instruction *pc) { - lu_byte mask = L->hookmask; - const Instruction *oldpc = L->savedpc; - L->savedpc = pc; - if ((mask & LUA_MASKCOUNT) && L->hookcount == 0) { - resethookcount(L); - luaD_callhook(L, LUA_HOOKCOUNT, -1); - } - if (mask & LUA_MASKLINE) { - Proto *p = ci_func(L->ci)->l.p; - int npc = pcRel(pc, p); - int newline = getline(p, npc); - /* call linehook when enter a new function, when jump back (loop), - or when enter a new line */ - if (npc == 0 || pc <= oldpc || newline != getline(p, pcRel(oldpc, p))) - luaD_callhook(L, LUA_HOOKLINE, newline); - } -} - - -static void callTMres (lua_State *L, StkId res, const TValue *f, - const TValue *p1, const TValue *p2) { - ptrdiff_t result = savestack(L, res); - setobj2s(L, L->top, f); /* push function */ - setobj2s(L, L->top+1, p1); /* 1st argument */ - setobj2s(L, L->top+2, p2); /* 2nd argument */ - luaD_checkstack(L, 3); - L->top += 3; - luaD_call(L, L->top - 3, 1); - res = restorestack(L, result); - L->top--; - setobjs2s(L, res, L->top); -} - - - -static void callTM (lua_State *L, const TValue *f, const TValue *p1, - const TValue *p2, const TValue *p3) { - setobj2s(L, L->top, f); /* push function */ - setobj2s(L, L->top+1, p1); /* 1st argument */ - setobj2s(L, L->top+2, p2); /* 2nd argument */ - setobj2s(L, L->top+3, p3); /* 3th argument */ - luaD_checkstack(L, 4); - L->top += 4; - luaD_call(L, L->top - 4, 0); -} - - -void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) { - int loop; - for (loop = 0; loop < MAXTAGLOOP; loop++) { - const TValue *tm; - if (ttistable(t)) { /* `t' is a table? */ - Table *h = hvalue(t); - const TValue *res = luaH_get(h, key); /* do a primitive get */ - if (!ttisnil(res) || /* result is no nil? */ - (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */ - setobj2s(L, val, res); - return; - } - /* else will try the tag method */ - } - else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX))) - luaG_typeerror(L, t, "index"); - if (ttisfunction(tm)) { - callTMres(L, val, tm, t, key); - return; - } - t = tm; /* else repeat with `tm' */ - } - luaG_runerror(L, "loop in gettable"); -} - - -void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) { - int loop; - TValue temp; - for (loop = 0; loop < MAXTAGLOOP; loop++) { - const TValue *tm; - if (ttistable(t)) { /* `t' is a table? */ - Table *h = hvalue(t); - TValue *oldval = luaH_set(L, h, key); /* do a primitive set */ - if (!ttisnil(oldval) || /* result is no nil? */ - (tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL) { /* or no TM? */ - setobj2t(L, oldval, val); - h->flags = 0; - luaC_barriert(L, h, val); - return; - } - /* else will try the tag method */ - } - else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX))) - luaG_typeerror(L, t, "index"); - if (ttisfunction(tm)) { - callTM(L, tm, t, key, val); - return; - } - /* else repeat with `tm' */ - setobj(L, &temp, tm); /* avoid pointing inside table (may rehash) */ - t = &temp; - } - luaG_runerror(L, "loop in settable"); -} - - -static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2, - StkId res, TMS event) { - const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */ - if (ttisnil(tm)) - tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ - if (ttisnil(tm)) return 0; - callTMres(L, res, tm, p1, p2); - return 1; -} - - -static const TValue *get_compTM (lua_State *L, Table *mt1, Table *mt2, - TMS event) { - const TValue *tm1 = fasttm(L, mt1, event); - const TValue *tm2; - if (tm1 == NULL) return NULL; /* no metamethod */ - if (mt1 == mt2) return tm1; /* same metatables => same metamethods */ - tm2 = fasttm(L, mt2, event); - if (tm2 == NULL) return NULL; /* no metamethod */ - if (luaO_rawequalObj(tm1, tm2)) /* same metamethods? */ - return tm1; - return NULL; -} - - -static int call_orderTM (lua_State *L, const TValue *p1, const TValue *p2, - TMS event) { - const TValue *tm1 = luaT_gettmbyobj(L, p1, event); - const TValue *tm2; - if (ttisnil(tm1)) return -1; /* no metamethod? */ - tm2 = luaT_gettmbyobj(L, p2, event); - if (!luaO_rawequalObj(tm1, tm2)) /* different metamethods? */ - return -1; - callTMres(L, L->top, tm1, p1, p2); - return !l_isfalse(L->top); -} - - -static int l_strcmp (const TString *ls, const TString *rs) { - const char *l = getstr(ls); - size_t ll = ls->tsv.len; - const char *r = getstr(rs); - size_t lr = rs->tsv.len; - for (;;) { - int temp = strcoll(l, r); - if (temp != 0) return temp; - else { /* strings are equal up to a `\0' */ - size_t len = strlen(l); /* index of first `\0' in both strings */ - if (len == lr) /* r is finished? */ - return (len == ll) ? 0 : 1; - else if (len == ll) /* l is finished? */ - return -1; /* l is smaller than r (because r is not finished) */ - /* both strings longer than `len'; go on comparing (after the `\0') */ - len++; - l += len; ll -= len; r += len; lr -= len; - } - } -} - - -int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) { - int res; - if (ttype(l) != ttype(r)) - return luaG_ordererror(L, l, r); - else if (ttisnumber(l)) - return luai_numlt(nvalue(l), nvalue(r)); - else if (ttisstring(l)) - return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0; - else if ((res = call_orderTM(L, l, r, TM_LT)) != -1) - return res; - return luaG_ordererror(L, l, r); -} - - -static int lessequal (lua_State *L, const TValue *l, const TValue *r) { - int res; - if (ttype(l) != ttype(r)) - return luaG_ordererror(L, l, r); - else if (ttisnumber(l)) - return luai_numle(nvalue(l), nvalue(r)); - else if (ttisstring(l)) - return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0; - else if ((res = call_orderTM(L, l, r, TM_LE)) != -1) /* first try `le' */ - return res; - else if ((res = call_orderTM(L, r, l, TM_LT)) != -1) /* else try `lt' */ - return !res; - return luaG_ordererror(L, l, r); -} - - -int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) { - const TValue *tm; - lua_assert(ttype(t1) == ttype(t2)); - switch (ttype(t1)) { - case LUA_TNIL: return 1; - case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)); - case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */ - case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2); - case LUA_TUSERDATA: { - if (uvalue(t1) == uvalue(t2)) return 1; - tm = get_compTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, - TM_EQ); - break; /* will try TM */ - } - case LUA_TTABLE: { - if (hvalue(t1) == hvalue(t2)) return 1; - tm = get_compTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ); - break; /* will try TM */ - } - default: return gcvalue(t1) == gcvalue(t2); - } - if (tm == NULL) return 0; /* no TM? */ - callTMres(L, L->top, tm, t1, t2); /* call TM */ - return !l_isfalse(L->top); -} - - -void luaV_concat (lua_State *L, int total, int last) { - do { - StkId top = L->base + last + 1; - int n = 2; /* number of elements handled in this pass (at least 2) */ - if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) { - if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT)) - luaG_concaterror(L, top-2, top-1); - } else if (tsvalue(top-1)->len == 0) /* second op is empty? */ - (void)tostring(L, top - 2); /* result is first op (as string) */ - else { - /* at least two string values; get as many as possible */ - size_t tl = tsvalue(top-1)->len; - char *buffer; - int i; - /* collect total length */ - for (n = 1; n < total && tostring(L, top-n-1); n++) { - size_t l = tsvalue(top-n-1)->len; - if (l >= MAX_SIZET - tl) luaG_runerror(L, "string length overflow"); - tl += l; - } - buffer = luaZ_openspace(L, &G(L)->buff, tl); - tl = 0; - for (i=n; i>0; i--) { /* concat all strings */ - size_t l = tsvalue(top-i)->len; - memcpy(buffer+tl, svalue(top-i), l); - tl += l; - } - setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl)); - } - total -= n-1; /* got `n' strings to create 1 new */ - last -= n-1; - } while (total > 1); /* repeat until only 1 result left */ -} - - -static void Arith (lua_State *L, StkId ra, const TValue *rb, - const TValue *rc, TMS op) { - TValue tempb, tempc; - const TValue *b, *c; - if ((b = luaV_tonumber(rb, &tempb)) != NULL && - (c = luaV_tonumber(rc, &tempc)) != NULL) { - lua_Number nb = nvalue(b), nc = nvalue(c); - switch (op) { - case TM_ADD: setnvalue(ra, luai_numadd(nb, nc)); break; - case TM_SUB: setnvalue(ra, luai_numsub(nb, nc)); break; - case TM_MUL: setnvalue(ra, luai_nummul(nb, nc)); break; - case TM_DIV: setnvalue(ra, luai_numdiv(nb, nc)); break; - case TM_MOD: setnvalue(ra, luai_nummod(nb, nc)); break; - case TM_POW: setnvalue(ra, luai_numpow(nb, nc)); break; - case TM_UNM: setnvalue(ra, luai_numunm(nb)); break; - default: lua_assert(0); break; - } - } - else if (!call_binTM(L, rb, rc, ra, op)) - luaG_aritherror(L, rb, rc); -} - - - -/* -** some macros for common tasks in `luaV_execute' -*/ - -#define runtime_check(L, c) { if (!(c)) break; } - -#define RA(i) (base+GETARG_A(i)) -/* to be used after possible stack reallocation */ -#define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i)) -#define RC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i)) -#define RKB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \ - ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i)) -#define RKC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \ - ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i)) -#define KBx(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, k+GETARG_Bx(i)) - - -#define dojump(L,pc,i) {(pc) += (i); luai_threadyield(L);} - - -#define Protect(x) { L->savedpc = pc; {x;}; base = L->base; } - - -#define arith_op(op,tm) { \ - TValue *rb = RKB(i); \ - TValue *rc = RKC(i); \ - if (ttisnumber(rb) && ttisnumber(rc)) { \ - lua_Number nb = nvalue(rb), nc = nvalue(rc); \ - setnvalue(ra, op(nb, nc)); \ - } \ - else \ - Protect(Arith(L, ra, rb, rc, tm)); \ - } - - - -void luaV_execute (lua_State *L, int nexeccalls) { - LClosure *cl; - StkId base; - TValue *k; - const Instruction *pc; - reentry: /* entry point */ - lua_assert(isLua(L->ci)); - pc = L->savedpc; - cl = &clvalue(L->ci->func)->l; - base = L->base; - k = cl->p->k; - /* main loop of interpreter */ - for (;;) { - const Instruction i = *pc++; - StkId ra; - if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) && - (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) { - traceexec(L, pc); - if (L->status == LUA_YIELD) { /* did hook yield? */ - L->savedpc = pc - 1; - return; - } - base = L->base; - } - /* warning!! several calls may realloc the stack and invalidate `ra' */ - ra = RA(i); - lua_assert(base == L->base && L->base == L->ci->base); - lua_assert(base <= L->top && L->top <= L->stack + L->stacksize); - lua_assert(L->top == L->ci->top || luaG_checkopenop(i)); - switch (GET_OPCODE(i)) { - case OP_MOVE: { - setobjs2s(L, ra, RB(i)); - continue; - } - case OP_LOADK: { - setobj2s(L, ra, KBx(i)); - continue; - } - case OP_LOADBOOL: { - setbvalue(ra, GETARG_B(i)); - if (GETARG_C(i)) pc++; /* skip next instruction (if C) */ - continue; - } - case OP_LOADNIL: { - TValue *rb = RB(i); - do { - setnilvalue(rb--); - } while (rb >= ra); - continue; - } - case OP_GETUPVAL: { - int b = GETARG_B(i); - setobj2s(L, ra, cl->upvals[b]->v); - continue; - } - case OP_GETGLOBAL: { - TValue g; - TValue *rb = KBx(i); - sethvalue(L, &g, cl->env); - lua_assert(ttisstring(rb)); - Protect(luaV_gettable(L, &g, rb, ra)); - continue; - } - case OP_GETTABLE: { - Protect(luaV_gettable(L, RB(i), RKC(i), ra)); - continue; - } - case OP_SETGLOBAL: { - TValue g; - sethvalue(L, &g, cl->env); - lua_assert(ttisstring(KBx(i))); - Protect(luaV_settable(L, &g, KBx(i), ra)); - continue; - } - case OP_SETUPVAL: { - UpVal *uv = cl->upvals[GETARG_B(i)]; - setobj(L, uv->v, ra); - luaC_barrier(L, uv, ra); - continue; - } - case OP_SETTABLE: { - Protect(luaV_settable(L, ra, RKB(i), RKC(i))); - continue; - } - case OP_NEWTABLE: { - int b = GETARG_B(i); - int c = GETARG_C(i); - sethvalue(L, ra, luaH_new(L, luaO_fb2int(b), luaO_fb2int(c))); - Protect(luaC_checkGC(L)); - continue; - } - case OP_SELF: { - StkId rb = RB(i); - setobjs2s(L, ra+1, rb); - Protect(luaV_gettable(L, rb, RKC(i), ra)); - continue; - } - case OP_ADD: { - arith_op(luai_numadd, TM_ADD); - continue; - } - case OP_SUB: { - arith_op(luai_numsub, TM_SUB); - continue; - } - case OP_MUL: { - arith_op(luai_nummul, TM_MUL); - continue; - } - case OP_DIV: { - arith_op(luai_numdiv, TM_DIV); - continue; - } - case OP_MOD: { - arith_op(luai_nummod, TM_MOD); - continue; - } - case OP_POW: { - arith_op(luai_numpow, TM_POW); - continue; - } - case OP_UNM: { - TValue *rb = RB(i); - if (ttisnumber(rb)) { - lua_Number nb = nvalue(rb); - setnvalue(ra, luai_numunm(nb)); - } - else { - Protect(Arith(L, ra, rb, rb, TM_UNM)); - } - continue; - } - case OP_NOT: { - int res = l_isfalse(RB(i)); /* next assignment may change this value */ - setbvalue(ra, res); - continue; - } - case OP_LEN: { - const TValue *rb = RB(i); - switch (ttype(rb)) { - case LUA_TTABLE: { - setnvalue(ra, cast_num(luaH_getn(hvalue(rb)))); - break; - } - case LUA_TSTRING: { - setnvalue(ra, cast_num(tsvalue(rb)->len)); - break; - } - default: { /* try metamethod */ - Protect( - if (!call_binTM(L, rb, luaO_nilobject, ra, TM_LEN)) - luaG_typeerror(L, rb, "get length of"); - ) - } - } - continue; - } - case OP_CONCAT: { - int b = GETARG_B(i); - int c = GETARG_C(i); - Protect(luaV_concat(L, c-b+1, c); luaC_checkGC(L)); - setobjs2s(L, RA(i), base+b); - continue; - } - case OP_JMP: { - dojump(L, pc, GETARG_sBx(i)); - continue; - } - case OP_EQ: { - TValue *rb = RKB(i); - TValue *rc = RKC(i); - Protect( - if (equalobj(L, rb, rc) == GETARG_A(i)) - dojump(L, pc, GETARG_sBx(*pc)); - ) - pc++; - continue; - } - case OP_LT: { - Protect( - if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i)) - dojump(L, pc, GETARG_sBx(*pc)); - ) - pc++; - continue; - } - case OP_LE: { - Protect( - if (lessequal(L, RKB(i), RKC(i)) == GETARG_A(i)) - dojump(L, pc, GETARG_sBx(*pc)); - ) - pc++; - continue; - } - case OP_TEST: { - if (l_isfalse(ra) != GETARG_C(i)) - dojump(L, pc, GETARG_sBx(*pc)); - pc++; - continue; - } - case OP_TESTSET: { - TValue *rb = RB(i); - if (l_isfalse(rb) != GETARG_C(i)) { - setobjs2s(L, ra, rb); - dojump(L, pc, GETARG_sBx(*pc)); - } - pc++; - continue; - } - case OP_CALL: { - int b = GETARG_B(i); - int nresults = GETARG_C(i) - 1; - if (b != 0) L->top = ra+b; /* else previous instruction set top */ - L->savedpc = pc; - switch (luaD_precall(L, ra, nresults)) { - case PCRLUA: { - nexeccalls++; - goto reentry; /* restart luaV_execute over new Lua function */ - } - case PCRC: { - /* it was a C function (`precall' called it); adjust results */ - if (nresults >= 0) L->top = L->ci->top; - base = L->base; - continue; - } - default: { - return; /* yield */ - } - } - } - case OP_TAILCALL: { - int b = GETARG_B(i); - if (b != 0) L->top = ra+b; /* else previous instruction set top */ - L->savedpc = pc; - lua_assert(GETARG_C(i) - 1 == LUA_MULTRET); - switch (luaD_precall(L, ra, LUA_MULTRET)) { - case PCRLUA: { - /* tail call: put new frame in place of previous one */ - CallInfo *ci = L->ci - 1; /* previous frame */ - int aux; - StkId func = ci->func; - StkId pfunc = (ci+1)->func; /* previous function index */ - if (L->openupval) luaF_close(L, ci->base); - L->base = ci->base = ci->func + ((ci+1)->base - pfunc); - for (aux = 0; pfunc+aux < L->top; aux++) /* move frame down */ - setobjs2s(L, func+aux, pfunc+aux); - ci->top = L->top = func+aux; /* correct top */ - lua_assert(L->top == L->base + clvalue(func)->l.p->maxstacksize); - ci->savedpc = L->savedpc; - ci->tailcalls++; /* one more call lost */ - L->ci--; /* remove new frame */ - goto reentry; - } - case PCRC: { /* it was a C function (`precall' called it) */ - base = L->base; - continue; - } - default: { - return; /* yield */ - } - } - } - case OP_RETURN: { - int b = GETARG_B(i); - if (b != 0) L->top = ra+b-1; - if (L->openupval) luaF_close(L, base); - L->savedpc = pc; - b = luaD_poscall(L, ra); - if (--nexeccalls == 0) /* was previous function running `here'? */ - return; /* no: return */ - else { /* yes: continue its execution */ - if (b) L->top = L->ci->top; - lua_assert(isLua(L->ci)); - lua_assert(GET_OPCODE(*((L->ci)->savedpc - 1)) == OP_CALL); - goto reentry; - } - } - case OP_FORLOOP: { - lua_Number step = nvalue(ra+2); - lua_Number idx = luai_numadd(nvalue(ra), step); /* increment index */ - lua_Number limit = nvalue(ra+1); - if (luai_numlt(0, step) ? luai_numle(idx, limit) - : luai_numle(limit, idx)) { - dojump(L, pc, GETARG_sBx(i)); /* jump back */ - setnvalue(ra, idx); /* update internal index... */ - setnvalue(ra+3, idx); /* ...and external index */ - } - continue; - } - case OP_FORPREP: { - const TValue *init = ra; - const TValue *plimit = ra+1; - const TValue *pstep = ra+2; - L->savedpc = pc; /* next steps may throw errors */ - if (!tonumber(init, ra)) - luaG_runerror(L, LUA_QL("for") " initial value must be a number"); - else if (!tonumber(plimit, ra+1)) - luaG_runerror(L, LUA_QL("for") " limit must be a number"); - else if (!tonumber(pstep, ra+2)) - luaG_runerror(L, LUA_QL("for") " step must be a number"); - setnvalue(ra, luai_numsub(nvalue(ra), nvalue(pstep))); - dojump(L, pc, GETARG_sBx(i)); - continue; - } - case OP_TFORLOOP: { - StkId cb = ra + 3; /* call base */ - setobjs2s(L, cb+2, ra+2); - setobjs2s(L, cb+1, ra+1); - setobjs2s(L, cb, ra); - L->top = cb+3; /* func. + 2 args (state and index) */ - Protect(luaD_call(L, cb, GETARG_C(i))); - L->top = L->ci->top; - cb = RA(i) + 3; /* previous call may change the stack */ - if (!ttisnil(cb)) { /* continue loop? */ - setobjs2s(L, cb-1, cb); /* save control variable */ - dojump(L, pc, GETARG_sBx(*pc)); /* jump back */ - } - pc++; - continue; - } - case OP_SETLIST: { - int n = GETARG_B(i); - int c = GETARG_C(i); - int last; - Table *h; - if (n == 0) { - n = cast_int(L->top - ra) - 1; - L->top = L->ci->top; - } - if (c == 0) c = cast_int(*pc++); - runtime_check(L, ttistable(ra)); - h = hvalue(ra); - last = ((c-1)*LFIELDS_PER_FLUSH) + n; - if (last > h->sizearray) /* needs more space? */ - luaH_resizearray(L, h, last); /* pre-alloc it at once */ - for (; n > 0; n--) { - TValue *val = ra+n; - setobj2t(L, luaH_setnum(L, h, last--), val); - luaC_barriert(L, h, val); - } - continue; - } - case OP_CLOSE: { - luaF_close(L, ra); - continue; - } - case OP_CLOSURE: { - Proto *p; - Closure *ncl; - int nup, j; - p = cl->p->p[GETARG_Bx(i)]; - nup = p->nups; - ncl = luaF_newLclosure(L, nup, cl->env); - ncl->l.p = p; - for (j=0; jl.upvals[j] = cl->upvals[GETARG_B(*pc)]; - else { - lua_assert(GET_OPCODE(*pc) == OP_MOVE); - ncl->l.upvals[j] = luaF_findupval(L, base + GETARG_B(*pc)); - } - } - setclvalue(L, ra, ncl); - Protect(luaC_checkGC(L)); - continue; - } - case OP_VARARG: { - int b = GETARG_B(i) - 1; - int j; - CallInfo *ci = L->ci; - int n = cast_int(ci->base - ci->func) - cl->p->numparams - 1; - if (b == LUA_MULTRET) { - Protect(luaD_checkstack(L, n)); - ra = RA(i); /* previous call may change the stack */ - b = n; - L->top = ra + n; - } - for (j = 0; j < b; j++) { - if (j < n) { - setobjs2s(L, ra + j, ci->base - n + j); - } - else { - setnilvalue(ra + j); - } - } - continue; - } - } - } -} - diff --git a/Utilities/lua-5.1.5/src/lvm.h b/Utilities/lua-5.1.5/src/lvm.h deleted file mode 100644 index bfe4f5678..000000000 --- a/Utilities/lua-5.1.5/src/lvm.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -** $Id: lvm.h,v 2.5.1.1 2007/12/27 13:02:25 roberto Exp $ -** Lua virtual machine -** See Copyright Notice in lua.h -*/ - -#ifndef lvm_h -#define lvm_h - - -#include "ldo.h" -#include "lobject.h" -#include "ltm.h" - - -#define tostring(L,o) ((ttype(o) == LUA_TSTRING) || (luaV_tostring(L, o))) - -#define tonumber(o,n) (ttype(o) == LUA_TNUMBER || \ - (((o) = luaV_tonumber(o,n)) != NULL)) - -#define equalobj(L,o1,o2) \ - (ttype(o1) == ttype(o2) && luaV_equalval(L, o1, o2)) - - -LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r); -LUAI_FUNC int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2); -LUAI_FUNC const TValue *luaV_tonumber (const TValue *obj, TValue *n); -LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj); -LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key, - StkId val); -LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key, - StkId val); -LUAI_FUNC void luaV_execute (lua_State *L, int nexeccalls); -LUAI_FUNC void luaV_concat (lua_State *L, int total, int last); - -#endif diff --git a/Utilities/lua-5.1.5/src/lzio.c b/Utilities/lua-5.1.5/src/lzio.c deleted file mode 100644 index 293edd59b..000000000 --- a/Utilities/lua-5.1.5/src/lzio.c +++ /dev/null @@ -1,82 +0,0 @@ -/* -** $Id: lzio.c,v 1.31.1.1 2007/12/27 13:02:25 roberto Exp $ -** a generic input stream interface -** See Copyright Notice in lua.h -*/ - - -#include - -#define lzio_c -#define LUA_CORE - -#include "lua.h" - -#include "llimits.h" -#include "lmem.h" -#include "lstate.h" -#include "lzio.h" - - -int luaZ_fill (ZIO *z) { - size_t size; - lua_State *L = z->L; - const char *buff; - lua_unlock(L); - buff = z->reader(L, z->data, &size); - lua_lock(L); - if (buff == NULL || size == 0) return EOZ; - z->n = size - 1; - z->p = buff; - return char2int(*(z->p++)); -} - - -int luaZ_lookahead (ZIO *z) { - if (z->n == 0) { - if (luaZ_fill(z) == EOZ) - return EOZ; - else { - z->n++; /* luaZ_fill removed first byte; put back it */ - z->p--; - } - } - return char2int(*z->p); -} - - -void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) { - z->L = L; - z->reader = reader; - z->data = data; - z->n = 0; - z->p = NULL; -} - - -/* --------------------------------------------------------------- read --- */ -size_t luaZ_read (ZIO *z, void *b, size_t n) { - while (n) { - size_t m; - if (luaZ_lookahead(z) == EOZ) - return n; /* return number of missing bytes */ - m = (n <= z->n) ? n : z->n; /* min. between n and z->n */ - memcpy(b, z->p, m); - z->n -= m; - z->p += m; - b = (char *)b + m; - n -= m; - } - return 0; -} - -/* ------------------------------------------------------------------------ */ -char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n) { - if (n > buff->buffsize) { - if (n < LUA_MINBUFFER) n = LUA_MINBUFFER; - luaZ_resizebuffer(L, buff, n); - } - return buff->buffer; -} - - diff --git a/Utilities/lua-5.1.5/src/lzio.h b/Utilities/lua-5.1.5/src/lzio.h deleted file mode 100644 index 51d695d8c..000000000 --- a/Utilities/lua-5.1.5/src/lzio.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -** $Id: lzio.h,v 1.21.1.1 2007/12/27 13:02:25 roberto Exp $ -** Buffered streams -** See Copyright Notice in lua.h -*/ - - -#ifndef lzio_h -#define lzio_h - -#include "lua.h" - -#include "lmem.h" - - -#define EOZ (-1) /* end of stream */ - -typedef struct Zio ZIO; - -#define char2int(c) cast(int, cast(unsigned char, (c))) - -#define zgetc(z) (((z)->n--)>0 ? char2int(*(z)->p++) : luaZ_fill(z)) - -typedef struct Mbuffer { - char *buffer; - size_t n; - size_t buffsize; -} Mbuffer; - -#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0) - -#define luaZ_buffer(buff) ((buff)->buffer) -#define luaZ_sizebuffer(buff) ((buff)->buffsize) -#define luaZ_bufflen(buff) ((buff)->n) - -#define luaZ_resetbuffer(buff) ((buff)->n = 0) - - -#define luaZ_resizebuffer(L, buff, size) \ - (luaM_reallocvector(L, (buff)->buffer, (buff)->buffsize, size, char), \ - (buff)->buffsize = size) - -#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) - - -LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n); -LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, - void *data); -LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n); /* read next n bytes */ -LUAI_FUNC int luaZ_lookahead (ZIO *z); - - - -/* --------- Private Part ------------------ */ - -struct Zio { - size_t n; /* bytes still unread */ - const char *p; /* current position in buffer */ - lua_Reader reader; - void* data; /* additional data */ - lua_State *L; /* Lua state (for reader) */ -}; - - -LUAI_FUNC int luaZ_fill (ZIO *z); - -#endif diff --git a/Utilities/lua-5.1.5/src/print.c b/Utilities/lua-5.1.5/src/print.c deleted file mode 100644 index e240cfc3c..000000000 --- a/Utilities/lua-5.1.5/src/print.c +++ /dev/null @@ -1,227 +0,0 @@ -/* -** $Id: print.c,v 1.55a 2006/05/31 13:30:05 lhf Exp $ -** print bytecodes -** See Copyright Notice in lua.h -*/ - -#include -#include - -#define luac_c -#define LUA_CORE - -#include "ldebug.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lundump.h" - -#define PrintFunction luaU_print - -#define Sizeof(x) ((int)sizeof(x)) -#define VOID(p) ((const void*)(p)) - -static void PrintString(const TString* ts) -{ - const char* s=getstr(ts); - size_t i,n=ts->tsv.len; - putchar('"'); - for (i=0; ik[i]; - switch (ttype(o)) - { - case LUA_TNIL: - printf("nil"); - break; - case LUA_TBOOLEAN: - printf(bvalue(o) ? "true" : "false"); - break; - case LUA_TNUMBER: - printf(LUA_NUMBER_FMT,nvalue(o)); - break; - case LUA_TSTRING: - PrintString(rawtsvalue(o)); - break; - default: /* cannot happen */ - printf("? type=%d",ttype(o)); - break; - } -} - -static void PrintCode(const Proto* f) -{ - const Instruction* code=f->code; - int pc,n=f->sizecode; - for (pc=0; pc0) printf("[%d]\t",line); else printf("[-]\t"); - printf("%-9s\t",luaP_opnames[o]); - switch (getOpMode(o)) - { - case iABC: - printf("%d",a); - if (getBMode(o)!=OpArgN) printf(" %d",ISK(b) ? (-1-INDEXK(b)) : b); - if (getCMode(o)!=OpArgN) printf(" %d",ISK(c) ? (-1-INDEXK(c)) : c); - break; - case iABx: - if (getBMode(o)==OpArgK) printf("%d %d",a,-1-bx); else printf("%d %d",a,bx); - break; - case iAsBx: - if (o==OP_JMP) printf("%d",sbx); else printf("%d %d",a,sbx); - break; - } - switch (o) - { - case OP_LOADK: - printf("\t; "); PrintConstant(f,bx); - break; - case OP_GETUPVAL: - case OP_SETUPVAL: - printf("\t; %s", (f->sizeupvalues>0) ? getstr(f->upvalues[b]) : "-"); - break; - case OP_GETGLOBAL: - case OP_SETGLOBAL: - printf("\t; %s",svalue(&f->k[bx])); - break; - case OP_GETTABLE: - case OP_SELF: - if (ISK(c)) { printf("\t; "); PrintConstant(f,INDEXK(c)); } - break; - case OP_SETTABLE: - case OP_ADD: - case OP_SUB: - case OP_MUL: - case OP_DIV: - case OP_POW: - case OP_EQ: - case OP_LT: - case OP_LE: - if (ISK(b) || ISK(c)) - { - printf("\t; "); - if (ISK(b)) PrintConstant(f,INDEXK(b)); else printf("-"); - printf(" "); - if (ISK(c)) PrintConstant(f,INDEXK(c)); else printf("-"); - } - break; - case OP_JMP: - case OP_FORLOOP: - case OP_FORPREP: - printf("\t; to %d",sbx+pc+2); - break; - case OP_CLOSURE: - printf("\t; %p",VOID(f->p[bx])); - break; - case OP_SETLIST: - if (c==0) printf("\t; %d",(int)code[++pc]); - else printf("\t; %d",c); - break; - default: - break; - } - printf("\n"); - } -} - -#define SS(x) (x==1)?"":"s" -#define S(x) x,SS(x) - -static void PrintHeader(const Proto* f) -{ - const char* s=getstr(f->source); - if (*s=='@' || *s=='=') - s++; - else if (*s==LUA_SIGNATURE[0]) - s="(bstring)"; - else - s="(string)"; - printf("\n%s <%s:%d,%d> (%d instruction%s, %d bytes at %p)\n", - (f->linedefined==0)?"main":"function",s, - f->linedefined,f->lastlinedefined, - S(f->sizecode),f->sizecode*Sizeof(Instruction),VOID(f)); - printf("%d%s param%s, %d slot%s, %d upvalue%s, ", - f->numparams,f->is_vararg?"+":"",SS(f->numparams), - S(f->maxstacksize),S(f->nups)); - printf("%d local%s, %d constant%s, %d function%s\n", - S(f->sizelocvars),S(f->sizek),S(f->sizep)); -} - -static void PrintConstants(const Proto* f) -{ - int i,n=f->sizek; - printf("constants (%d) for %p:\n",n,VOID(f)); - for (i=0; isizelocvars; - printf("locals (%d) for %p:\n",n,VOID(f)); - for (i=0; ilocvars[i].varname),f->locvars[i].startpc+1,f->locvars[i].endpc+1); - } -} - -static void PrintUpvalues(const Proto* f) -{ - int i,n=f->sizeupvalues; - printf("upvalues (%d) for %p:\n",n,VOID(f)); - if (f->upvalues==NULL) return; - for (i=0; iupvalues[i])); - } -} - -void PrintFunction(const Proto* f, int full) -{ - int i,n=f->sizep; - PrintHeader(f); - PrintCode(f); - if (full) - { - PrintConstants(f); - PrintLocals(f); - PrintUpvalues(f); - } - for (i=0; ip[i],full); -} From f7e5613385c19967e544371b3b60601c4d6095a6 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 11 Jun 2015 15:27:49 -0400 Subject: [PATCH 026/412] Add Superbuild of GoogleTest While GoogleTest has a CMake configuration file it does not have an "install" target not does it export dependencies of the libraries with CMake goodness. For installation we just copy the library and include directories. Change-Id: If6ac0815e9b8338038c7b23e53cbfdbd5466e853 --- SuperBuild/External_GTest.cmake | 42 +++++++++++++++++++++++++++++++++ SuperBuild/SuperBuild.cmake | 18 +++++++++++++- 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 SuperBuild/External_GTest.cmake diff --git a/SuperBuild/External_GTest.cmake b/SuperBuild/External_GTest.cmake new file mode 100644 index 000000000..709d44aa8 --- /dev/null +++ b/SuperBuild/External_GTest.cmake @@ -0,0 +1,42 @@ +# Make sure this file is included only once +get_filename_component(CMAKE_CURRENT_LIST_FILENAME ${CMAKE_CURRENT_LIST_FILE} NAME_WE) +if(${CMAKE_CURRENT_LIST_FILENAME}_FILE_INCLUDED) + return() +endif() +set(${CMAKE_CURRENT_LIST_FILENAME}_FILE_INCLUDED 1) + +set(proj GTest) + +set(GTEST_TARGET_VERSION 1.7.0) +set(GTEST_DOWNLOAD_SOURCE_HASH "2d6ec8ccdf5c46b05ba54a9fd1d130d7") + +# follow the standard EP_PREFIX locations +set(GTEST_binary_dir ${CMAKE_CURRENT_BINARY_DIR}/${proj}-prefix/src/${proj}-build) +set(GTEST_source_dir ${CMAKE_CURRENT_BINARY_DIR}/${proj}-prefix/src/${proj}) +set(GTEST_install_dir ${CMAKE_CURRENT_BINARY_DIR}/${proj}) + +file(WRITE "${GTEST_binary_dir}/CMakeCacheInit.txt" "${ep_common_cache}" ) + +set(GTEST_PATCH_COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${CMAKE_CURRENT_SOURCE_DIR}/lua.cmake + ${lua_source_dir}/CMakeLists.txt +) + +ExternalProject_Add(${proj} + URL http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${GTEST_DOWNLOAD_SOURCE_HASH}&name=swig-${GTEST_TARGET_VERSION}.zip + URL_MD5 ${GTEST_DOWNLOAD_SOURCE_HASH} + INSTALL_DIR ${GTEST_install_dir} + CMAKE_GENERATOR ${gen} + CMAKE_ARGS + --no-warn-unused-cli + -C "${GTEST_binary_dir}/CMakeCacheInit.txt" + ${ep_common_args} + -D BUILD_SHARED_LIBS:BOOL=OFF + -D CMAKE_ARCHIVE_OUTPUT_DIRECTORY:PATH=/lib + INSTALL_COMMAND + ${CMAKE_COMMAND} -E copy_directory /lib /lib + COMMAND + ${CMAKE_COMMAND} -E copy_directory /include /include +) + +set(GTEST_ROOT ${GTEST_install_dir}) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 867cd4ec1..24fcc2615 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -259,6 +259,22 @@ else() list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES Swig) endif() +#------------------------------------------------------------------------------ +# Google Test +#------------------------------------------------------------------------------ +option( USE_SYSTEM_GTEST "Use a pre-compiled version of GoogleTest. " OFF ) +if ( BUILD_TESTING ) + if (USE_SYSTEM_GTEST) + find_package( GTest REQUIRED ) + list(APPEND SimpleITKITK_VARS GTEST_LIBRARIES GTEST_INCLUDE_DIRS GTEST_MAIN_LIBRARIES) + else() + include(External_GTest) + set( GTEST_ROOT ${GTEST_ROOT} CACHE PATH "The root directory of the gtest install prefix" ) + list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES GTest) + list(APPEND SimpleITKITK_VARS GTEST_ROOT) + endif() +endif() + #------------------------------------------------------------------------------ # ITK #------------------------------------------------------------------------------ @@ -358,7 +374,7 @@ include(External_SimpleITKExamples) #------------------------------------------------------------------------------ # List of external projects #------------------------------------------------------------------------------ -set(external_project_list ITK Swig SimpleITKExamples PCRE ${CMAKE_PROJECT_NAME}) +set(external_project_list ITK Swig SimpleITKExamples PCRE GTest ${CMAKE_PROJECT_NAME}) #----------------------------------------------------------------------------- # Dump external project dependencies From e8f97f8f150dcb403a8016f7722e5f565538c663 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 11 Jun 2015 15:28:13 -0400 Subject: [PATCH 027/412] Use find_package for google test Add support for using system GoogleTest by no longer compiling it inside SimpleITK. Remove our custom ADD_GOOGLE_TEST macro, and use the version for CMake, which was inspired by this implementation by Dan Blezek. Change-Id: I7a7eb6b4d6a686231392619221c26d285d4543c5 --- Testing/Unit/CMakeLists.txt | 85 ++++++------------------------------- 1 file changed, 14 insertions(+), 71 deletions(-) diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index 8975f818b..4bb917d2a 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -2,6 +2,8 @@ set ( ITK_NO_IO_FACTORY_REGISTER_MANAGER 1 ) include(${ITK_USE_FILE}) +find_package( GTest REQUIRED ) + set ( SimpleITKUnitTestSourceBase SimpleITKTestHarness.cxx sitkImageCompare.cxx @@ -9,10 +11,10 @@ set ( SimpleITKUnitTestSourceBase ) add_library ( SimpleITKUnitTestBase STATIC ${SimpleITKUnitTestSourceBase} ) add_dependencies( SimpleITKUnitTestBase BasicFiltersSourceCode ) -target_link_libraries( SimpleITKUnitTestBase gtest ${SimpleITK_LIBRARIES} ) +target_link_libraries( SimpleITKUnitTestBase ${GTEST_LIBRARIES} ${SimpleITK_LIBRARIES} ) add_executable( sitkTransformCompareDriver sitkTransformCompareDriver.cxx ) -target_link_libraries( sitkTransformCompareDriver gtest SimpleITKUnitTestBase ${SimpleITK_LIBRARIES} ) +target_link_libraries( sitkTransformCompareDriver ${GTEST_LIBRARIES} SimpleITKUnitTestBase ${SimpleITK_LIBRARIES} ) # Find tests generated in the binary directory # To add a new file, just add it to this list. Any GoogleTests inside will be automatically # added to ctest. @@ -50,7 +52,7 @@ set( PythonVirtualenvHome ${SimpleITK_BINARY_DIR}/Testing/Installation/PythonVir add_executable(SimpleITKUnitTestDriver0 SimpleITKUnitTestDriver.cxx ${SimpleITKUnitTestSource}) -target_link_libraries ( SimpleITKUnitTestDriver0 gtest SimpleITKUnitTestBase ${SimpleITK_LIBRARIES} ) +target_link_libraries ( SimpleITKUnitTestDriver0 ${GTEST_LIBRARIES} SimpleITKUnitTestBase ${SimpleITK_LIBRARIES} ) # # Glob for necessary template files up front, before the foreach loop over @@ -78,7 +80,7 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) if ( NOT _i LESS _stride ) add_executable(SimpleITKUnitTestDriver${_exec_i} SimpleITKUnitTestDriver.cxx ${GENERATED_TEST_SOURCE}) - target_link_libraries ( SimpleITKUnitTestDriver${_exec_i} gtest SimpleITKUnitTestBase ${SimpleITK_LIBRARIES} ) + target_link_libraries ( SimpleITKUnitTestDriver${_exec_i} ${GTEST_LIBRARIES} SimpleITKUnitTestBase ${SimpleITK_LIBRARIES} ) math(EXPR _exec_i "${_exec_i}+1") set(GENERATED_TEST_SOURCE "") set ( _i 0 ) @@ -214,19 +216,7 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) endforeach() add_executable(SimpleITKUnitTestDriver${_exec_i} SimpleITKUnitTestDriver.cxx ${GENERATED_TEST_SOURCE}) -target_link_libraries ( SimpleITKUnitTestDriver${_exec_i} gtest SimpleITKUnitTestBase ${SimpleITK_LIBRARIES} ) - -# Build Google Test -find_package(Threads) -if (CMAKE_USE_PTHREADS_INIT) # The pthreads library is available. - set(cxx_base_flags "${cxx_base_flags} -DGTEST_HAS_PTHREAD=1") -endif() - -# The gtest include file directories. -SET(GTEST_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/GoogleTest" PARENT_SCOPE) - -# The gtest library directories. -SET(GTEST_LIBRARY_DIRS "${CMAKE_CURRENT_BINARY_DIR}" PARENT_SCOPE) +target_link_libraries ( SimpleITKUnitTestDriver${_exec_i} ${GTEST_LIBRARIES} SimpleITKUnitTestBase ${SimpleITK_LIBRARIES} ) # Test data directory set(TEST_HARNESS_TEMP_DIRECTORY ${SimpleITK_BINARY_DIR}/Testing/Temporary) @@ -236,18 +226,13 @@ set(TEST_HARNESS_DATA_DIRECTORY ${SimpleITK_BINARY_DIR}/ExternalData/Testing/Dat configure_file(${CMAKE_CURRENT_SOURCE_DIR}/SimpleITKTestHarnessPaths.h.in ${CMAKE_CURRENT_BINARY_DIR}/SimpleITKTestHarnessPaths.h ESCAPE_QUOTES) -# Build Google Testing -set ( GTestSource - GoogleTest/gtest/gtest-all.cc -) -include_directories ( GoogleTest ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) -add_library(gtest STATIC ${GTestSource}) -if (CMAKE_USE_PTHREADS_INIT) - target_link_libraries(gtest ${CMAKE_THREAD_LIBS_INIT}) -endif() - -include_directories ( ${SimpleITK_INCLUDE_DIRS} ) +include_directories ( + ${SimpleITK_INCLUDE_DIRS} + ${GTEST_INCLUDE_DIRS} + ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_CURRENT_SOURCE_DIR} + ) add_custom_target(WrappedGeneratedTests ALL DEPENDS ${WRAPPED_GENERATED_TEST_SOURCE} @@ -271,49 +256,7 @@ target_link_libraries( sitkSystemInformationTest ${SimpleITK_LIBRARIES} ) add_test( NAME sitkSystemInformaionTest COMMAND sitkSystemInformationTest ${CMAKE_BINARY_DIR} ) -# Add all the tests by parsing the source code -# This macro searches for GoogleTest macros and adds them as test automatically -macro(ADD_GOOGLE_TESTS target) - # Add the generated tests - set ( AllTestsHits "" ) - set ( LongTestsHits "" ) - - foreach ( source ${ARGN} ) - file(READ "${source}" contents) - - # Find all test and long test lists - string(REGEX MATCHALL "TEST_?F?\\(([A-Za-z_0-9 ,_]+)\\) /\\* Long \\*/" LongTests ${contents}) - string(REGEX MATCHALL "TEST_?F?\\(([A-Za-z_0-9 ,_]+)\\)" AllTests ${contents}) - - # Convert the C++ code into a short test name - foreach(hit ${AllTests}) - string(REGEX REPLACE ".*\\( *( *[A-Za-z_0-9]+)[, ]*([A-Za-z_0-9]+) *\\).*" "\\1.\\2" test_name ${hit}) - set ( AllTestsHits ${AllTestsHits} ${test_name} ) - endforeach() - foreach(hit ${LongTests}) - string(REGEX REPLACE ".*\\(( *[A-Za-z_0-9]+)[, ]*([A-Za-z_0-9]+) *\\).*" "\\1.\\2" test_name ${hit}) - set ( LongTestsHits ${LongTestsHits} ${test_name} ) - endforeach() - endforeach() - - # If we are not running the long tests, remove them from the AllTests list - if ( NOT RUN_LONG_TESTS ) - foreach ( test ${LongTestsHits} ) - list ( REMOVE_ITEM AllTestsHits ${test} ) - endforeach() - endif () - - list ( SORT AllTestsHits ) - list ( REMOVE_DUPLICATES AllTestsHits ) - # Add all the remaining tests to CTest's test list - foreach(hit ${AllTestsHits}) - # Take the first item in gtest list as the name - string( REGEX MATCH "[^:]+" name ${hit} ) - add_test( NAME ${name} COMMAND ${target} --gtest_filter=${hit} ) - endforeach() -endmacro() - -add_google_tests(SimpleITKUnitTestDriver0 ${SimpleITKUnitTestSource}) +gtest_add_tests(SimpleITKUnitTestDriver0 ${SimpleITKUnitTestSource}) ####################################################### From bfd34f779245710685fa09974b6a522b7240ada3 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 12 Jun 2015 08:46:24 -0400 Subject: [PATCH 028/412] Remove anonymous namespace for std::vector output operator. This addresses compilation issues with gcc 4.8 and gtest 1.7.0 not finding this function. Change-Id: If5703cd7f56a2cd3f64247c747f22948a0cbc93c --- Testing/Unit/SimpleITKTestHarness.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/Testing/Unit/SimpleITKTestHarness.h b/Testing/Unit/SimpleITKTestHarness.h index cf9ed12fb..ef8eb2754 100644 --- a/Testing/Unit/SimpleITKTestHarness.h +++ b/Testing/Unit/SimpleITKTestHarness.h @@ -26,7 +26,6 @@ // This is needed before the gtest include for lookup of the operator // to work with clang 5.1 -namespace { inline std::ostream& operator<< (std::ostream& os, const std::vector& v) { if ( v.empty() ) @@ -38,7 +37,6 @@ inline std::ostream& operator<< (std::ostream& os, const std::vector& v) std::copy( v.begin(), v.end()-1, std::ostream_iterator(os, ", ") ); return os << v.back() << " ]"; } -} #include #include From f208f9ed9091bfaf4269f1c0d7a5b8802eee2ac6 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 12 Jun 2015 10:51:10 -0400 Subject: [PATCH 029/412] Remove the GTest source code from testing Change-Id: I63cbc2ef99e5b1c63ca8ca13e88ec5feb2e6c8d6 --- Testing/Unit/GoogleTest/COPYING | 28 - Testing/Unit/GoogleTest/README | 424 - Testing/Unit/GoogleTest/gtest/gtest-all.cc | 9118 -------- Testing/Unit/GoogleTest/gtest/gtest.h | 19550 ------------------ Testing/Unit/GoogleTest/gtest/gtest_main.cc | 39 - 5 files changed, 29159 deletions(-) delete mode 100644 Testing/Unit/GoogleTest/COPYING delete mode 100644 Testing/Unit/GoogleTest/README delete mode 100644 Testing/Unit/GoogleTest/gtest/gtest-all.cc delete mode 100644 Testing/Unit/GoogleTest/gtest/gtest.h delete mode 100644 Testing/Unit/GoogleTest/gtest/gtest_main.cc diff --git a/Testing/Unit/GoogleTest/COPYING b/Testing/Unit/GoogleTest/COPYING deleted file mode 100644 index 1941a11f8..000000000 --- a/Testing/Unit/GoogleTest/COPYING +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2008, Google Inc. -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 name of Google Inc. nor the names of its -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 -OWNER 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. diff --git a/Testing/Unit/GoogleTest/README b/Testing/Unit/GoogleTest/README deleted file mode 100644 index 51a9376db..000000000 --- a/Testing/Unit/GoogleTest/README +++ /dev/null @@ -1,424 +0,0 @@ -Google C++ Testing Framework -============================ - -http://code.google.com/p/googletest/ - -Overview --------- - -Google's framework for writing C++ tests on a variety of platforms -(Linux, Mac OS X, Windows, Windows CE, Symbian, etc). Based on the -xUnit architecture. Supports automatic test discovery, a rich set of -assertions, user-defined assertions, death tests, fatal and non-fatal -failures, various options for running the tests, and XML test report -generation. - -Please see the project page above for more information as well as the -mailing list for questions, discussions, and development. There is -also an IRC channel on OFTC (irc.oftc.net) #gtest available. Please -join us! - -Requirements for End Users --------------------------- - -Google Test is designed to have fairly minimal requirements to build -and use with your projects, but there are some. Currently, we support -Linux, Windows, Mac OS X, and Cygwin. We will also make our best -effort to support other platforms (e.g. Solaris, AIX, and z/OS). -However, since core members of the Google Test project have no access -to these platforms, Google Test may have outstanding issues there. If -you notice any problems on your platform, please notify -googletestframework@googlegroups.com. Patches for fixing them are -even more welcome! - -### Linux Requirements ### - -These are the base requirements to build and use Google Test from a source -package (as described below): - * GNU-compatible Make or gmake - * POSIX-standard shell - * POSIX(-2) Regular Expressions (regex.h) - * A C++98-standard-compliant compiler - -### Windows Requirements ### - - * Microsoft Visual C++ 7.1 or newer - -### Cygwin Requirements ### - - * Cygwin 1.5.25-14 or newer - -### Mac OS X Requirements ### - - * Mac OS X 10.4 Tiger or newer - * Developer Tools Installed - -Also, you'll need CMake 2.6.4 or higher if you want to build the -samples using the provided CMake script, regardless of the platform. - -Requirements for Contributors ------------------------------ - -We welcome patches. If you plan to contribute a patch, you need to -build Google Test and its own tests from an SVN checkout (described -below), which has further requirements: - - * Python version 2.3 or newer (for running some of the tests and - re-generating certain source files from templates) - * CMake 2.6.4 or newer - -Getting the Source ------------------- - -There are two primary ways of getting Google Test's source code: you -can download a stable source release in your preferred archive format, -or directly check out the source from our Subversion (SVN) repositary. -The SVN checkout requires a few extra steps and some extra software -packages on your system, but lets you track the latest development and -make patches much more easily, so we highly encourage it. - -### Source Package ### - -Google Test is released in versioned source packages which can be -downloaded from the download page [1]. Several different archive -formats are provided, but the only difference is the tools used to -manipulate them, and the size of the resulting file. Download -whichever you are most comfortable with. - - [1] http://code.google.com/p/googletest/downloads/list - -Once the package is downloaded, expand it using whichever tools you -prefer for that type. This will result in a new directory with the -name "gtest-X.Y.Z" which contains all of the source code. Here are -some examples on Linux: - - tar -xvzf gtest-X.Y.Z.tar.gz - tar -xvjf gtest-X.Y.Z.tar.bz2 - unzip gtest-X.Y.Z.zip - -### SVN Checkout ### - -To check out the main branch (also known as the "trunk") of Google -Test, run the following Subversion command: - - svn checkout http://googletest.googlecode.com/svn/trunk/ gtest-svn - -Setting up the Build --------------------- - -To build Google Test and your tests that use it, you need to tell your -build system where to find its headers and source files. The exact -way to do it depends on which build system you use, and is usually -straightforward. - -### Generic Build Instructions ### - -Suppose you put Google Test in directory ${GTEST_DIR}. To build it, -create a library build target (or a project as called by Visual Studio -and Xcode) to compile - - ${GTEST_DIR}/src/gtest-all.cc - -with - - ${GTEST_DIR}/include and ${GTEST_DIR} - -in the header search path. Assuming a Linux-like system and gcc, -something like the following will do: - - g++ -I${GTEST_DIR}/include -I${GTEST_DIR} -c ${GTEST_DIR}/src/gtest-all.cc - ar -rv libgtest.a gtest-all.o - -Next, you should compile your test source file with -${GTEST_DIR}/include in the header search path, and link it with gtest -and any other necessary libraries: - - g++ -I${GTEST_DIR}/include path/to/your_test.cc libgtest.a -o your_test - -As an example, the make/ directory contains a Makefile that you can -use to build Google Test on systems where GNU make is available -(e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google -Test's own tests. Instead, it just builds the Google Test library and -a sample test. You can use it as a starting point for your own build -script. - -If the default settings are correct for your environment, the -following commands should succeed: - - cd ${GTEST_DIR}/make - make - ./sample1_unittest - -If you see errors, try to tweak the contents of make/Makefile to make -them go away. There are instructions in make/Makefile on how to do -it. - -### Using CMake ### - -Google Test comes with a CMake build script (CMakeLists.txt) that can -be used on a wide range of platforms ("C" stands for cross-platofrm.). -If you don't have CMake installed already, you can download it for -free from http://www.cmake.org/. - -CMake works by generating native makefiles or build projects that can -be used in the compiler environment of your choice. The typical -workflow starts with: - - mkdir mybuild # Create a directory to hold the build output. - cd mybuild - cmake ${GTEST_DIR} # Generate native build scripts. - -If you want to build Google Test's samples, you should replace the -last command with - - cmake -Dgtest_build_samples=ON ${GTEST_DIR} - -If you are on a *nix system, you should now see a Makefile in the -current directory. Just type 'make' to build gtest. - -If you use Windows and have Vistual Studio installed, a gtest.sln file -and several .vcproj files will be created. You can then build them -using Visual Studio. - -On Mac OS X with Xcode installed, a .xcodeproj file will be generated. - -### Legacy Build Scripts ### - -Before settling on CMake, we have been providing hand-maintained build -projects/scripts for Visual Studio, Xcode, and Autotools. While we -continue to provide them for convenience, they are not actively -maintained any more. We highly recommend that you follow the -instructions in the previous two sections to integrate Google Test -with your existing build system. - -If you still need to use the legacy build scripts, here's how: - -The msvc\ folder contains two solutions with Visual C++ projects. -Open the gtest.sln or gtest-md.sln file using Visual Studio, and you -are ready to build Google Test the same way you build any Visual -Studio project. Files that have names ending with -md use DLL -versions of Microsoft runtime libraries (the /MD or the /MDd compiler -option). Files without that suffix use static versions of the runtime -libraries (the /MT or the /MTd option). Please note that one must use -the same option to compile both gtest and the test code. If you use -Visual Studio 2005 or above, we recommend the -md version as /MD is -the default for new projects in these versions of Visual Studio. - -On Mac OS X, open the gtest.xcodeproj in the xcode/ folder using -Xcode. Build the "gtest" target. The universal binary framework will -end up in your selected build directory (selected in the Xcode -"Preferences..." -> "Building" pane and defaults to xcode/build). -Alternatively, at the command line, enter: - - xcodebuild - -This will build the "Release" configuration of gtest.framework in your -default build location. See the "xcodebuild" man page for more -information about building different configurations and building in -different locations. - -Tweaking Google Test --------------------- - -Google Test can be used in diverse environments. The default -configuration may not work (or may not work well) out of the box in -some environments. However, you can easily tweak Google Test by -defining control macros on the compiler command line. Generally, -these macros are named like GTEST_XYZ and you define them to either 1 -or 0 to enable or disable a certain feature. - -We list the most frequently used macros below. For a complete list, -see file include/gtest/internal/gtest-port.h. - -### Choosing a TR1 Tuple Library ### - -Some Google Test features require the C++ Technical Report 1 (TR1) -tuple library, which is not yet available with all compilers. The -good news is that Google Test implements a subset of TR1 tuple that's -enough for its own need, and will automatically use this when the -compiler doesn't provide TR1 tuple. - -Usually you don't need to care about which tuple library Google Test -uses. However, if your project already uses TR1 tuple, you need to -tell Google Test to use the same TR1 tuple library the rest of your -project uses, or the two tuple implementations will clash. To do -that, add - - -DGTEST_USE_OWN_TR1_TUPLE=0 - -to the compiler flags while compiling Google Test and your tests. If -you want to force Google Test to use its own tuple library, just add - - -DGTEST_USE_OWN_TR1_TUPLE=1 - -to the compiler flags instead. - -If you don't want Google Test to use tuple at all, add - - -DGTEST_HAS_TR1_TUPLE=0 - -and all features using tuple will be disabled. - -### Multi-threaded Tests ### - -Google Test is thread-safe where the pthread library is available. -After #include "gtest/gtest.h", you can check the GTEST_IS_THREADSAFE -macro to see whether this is the case (yes if the macro is #defined to -1, no if it's undefined.). - -If Google Test doesn't correctly detect whether pthread is available -in your environment, you can force it with - - -DGTEST_HAS_PTHREAD=1 - -or - - -DGTEST_HAS_PTHREAD=0 - -When Google Test uses pthread, you may need to add flags to your -compiler and/or linker to select the pthread library, or you'll get -link errors. If you use the CMake script or the deprecated Autotools -script, this is taken care of for you. If you use your own build -script, you'll need to read your compiler and linker's manual to -figure out what flags to add. - -### As a Shared Library (DLL) ### - -Google Test is compact, so most users can build and link it as a -static library for the simplicity. You can choose to use Google Test -as a shared library (known as a DLL on Windows) if you prefer. - -To compile *gtest* as a shared library, add - - -DGTEST_CREATE_SHARED_LIBRARY=1 - -to the compiler flags. You'll also need to tell the linker to produce -a shared library instead - consult your linker's manual for how to do -it. - -To compile your *tests* that use the gtest shared library, add - - -DGTEST_LINKED_AS_SHARED_LIBRARY=1 - -to the compiler flags. - -Note: while the above steps aren't technically necessary today when -using some compilers (e.g. GCC), they may become necessary in the -future, if we decide to improve the speed of loading the library (see -http://gcc.gnu.org/wiki/Visibility for details). Therefore you are -recommended to always add the above flags when using Google Test as a -shared library. Otherwise a future release of Google Test may break -your build script. - -### Avoiding Macro Name Clashes ### - -In C++, macros don't obey namespaces. Therefore two libraries that -both define a macro of the same name will clash if you #include both -definitions. In case a Google Test macro clashes with another -library, you can force Google Test to rename its macro to avoid the -conflict. - -Specifically, if both Google Test and some other code define macro -FOO, you can add - - -DGTEST_DONT_DEFINE_FOO=1 - -to the compiler flags to tell Google Test to change the macro's name -from FOO to GTEST_FOO. Currently FOO can be FAIL, SUCCEED, or TEST. -For example, with -DGTEST_DONT_DEFINE_TEST=1, you'll need to write - - GTEST_TEST(SomeTest, DoesThis) { ... } - -instead of - - TEST(SomeTest, DoesThis) { ... } - -in order to define a test. - -Upgrating from an Earlier Version ---------------------------------- - -We strive to keep Google Test releases backward compatible. -Sometimes, though, we have to make some breaking changes for the -users' long-term benefits. This section describes what you'll need to -do if you are upgrading from an earlier version of Google Test. - -### Upgrading from 1.3.0 or Earlier ### - -You may need to explicitly enable or disable Google Test's own TR1 -tuple library. See the instructions in section "Choosing a TR1 Tuple -Library". - -### Upgrading from 1.4.0 or Earlier ### - -The Autotools build script (configure + make) is no longer officially -supportted. You are encouraged to migrate to your own build system or -use CMake. If you still need to use Autotools, you can find -instructions in the README file from Google Test 1.4.0. - -On platforms where the pthread library is available, Google Test uses -it in order to be thread-safe. See the "Multi-threaded Tests" section -for what this means to your build script. - -If you use Microsoft Visual C++ 7.1 with exceptions disabled, Google -Test will no longer compile. This should affect very few people, as a -large portion of STL (including ) doesn't compile in this mode -anyway. We decided to stop supporting it in order to greatly simplify -Google Test's implementation. - -Developing Google Test ----------------------- - -This section discusses how to make your own changes to Google Test. - -### Testing Google Test Itself ### - -To make sure your changes work as intended and don't break existing -functionality, you'll want to compile and run Google Test's own tests. -For that you can use CMake: - - mkdir mybuild - cd mybuild - cmake -Dgtest_build_tests=ON ${GTEST_DIR} - -Make sure you have Python installed, as some of Google Test's tests -are written in Python. If the cmake command complains about not being -able to find Python ("Could NOT find PythonInterp (missing: -PYTHON_EXECUTABLE)"), try telling it explicitly where your Python -executable can be found: - - cmake -DPYTHON_EXECUTABLE=path/to/python -Dgtest_build_tests=ON ${GTEST_DIR} - -Next, you can build Google Test and all of its own tests. On *nix, -this is usually done by 'make'. To run the tests, do - - make test - -All tests should pass. - -### Regenerating Source Files ### - -Some of Google Test's source files are generated from templates (not -in the C++ sense) using a script. A template file is named FOO.pump, -where FOO is the name of the file it will generate. For example, the -file include/gtest/internal/gtest-type-util.h.pump is used to generate -gtest-type-util.h in the same directory. - -Normally you don't need to worry about regenerating the source files, -unless you need to modify them. In that case, you should modify the -corresponding .pump files instead and run the pump.py Python script to -regenerate them. You can find pump.py in the scripts/ directory. -Read the Pump manual [2] for how to use it. - - [2] http://code.google.com/p/googletest/wiki/PumpManual - -### Contributing a Patch ### - -We welcome patches. Please read the Google Test developer's guide [3] -for how you can contribute. In particular, make sure you have signed -the Contributor License Agreement, or we won't be able to accept the -patch. - - [3] http://code.google.com/p/googletest/wiki/GoogleTestDevGuide - -Happy testing! diff --git a/Testing/Unit/GoogleTest/gtest/gtest-all.cc b/Testing/Unit/GoogleTest/gtest/gtest-all.cc deleted file mode 100644 index 5ced66a90..000000000 --- a/Testing/Unit/GoogleTest/gtest/gtest-all.cc +++ /dev/null @@ -1,9118 +0,0 @@ -// Copyright 2008, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: mheule@google.com (Markus Heule) -// -// Google C++ Testing Framework (Google Test) -// -// Sometimes it's desirable to build Google Test by compiling a single file. -// This file serves this purpose. - -// This line ensures that gtest.h can be compiled on its own, even -// when it's fused. -#include "gtest/gtest.h" - -// The following lines pull in the real gtest *.cc files. -// Copyright 2005, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) -// -// The Google C++ Testing Framework (Google Test) - -// Copyright 2007, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) -// -// Utilities for testing Google Test itself and code that uses Google Test -// (e.g. frameworks built on top of Google Test). - -#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ -#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ - - -namespace testing { - -// This helper class can be used to mock out Google Test failure reporting -// so that we can test Google Test or code that builds on Google Test. -// -// An object of this class appends a TestPartResult object to the -// TestPartResultArray object given in the constructor whenever a Google Test -// failure is reported. It can either intercept only failures that are -// generated in the same thread that created this object or it can intercept -// all generated failures. The scope of this mock object can be controlled with -// the second argument to the two arguments constructor. -class GTEST_API_ ScopedFakeTestPartResultReporter - : public TestPartResultReporterInterface { - public: - // The two possible mocking modes of this object. - enum InterceptMode { - INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures. - INTERCEPT_ALL_THREADS // Intercepts all failures. - }; - - // The c'tor sets this object as the test part result reporter used - // by Google Test. The 'result' parameter specifies where to report the - // results. This reporter will only catch failures generated in the current - // thread. DEPRECATED - explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); - - // Same as above, but you can choose the interception scope of this object. - ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, - TestPartResultArray* result); - - // The d'tor restores the previous test part result reporter. - virtual ~ScopedFakeTestPartResultReporter(); - - // Appends the TestPartResult object to the TestPartResultArray - // received in the constructor. - // - // This method is from the TestPartResultReporterInterface - // interface. - virtual void ReportTestPartResult(const TestPartResult& result); - private: - void Init(); - - const InterceptMode intercept_mode_; - TestPartResultReporterInterface* old_reporter_; - TestPartResultArray* const result_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter); -}; - -namespace internal { - -// A helper class for implementing EXPECT_FATAL_FAILURE() and -// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given -// TestPartResultArray contains exactly one failure that has the given -// type and contains the given substring. If that's not the case, a -// non-fatal failure will be generated. -class GTEST_API_ SingleFailureChecker { - public: - // The constructor remembers the arguments. - SingleFailureChecker(const TestPartResultArray* results, - TestPartResult::Type type, - const string& substr); - ~SingleFailureChecker(); - private: - const TestPartResultArray* const results_; - const TestPartResult::Type type_; - const string substr_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); -}; - -} // namespace internal - -} // namespace testing - -// A set of macros for testing Google Test assertions or code that's expected -// to generate Google Test fatal failures. It verifies that the given -// statement will cause exactly one fatal Google Test failure with 'substr' -// being part of the failure message. -// -// There are two different versions of this macro. EXPECT_FATAL_FAILURE only -// affects and considers failures generated in the current thread and -// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. -// -// The verification of the assertion is done correctly even when the statement -// throws an exception or aborts the current function. -// -// Known restrictions: -// - 'statement' cannot reference local non-static variables or -// non-static members of the current object. -// - 'statement' cannot return a value. -// - You cannot stream a failure message to this macro. -// -// Note that even though the implementations of the following two -// macros are much alike, we cannot refactor them to use a common -// helper macro, due to some peculiarity in how the preprocessor -// works. The AcceptsMacroThatExpandsToUnprotectedComma test in -// gtest_unittest.cc will fail to compile if we do that. -#define EXPECT_FATAL_FAILURE(statement, substr) \ - do { \ - class GTestExpectFatalFailureHelper {\ - public:\ - static void Execute() { statement; }\ - };\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ - GTestExpectFatalFailureHelper::Execute();\ - }\ - } while (::testing::internal::AlwaysFalse()) - -#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ - do { \ - class GTestExpectFatalFailureHelper {\ - public:\ - static void Execute() { statement; }\ - };\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ALL_THREADS, >est_failures);\ - GTestExpectFatalFailureHelper::Execute();\ - }\ - } while (::testing::internal::AlwaysFalse()) - -// A macro for testing Google Test assertions or code that's expected to -// generate Google Test non-fatal failures. It asserts that the given -// statement will cause exactly one non-fatal Google Test failure with 'substr' -// being part of the failure message. -// -// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only -// affects and considers failures generated in the current thread and -// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. -// -// 'statement' is allowed to reference local variables and members of -// the current object. -// -// The verification of the assertion is done correctly even when the statement -// throws an exception or aborts the current function. -// -// Known restrictions: -// - You cannot stream a failure message to this macro. -// -// Note that even though the implementations of the following two -// macros are much alike, we cannot refactor them to use a common -// helper macro, due to some peculiarity in how the preprocessor -// works. If we do that, the code won't compile when the user gives -// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that -// expands to code containing an unprotected comma. The -// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc -// catches that. -// -// For the same reason, we have to write -// if (::testing::internal::AlwaysTrue()) { statement; } -// instead of -// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) -// to avoid an MSVC warning on unreachable code. -#define EXPECT_NONFATAL_FAILURE(statement, substr) \ - do {\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ - (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ - if (::testing::internal::AlwaysTrue()) { statement; }\ - }\ - } while (::testing::internal::AlwaysFalse()) - -#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ - do {\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ - (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS,\ - >est_failures);\ - if (::testing::internal::AlwaysTrue()) { statement; }\ - }\ - } while (::testing::internal::AlwaysFalse()) - -#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_ - -#include -#include -#include -#include -#include -#include -#include - -#include -#include // NOLINT -#include -#include - -#if GTEST_OS_LINUX - -// TODO(kenton@google.com): Use autoconf to detect availability of -// gettimeofday(). -# define GTEST_HAS_GETTIMEOFDAY_ 1 - -# include // NOLINT -# include // NOLINT -# include // NOLINT -// Declares vsnprintf(). This header is not available on Windows. -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include - -#elif GTEST_OS_SYMBIAN -# define GTEST_HAS_GETTIMEOFDAY_ 1 -# include // NOLINT - -#elif GTEST_OS_ZOS -# define GTEST_HAS_GETTIMEOFDAY_ 1 -# include // NOLINT - -// On z/OS we additionally need strings.h for strcasecmp. -# include // NOLINT - -#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. - -# include // NOLINT - -#elif GTEST_OS_WINDOWS // We are on Windows proper. - -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include // NOLINT - -# if GTEST_OS_WINDOWS_MINGW -// MinGW has gettimeofday() but not _ftime64(). -// TODO(kenton@google.com): Use autoconf to detect availability of -// gettimeofday(). -// TODO(kenton@google.com): There are other ways to get the time on -// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW -// supports these. consider using them instead. -# define GTEST_HAS_GETTIMEOFDAY_ 1 -# include // NOLINT -# endif // GTEST_OS_WINDOWS_MINGW - -// cpplint thinks that the header is already included, so we want to -// silence it. -# include // NOLINT - -#else - -// Assume other platforms have gettimeofday(). -// TODO(kenton@google.com): Use autoconf to detect availability of -// gettimeofday(). -# define GTEST_HAS_GETTIMEOFDAY_ 1 - -// cpplint thinks that the header is already included, so we want to -// silence it. -# include // NOLINT -# include // NOLINT - -#endif // GTEST_OS_LINUX - -#if GTEST_HAS_EXCEPTIONS -# include -#endif - -#if GTEST_CAN_STREAM_RESULTS_ -# include // NOLINT -# include // NOLINT -#endif - -// Indicates that this translation unit is part of Google Test's -// implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. -#define GTEST_IMPLEMENTATION_ 1 -// Copyright 2005, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. - -// Utility functions and classes used by the Google C++ testing framework. -// -// Author: wan@google.com (Zhanyong Wan) -// -// This file contains purely Google Test's internal implementation. Please -// DO NOT #INCLUDE IT IN A USER PROGRAM. - -#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ -#define GTEST_SRC_GTEST_INTERNAL_INL_H_ - -// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is -// part of Google Test's implementation; otherwise it's undefined. -#if !GTEST_IMPLEMENTATION_ -// A user is trying to include this from his code - just say no. -# error "gtest-internal-inl.h is part of Google Test's internal implementation." -# error "It must not be included except by Google Test itself." -#endif // GTEST_IMPLEMENTATION_ - -#ifndef _WIN32_WCE -# include -#endif // !_WIN32_WCE -#include -#include // For strtoll/_strtoul64/malloc/free. -#include // For memmove. - -#include -#include -#include - - -#if GTEST_OS_WINDOWS -# include // NOLINT -#endif // GTEST_OS_WINDOWS - - -namespace testing { - -// Declares the flags. -// -// We don't want the users to modify this flag in the code, but want -// Google Test's own unit tests to be able to access it. Therefore we -// declare it here as opposed to in gtest.h. -GTEST_DECLARE_bool_(death_test_use_fork); - -namespace internal { - -// The value of GetTestTypeId() as seen from within the Google Test -// library. This is solely for testing GetTestTypeId(). -GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; - -// Names of the flags (needed for parsing Google Test flags). -const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; -const char kBreakOnFailureFlag[] = "break_on_failure"; -const char kCatchExceptionsFlag[] = "catch_exceptions"; -const char kColorFlag[] = "color"; -const char kFilterFlag[] = "filter"; -const char kListTestsFlag[] = "list_tests"; -const char kOutputFlag[] = "output"; -const char kPrintTimeFlag[] = "print_time"; -const char kRandomSeedFlag[] = "random_seed"; -const char kRepeatFlag[] = "repeat"; -const char kShuffleFlag[] = "shuffle"; -const char kStackTraceDepthFlag[] = "stack_trace_depth"; -const char kStreamResultToFlag[] = "stream_result_to"; -const char kThrowOnFailureFlag[] = "throw_on_failure"; - -// A valid random seed must be in [1, kMaxRandomSeed]. -const int kMaxRandomSeed = 99999; - -// g_help_flag is true iff the --help flag or an equivalent form is -// specified on the command line. -GTEST_API_ extern bool g_help_flag; - -// Returns the current time in milliseconds. -GTEST_API_ TimeInMillis GetTimeInMillis(); - -// Returns true iff Google Test should use colors in the output. -GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); - -// Formats the given time in milliseconds as seconds. -GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); - -// Parses a string for an Int32 flag, in the form of "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -GTEST_API_ bool ParseInt32Flag( - const char* str, const char* flag, Int32* value); - -// Returns a random seed in range [1, kMaxRandomSeed] based on the -// given --gtest_random_seed flag value. -inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { - const unsigned int raw_seed = (random_seed_flag == 0) ? - static_cast(GetTimeInMillis()) : - static_cast(random_seed_flag); - - // Normalizes the actual seed to range [1, kMaxRandomSeed] such that - // it's easy to type. - const int normalized_seed = - static_cast((raw_seed - 1U) % - static_cast(kMaxRandomSeed)) + 1; - return normalized_seed; -} - -// Returns the first valid random seed after 'seed'. The behavior is -// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is -// considered to be 1. -inline int GetNextRandomSeed(int seed) { - GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) - << "Invalid random seed " << seed << " - must be in [1, " - << kMaxRandomSeed << "]."; - const int next_seed = seed + 1; - return (next_seed > kMaxRandomSeed) ? 1 : next_seed; -} - -// This class saves the values of all Google Test flags in its c'tor, and -// restores them in its d'tor. -class GTestFlagSaver { - public: - // The c'tor. - GTestFlagSaver() { - also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); - break_on_failure_ = GTEST_FLAG(break_on_failure); - catch_exceptions_ = GTEST_FLAG(catch_exceptions); - color_ = GTEST_FLAG(color); - death_test_style_ = GTEST_FLAG(death_test_style); - death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); - filter_ = GTEST_FLAG(filter); - internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); - list_tests_ = GTEST_FLAG(list_tests); - output_ = GTEST_FLAG(output); - print_time_ = GTEST_FLAG(print_time); - random_seed_ = GTEST_FLAG(random_seed); - repeat_ = GTEST_FLAG(repeat); - shuffle_ = GTEST_FLAG(shuffle); - stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); - stream_result_to_ = GTEST_FLAG(stream_result_to); - throw_on_failure_ = GTEST_FLAG(throw_on_failure); - } - - // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. - ~GTestFlagSaver() { - GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; - GTEST_FLAG(break_on_failure) = break_on_failure_; - GTEST_FLAG(catch_exceptions) = catch_exceptions_; - GTEST_FLAG(color) = color_; - GTEST_FLAG(death_test_style) = death_test_style_; - GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; - GTEST_FLAG(filter) = filter_; - GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; - GTEST_FLAG(list_tests) = list_tests_; - GTEST_FLAG(output) = output_; - GTEST_FLAG(print_time) = print_time_; - GTEST_FLAG(random_seed) = random_seed_; - GTEST_FLAG(repeat) = repeat_; - GTEST_FLAG(shuffle) = shuffle_; - GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; - GTEST_FLAG(stream_result_to) = stream_result_to_; - GTEST_FLAG(throw_on_failure) = throw_on_failure_; - } - private: - // Fields for saving the original values of flags. - bool also_run_disabled_tests_; - bool break_on_failure_; - bool catch_exceptions_; - String color_; - String death_test_style_; - bool death_test_use_fork_; - String filter_; - String internal_run_death_test_; - bool list_tests_; - String output_; - bool print_time_; - bool pretty_; - internal::Int32 random_seed_; - internal::Int32 repeat_; - bool shuffle_; - internal::Int32 stack_trace_depth_; - String stream_result_to_; - bool throw_on_failure_; -} GTEST_ATTRIBUTE_UNUSED_; - -// Converts a Unicode code point to a narrow string in UTF-8 encoding. -// code_point parameter is of type UInt32 because wchar_t may not be -// wide enough to contain a code point. -// The output buffer str must containt at least 32 characters. -// The function returns the address of the output buffer. -// If the code_point is not a valid Unicode code point -// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output -// as '(Invalid Unicode 0xXXXXXXXX)'. -GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str); - -// Converts a wide string to a narrow string in UTF-8 encoding. -// The wide string is assumed to have the following encoding: -// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) -// UTF-32 if sizeof(wchar_t) == 4 (on Linux) -// Parameter str points to a null-terminated wide string. -// Parameter num_chars may additionally limit the number -// of wchar_t characters processed. -1 is used when the entire string -// should be processed. -// If the string contains code points that are not valid Unicode code points -// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output -// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding -// and contains invalid UTF-16 surrogate pairs, values in those pairs -// will be encoded as individual Unicode characters from Basic Normal Plane. -GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars); - -// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file -// if the variable is present. If a file already exists at this location, this -// function will write over it. If the variable is present, but the file cannot -// be created, prints an error and exits. -void WriteToShardStatusFileIfNeeded(); - -// Checks whether sharding is enabled by examining the relevant -// environment variable values. If the variables are present, -// but inconsistent (e.g., shard_index >= total_shards), prints -// an error and exits. If in_subprocess_for_death_test, sharding is -// disabled because it must only be applied to the original test -// process. Otherwise, we could filter out death tests we intended to execute. -GTEST_API_ bool ShouldShard(const char* total_shards_str, - const char* shard_index_str, - bool in_subprocess_for_death_test); - -// Parses the environment variable var as an Int32. If it is unset, -// returns default_val. If it is not an Int32, prints an error and -// and aborts. -GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); - -// Given the total number of shards, the shard index, and the test id, -// returns true iff the test should be run on this shard. The test id is -// some arbitrary but unique non-negative integer assigned to each test -// method. Assumes that 0 <= shard_index < total_shards. -GTEST_API_ bool ShouldRunTestOnShard( - int total_shards, int shard_index, int test_id); - -// STL container utilities. - -// Returns the number of elements in the given container that satisfy -// the given predicate. -template -inline int CountIf(const Container& c, Predicate predicate) { - // Implemented as an explicit loop since std::count_if() in libCstd on - // Solaris has a non-standard signature. - int count = 0; - for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { - if (predicate(*it)) - ++count; - } - return count; -} - -// Applies a function/functor to each element in the container. -template -void ForEach(const Container& c, Functor functor) { - std::for_each(c.begin(), c.end(), functor); -} - -// Returns the i-th element of the vector, or default_value if i is not -// in range [0, v.size()). -template -inline E GetElementOr(const std::vector& v, int i, E default_value) { - return (i < 0 || i >= static_cast(v.size())) ? default_value : v[i]; -} - -// Performs an in-place shuffle of a range of the vector's elements. -// 'begin' and 'end' are element indices as an STL-style range; -// i.e. [begin, end) are shuffled, where 'end' == size() means to -// shuffle to the end of the vector. -template -void ShuffleRange(internal::Random* random, int begin, int end, - std::vector* v) { - const int size = static_cast(v->size()); - GTEST_CHECK_(0 <= begin && begin <= size) - << "Invalid shuffle range start " << begin << ": must be in range [0, " - << size << "]."; - GTEST_CHECK_(begin <= end && end <= size) - << "Invalid shuffle range finish " << end << ": must be in range [" - << begin << ", " << size << "]."; - - // Fisher-Yates shuffle, from - // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle - for (int range_width = end - begin; range_width >= 2; range_width--) { - const int last_in_range = begin + range_width - 1; - const int selected = begin + random->Generate(range_width); - std::swap((*v)[selected], (*v)[last_in_range]); - } -} - -// Performs an in-place shuffle of the vector's elements. -template -inline void Shuffle(internal::Random* random, std::vector* v) { - ShuffleRange(random, 0, static_cast(v->size()), v); -} - -// A function for deleting an object. Handy for being used as a -// functor. -template -static void Delete(T* x) { - delete x; -} - -// A predicate that checks the key of a TestProperty against a known key. -// -// TestPropertyKeyIs is copyable. -class TestPropertyKeyIs { - public: - // Constructor. - // - // TestPropertyKeyIs has NO default constructor. - explicit TestPropertyKeyIs(const char* key) - : key_(key) {} - - // Returns true iff the test name of test property matches on key_. - bool operator()(const TestProperty& test_property) const { - return String(test_property.key()).Compare(key_) == 0; - } - - private: - String key_; -}; - -// Class UnitTestOptions. -// -// This class contains functions for processing options the user -// specifies when running the tests. It has only static members. -// -// In most cases, the user can specify an option using either an -// environment variable or a command line flag. E.g. you can set the -// test filter using either GTEST_FILTER or --gtest_filter. If both -// the variable and the flag are present, the latter overrides the -// former. -class GTEST_API_ UnitTestOptions { - public: - // Functions for processing the gtest_output flag. - - // Returns the output format, or "" for normal printed output. - static String GetOutputFormat(); - - // Returns the absolute path of the requested output file, or the - // default (test_detail.xml in the original working directory) if - // none was explicitly specified. - static String GetAbsolutePathToOutputFile(); - - // Functions for processing the gtest_filter flag. - - // Returns true iff the wildcard pattern matches the string. The - // first ':' or '\0' character in pattern marks the end of it. - // - // This recursive algorithm isn't very efficient, but is clear and - // works well enough for matching test names, which are short. - static bool PatternMatchesString(const char *pattern, const char *str); - - // Returns true iff the user-specified filter matches the test case - // name and the test name. - static bool FilterMatchesTest(const String &test_case_name, - const String &test_name); - -#if GTEST_OS_WINDOWS - // Function for supporting the gtest_catch_exception flag. - - // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the - // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. - // This function is useful as an __except condition. - static int GTestShouldProcessSEH(DWORD exception_code); -#endif // GTEST_OS_WINDOWS - - // Returns true if "name" matches the ':' separated list of glob-style - // filters in "filter". - static bool MatchesFilter(const String& name, const char* filter); -}; - -// Returns the current application's name, removing directory path if that -// is present. Used by UnitTestOptions::GetOutputFile. -GTEST_API_ FilePath GetCurrentExecutableName(); - -// The role interface for getting the OS stack trace as a string. -class OsStackTraceGetterInterface { - public: - OsStackTraceGetterInterface() {} - virtual ~OsStackTraceGetterInterface() {} - - // Returns the current OS stack trace as a String. Parameters: - // - // max_depth - the maximum number of stack frames to be included - // in the trace. - // skip_count - the number of top frames to be skipped; doesn't count - // against max_depth. - virtual String CurrentStackTrace(int max_depth, int skip_count) = 0; - - // UponLeavingGTest() should be called immediately before Google Test calls - // user code. It saves some information about the current stack that - // CurrentStackTrace() will use to find and hide Google Test stack frames. - virtual void UponLeavingGTest() = 0; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); -}; - -// A working implementation of the OsStackTraceGetterInterface interface. -class OsStackTraceGetter : public OsStackTraceGetterInterface { - public: - OsStackTraceGetter() : caller_frame_(NULL) {} - virtual String CurrentStackTrace(int max_depth, int skip_count); - virtual void UponLeavingGTest(); - - // This string is inserted in place of stack frames that are part of - // Google Test's implementation. - static const char* const kElidedFramesMarker; - - private: - Mutex mutex_; // protects all internal state - - // We save the stack frame below the frame that calls user code. - // We do this because the address of the frame immediately below - // the user code changes between the call to UponLeavingGTest() - // and any calls to CurrentStackTrace() from within the user code. - void* caller_frame_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); -}; - -// Information about a Google Test trace point. -struct TraceInfo { - const char* file; - int line; - String message; -}; - -// This is the default global test part result reporter used in UnitTestImpl. -// This class should only be used by UnitTestImpl. -class DefaultGlobalTestPartResultReporter - : public TestPartResultReporterInterface { - public: - explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); - // Implements the TestPartResultReporterInterface. Reports the test part - // result in the current test. - virtual void ReportTestPartResult(const TestPartResult& result); - - private: - UnitTestImpl* const unit_test_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); -}; - -// This is the default per thread test part result reporter used in -// UnitTestImpl. This class should only be used by UnitTestImpl. -class DefaultPerThreadTestPartResultReporter - : public TestPartResultReporterInterface { - public: - explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); - // Implements the TestPartResultReporterInterface. The implementation just - // delegates to the current global test part result reporter of *unit_test_. - virtual void ReportTestPartResult(const TestPartResult& result); - - private: - UnitTestImpl* const unit_test_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); -}; - -// The private implementation of the UnitTest class. We don't protect -// the methods under a mutex, as this class is not accessible by a -// user and the UnitTest class that delegates work to this class does -// proper locking. -class GTEST_API_ UnitTestImpl { - public: - explicit UnitTestImpl(UnitTest* parent); - virtual ~UnitTestImpl(); - - // There are two different ways to register your own TestPartResultReporter. - // You can register your own repoter to listen either only for test results - // from the current thread or for results from all threads. - // By default, each per-thread test result repoter just passes a new - // TestPartResult to the global test result reporter, which registers the - // test part result for the currently running test. - - // Returns the global test part result reporter. - TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); - - // Sets the global test part result reporter. - void SetGlobalTestPartResultReporter( - TestPartResultReporterInterface* reporter); - - // Returns the test part result reporter for the current thread. - TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); - - // Sets the test part result reporter for the current thread. - void SetTestPartResultReporterForCurrentThread( - TestPartResultReporterInterface* reporter); - - // Gets the number of successful test cases. - int successful_test_case_count() const; - - // Gets the number of failed test cases. - int failed_test_case_count() const; - - // Gets the number of all test cases. - int total_test_case_count() const; - - // Gets the number of all test cases that contain at least one test - // that should run. - int test_case_to_run_count() const; - - // Gets the number of successful tests. - int successful_test_count() const; - - // Gets the number of failed tests. - int failed_test_count() const; - - // Gets the number of disabled tests. - int disabled_test_count() const; - - // Gets the number of all tests. - int total_test_count() const; - - // Gets the number of tests that should run. - int test_to_run_count() const; - - // Gets the elapsed time, in milliseconds. - TimeInMillis elapsed_time() const { return elapsed_time_; } - - // Returns true iff the unit test passed (i.e. all test cases passed). - bool Passed() const { return !Failed(); } - - // Returns true iff the unit test failed (i.e. some test case failed - // or something outside of all tests failed). - bool Failed() const { - return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); - } - - // Gets the i-th test case among all the test cases. i can range from 0 to - // total_test_case_count() - 1. If i is not in that range, returns NULL. - const TestCase* GetTestCase(int i) const { - const int index = GetElementOr(test_case_indices_, i, -1); - return index < 0 ? NULL : test_cases_[i]; - } - - // Gets the i-th test case among all the test cases. i can range from 0 to - // total_test_case_count() - 1. If i is not in that range, returns NULL. - TestCase* GetMutableTestCase(int i) { - const int index = GetElementOr(test_case_indices_, i, -1); - return index < 0 ? NULL : test_cases_[index]; - } - - // Provides access to the event listener list. - TestEventListeners* listeners() { return &listeners_; } - - // Returns the TestResult for the test that's currently running, or - // the TestResult for the ad hoc test if no test is running. - TestResult* current_test_result(); - - // Returns the TestResult for the ad hoc test. - const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } - - // Sets the OS stack trace getter. - // - // Does nothing if the input and the current OS stack trace getter - // are the same; otherwise, deletes the old getter and makes the - // input the current getter. - void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); - - // Returns the current OS stack trace getter if it is not NULL; - // otherwise, creates an OsStackTraceGetter, makes it the current - // getter, and returns it. - OsStackTraceGetterInterface* os_stack_trace_getter(); - - // Returns the current OS stack trace as a String. - // - // The maximum number of stack frames to be included is specified by - // the gtest_stack_trace_depth flag. The skip_count parameter - // specifies the number of top frames to be skipped, which doesn't - // count against the number of frames to be included. - // - // For example, if Foo() calls Bar(), which in turn calls - // CurrentOsStackTraceExceptTop(1), Foo() will be included in the - // trace but Bar() and CurrentOsStackTraceExceptTop() won't. - String CurrentOsStackTraceExceptTop(int skip_count); - - // Finds and returns a TestCase with the given name. If one doesn't - // exist, creates one and returns it. - // - // Arguments: - // - // test_case_name: name of the test case - // type_param: the name of the test's type parameter, or NULL if - // this is not a typed or a type-parameterized test. - // set_up_tc: pointer to the function that sets up the test case - // tear_down_tc: pointer to the function that tears down the test case - TestCase* GetTestCase(const char* test_case_name, - const char* type_param, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc); - - // Adds a TestInfo to the unit test. - // - // Arguments: - // - // set_up_tc: pointer to the function that sets up the test case - // tear_down_tc: pointer to the function that tears down the test case - // test_info: the TestInfo object - void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc, - TestInfo* test_info) { - // In order to support thread-safe death tests, we need to - // remember the original working directory when the test program - // was first invoked. We cannot do this in RUN_ALL_TESTS(), as - // the user may have changed the current directory before calling - // RUN_ALL_TESTS(). Therefore we capture the current directory in - // AddTestInfo(), which is called to register a TEST or TEST_F - // before main() is reached. - if (original_working_dir_.IsEmpty()) { - original_working_dir_.Set(FilePath::GetCurrentDir()); - GTEST_CHECK_(!original_working_dir_.IsEmpty()) - << "Failed to get the current working directory."; - } - - GetTestCase(test_info->test_case_name(), - test_info->type_param(), - set_up_tc, - tear_down_tc)->AddTestInfo(test_info); - } - -#if GTEST_HAS_PARAM_TEST - // Returns ParameterizedTestCaseRegistry object used to keep track of - // value-parameterized tests and instantiate and register them. - internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { - return parameterized_test_registry_; - } -#endif // GTEST_HAS_PARAM_TEST - - // Sets the TestCase object for the test that's currently running. - void set_current_test_case(TestCase* a_current_test_case) { - current_test_case_ = a_current_test_case; - } - - // Sets the TestInfo object for the test that's currently running. If - // current_test_info is NULL, the assertion results will be stored in - // ad_hoc_test_result_. - void set_current_test_info(TestInfo* a_current_test_info) { - current_test_info_ = a_current_test_info; - } - - // Registers all parameterized tests defined using TEST_P and - // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter - // combination. This method can be called more then once; it has guards - // protecting from registering the tests more then once. If - // value-parameterized tests are disabled, RegisterParameterizedTests is - // present but does nothing. - void RegisterParameterizedTests(); - - // Runs all tests in this UnitTest object, prints the result, and - // returns true if all tests are successful. If any exception is - // thrown during a test, this test is considered to be failed, but - // the rest of the tests will still be run. - bool RunAllTests(); - - // Clears the results of all tests, except the ad hoc tests. - void ClearNonAdHocTestResult() { - ForEach(test_cases_, TestCase::ClearTestCaseResult); - } - - // Clears the results of ad-hoc test assertions. - void ClearAdHocTestResult() { - ad_hoc_test_result_.Clear(); - } - - enum ReactionToSharding { - HONOR_SHARDING_PROTOCOL, - IGNORE_SHARDING_PROTOCOL - }; - - // Matches the full name of each test against the user-specified - // filter to decide whether the test should run, then records the - // result in each TestCase and TestInfo object. - // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests - // based on sharding variables in the environment. - // Returns the number of tests that should run. - int FilterTests(ReactionToSharding shard_tests); - - // Prints the names of the tests matching the user-specified filter flag. - void ListTestsMatchingFilter(); - - const TestCase* current_test_case() const { return current_test_case_; } - TestInfo* current_test_info() { return current_test_info_; } - const TestInfo* current_test_info() const { return current_test_info_; } - - // Returns the vector of environments that need to be set-up/torn-down - // before/after the tests are run. - std::vector& environments() { return environments_; } - - // Getters for the per-thread Google Test trace stack. - std::vector& gtest_trace_stack() { - return *(gtest_trace_stack_.pointer()); - } - const std::vector& gtest_trace_stack() const { - return gtest_trace_stack_.get(); - } - -#if GTEST_HAS_DEATH_TEST - void InitDeathTestSubprocessControlInfo() { - internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); - } - // Returns a pointer to the parsed --gtest_internal_run_death_test - // flag, or NULL if that flag was not specified. - // This information is useful only in a death test child process. - // Must not be called before a call to InitGoogleTest. - const InternalRunDeathTestFlag* internal_run_death_test_flag() const { - return internal_run_death_test_flag_.get(); - } - - // Returns a pointer to the current death test factory. - internal::DeathTestFactory* death_test_factory() { - return death_test_factory_.get(); - } - - void SuppressTestEventsIfInSubprocess(); - - friend class ReplaceDeathTestFactory; -#endif // GTEST_HAS_DEATH_TEST - - // Initializes the event listener performing XML output as specified by - // UnitTestOptions. Must not be called before InitGoogleTest. - void ConfigureXmlOutput(); - -#if GTEST_CAN_STREAM_RESULTS_ - // Initializes the event listener for streaming test results to a socket. - // Must not be called before InitGoogleTest. - void ConfigureStreamingOutput(); -#endif - - // Performs initialization dependent upon flag values obtained in - // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to - // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest - // this function is also called from RunAllTests. Since this function can be - // called more than once, it has to be idempotent. - void PostFlagParsingInit(); - - // Gets the random seed used at the start of the current test iteration. - int random_seed() const { return random_seed_; } - - // Gets the random number generator. - internal::Random* random() { return &random_; } - - // Shuffles all test cases, and the tests within each test case, - // making sure that death tests are still run first. - void ShuffleTests(); - - // Restores the test cases and tests to their order before the first shuffle. - void UnshuffleTests(); - - // Returns the value of GTEST_FLAG(catch_exceptions) at the moment - // UnitTest::Run() starts. - bool catch_exceptions() const { return catch_exceptions_; } - - private: - friend class ::testing::UnitTest; - - // Used by UnitTest::Run() to capture the state of - // GTEST_FLAG(catch_exceptions) at the moment it starts. - void set_catch_exceptions(bool value) { catch_exceptions_ = value; } - - // The UnitTest object that owns this implementation object. - UnitTest* const parent_; - - // The working directory when the first TEST() or TEST_F() was - // executed. - internal::FilePath original_working_dir_; - - // The default test part result reporters. - DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; - DefaultPerThreadTestPartResultReporter - default_per_thread_test_part_result_reporter_; - - // Points to (but doesn't own) the global test part result reporter. - TestPartResultReporterInterface* global_test_part_result_repoter_; - - // Protects read and write access to global_test_part_result_reporter_. - internal::Mutex global_test_part_result_reporter_mutex_; - - // Points to (but doesn't own) the per-thread test part result reporter. - internal::ThreadLocal - per_thread_test_part_result_reporter_; - - // The vector of environments that need to be set-up/torn-down - // before/after the tests are run. - std::vector environments_; - - // The vector of TestCases in their original order. It owns the - // elements in the vector. - std::vector test_cases_; - - // Provides a level of indirection for the test case list to allow - // easy shuffling and restoring the test case order. The i-th - // element of this vector is the index of the i-th test case in the - // shuffled order. - std::vector test_case_indices_; - -#if GTEST_HAS_PARAM_TEST - // ParameterizedTestRegistry object used to register value-parameterized - // tests. - internal::ParameterizedTestCaseRegistry parameterized_test_registry_; - - // Indicates whether RegisterParameterizedTests() has been called already. - bool parameterized_tests_registered_; -#endif // GTEST_HAS_PARAM_TEST - - // Index of the last death test case registered. Initially -1. - int last_death_test_case_; - - // This points to the TestCase for the currently running test. It - // changes as Google Test goes through one test case after another. - // When no test is running, this is set to NULL and Google Test - // stores assertion results in ad_hoc_test_result_. Initially NULL. - TestCase* current_test_case_; - - // This points to the TestInfo for the currently running test. It - // changes as Google Test goes through one test after another. When - // no test is running, this is set to NULL and Google Test stores - // assertion results in ad_hoc_test_result_. Initially NULL. - TestInfo* current_test_info_; - - // Normally, a user only writes assertions inside a TEST or TEST_F, - // or inside a function called by a TEST or TEST_F. Since Google - // Test keeps track of which test is current running, it can - // associate such an assertion with the test it belongs to. - // - // If an assertion is encountered when no TEST or TEST_F is running, - // Google Test attributes the assertion result to an imaginary "ad hoc" - // test, and records the result in ad_hoc_test_result_. - TestResult ad_hoc_test_result_; - - // The list of event listeners that can be used to track events inside - // Google Test. - TestEventListeners listeners_; - - // The OS stack trace getter. Will be deleted when the UnitTest - // object is destructed. By default, an OsStackTraceGetter is used, - // but the user can set this field to use a custom getter if that is - // desired. - OsStackTraceGetterInterface* os_stack_trace_getter_; - - // True iff PostFlagParsingInit() has been called. - bool post_flag_parse_init_performed_; - - // The random number seed used at the beginning of the test run. - int random_seed_; - - // Our random number generator. - internal::Random random_; - - // How long the test took to run, in milliseconds. - TimeInMillis elapsed_time_; - -#if GTEST_HAS_DEATH_TEST - // The decomposed components of the gtest_internal_run_death_test flag, - // parsed when RUN_ALL_TESTS is called. - internal::scoped_ptr internal_run_death_test_flag_; - internal::scoped_ptr death_test_factory_; -#endif // GTEST_HAS_DEATH_TEST - - // A per-thread stack of traces created by the SCOPED_TRACE() macro. - internal::ThreadLocal > gtest_trace_stack_; - - // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests() - // starts. - bool catch_exceptions_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); -}; // class UnitTestImpl - -// Convenience function for accessing the global UnitTest -// implementation object. -inline UnitTestImpl* GetUnitTestImpl() { - return UnitTest::GetInstance()->impl(); -} - -#if GTEST_USES_SIMPLE_RE - -// Internal helper functions for implementing the simple regular -// expression matcher. -GTEST_API_ bool IsInSet(char ch, const char* str); -GTEST_API_ bool IsAsciiDigit(char ch); -GTEST_API_ bool IsAsciiPunct(char ch); -GTEST_API_ bool IsRepeat(char ch); -GTEST_API_ bool IsAsciiWhiteSpace(char ch); -GTEST_API_ bool IsAsciiWordChar(char ch); -GTEST_API_ bool IsValidEscape(char ch); -GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); -GTEST_API_ bool ValidateRegex(const char* regex); -GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); -GTEST_API_ bool MatchRepetitionAndRegexAtHead( - bool escaped, char ch, char repeat, const char* regex, const char* str); -GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); - -#endif // GTEST_USES_SIMPLE_RE - -// Parses the command line for Google Test flags, without initializing -// other parts of Google Test. -GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); -GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); - -#if GTEST_HAS_DEATH_TEST - -// Returns the message describing the last system error, regardless of the -// platform. -GTEST_API_ String GetLastErrnoDescription(); - -# if GTEST_OS_WINDOWS -// Provides leak-safe Windows kernel handle ownership. -class AutoHandle { - public: - AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} - explicit AutoHandle(HANDLE handle) : handle_(handle) {} - - ~AutoHandle() { Reset(); } - - HANDLE Get() const { return handle_; } - void Reset() { Reset(INVALID_HANDLE_VALUE); } - void Reset(HANDLE handle) { - if (handle != handle_) { - if (handle_ != INVALID_HANDLE_VALUE) - ::CloseHandle(handle_); - handle_ = handle; - } - } - - private: - HANDLE handle_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); -}; -# endif // GTEST_OS_WINDOWS - -// Attempts to parse a string into a positive integer pointed to by the -// number parameter. Returns true if that is possible. -// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use -// it here. -template -bool ParseNaturalNumber(const ::std::string& str, Integer* number) { - // Fail fast if the given string does not begin with a digit; - // this bypasses strtoXXX's "optional leading whitespace and plus - // or minus sign" semantics, which are undesirable here. - if (str.empty() || !IsDigit(str[0])) { - return false; - } - errno = 0; - - char* end; - // BiggestConvertible is the largest integer type that system-provided - // string-to-number conversion routines can return. - -# if GTEST_OS_WINDOWS && !defined(__GNUC__) - - // MSVC and C++ Builder define __int64 instead of the standard long long. - typedef unsigned __int64 BiggestConvertible; - const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); - -# else - - typedef unsigned long long BiggestConvertible; // NOLINT - const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); - -# endif // GTEST_OS_WINDOWS && !defined(__GNUC__) - - const bool parse_success = *end == '\0' && errno == 0; - - // TODO(vladl@google.com): Convert this to compile time assertion when it is - // available. - GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); - - const Integer result = static_cast(parsed); - if (parse_success && static_cast(result) == parsed) { - *number = result; - return true; - } - return false; -} -#endif // GTEST_HAS_DEATH_TEST - -// TestResult contains some private methods that should be hidden from -// Google Test user but are required for testing. This class allow our tests -// to access them. -// -// This class is supplied only for the purpose of testing Google Test's own -// constructs. Do not use it in user tests, either directly or indirectly. -class TestResultAccessor { - public: - static void RecordProperty(TestResult* test_result, - const TestProperty& property) { - test_result->RecordProperty(property); - } - - static void ClearTestPartResults(TestResult* test_result) { - test_result->ClearTestPartResults(); - } - - static const std::vector& test_part_results( - const TestResult& test_result) { - return test_result.test_part_results(); - } -}; - -} // namespace internal -} // namespace testing - -#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ -#undef GTEST_IMPLEMENTATION_ - -#if GTEST_OS_WINDOWS -# define vsnprintf _vsnprintf -#endif // GTEST_OS_WINDOWS - -namespace testing { - -using internal::CountIf; -using internal::ForEach; -using internal::GetElementOr; -using internal::Shuffle; - -// Constants. - -// A test whose test case name or test name matches this filter is -// disabled and not run. -static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; - -// A test case whose name matches this filter is considered a death -// test case and will be run before test cases whose name doesn't -// match this filter. -static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*"; - -// A test filter that matches everything. -static const char kUniversalFilter[] = "*"; - -// The default output file for XML output. -static const char kDefaultOutputFile[] = "test_detail.xml"; - -// The environment variable name for the test shard index. -static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; -// The environment variable name for the total number of test shards. -static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; -// The environment variable name for the test shard status file. -static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; - -namespace internal { - -// The text used in failure messages to indicate the start of the -// stack trace. -const char kStackTraceMarker[] = "\nStack trace:\n"; - -// g_help_flag is true iff the --help flag or an equivalent form is -// specified on the command line. -bool g_help_flag = false; - -} // namespace internal - -GTEST_DEFINE_bool_( - also_run_disabled_tests, - internal::BoolFromGTestEnv("also_run_disabled_tests", false), - "Run disabled tests too, in addition to the tests normally being run."); - -GTEST_DEFINE_bool_( - break_on_failure, - internal::BoolFromGTestEnv("break_on_failure", false), - "True iff a failed assertion should be a debugger break-point."); - -GTEST_DEFINE_bool_( - catch_exceptions, - internal::BoolFromGTestEnv("catch_exceptions", true), - "True iff " GTEST_NAME_ - " should catch exceptions and treat them as test failures."); - -GTEST_DEFINE_string_( - color, - internal::StringFromGTestEnv("color", "auto"), - "Whether to use colors in the output. Valid values: yes, no, " - "and auto. 'auto' means to use colors if the output is " - "being sent to a terminal and the TERM environment variable " - "is set to xterm, xterm-color, xterm-256color, linux or cygwin."); - -GTEST_DEFINE_string_( - filter, - internal::StringFromGTestEnv("filter", kUniversalFilter), - "A colon-separated list of glob (not regex) patterns " - "for filtering the tests to run, optionally followed by a " - "'-' and a : separated list of negative patterns (tests to " - "exclude). A test is run if it matches one of the positive " - "patterns and does not match any of the negative patterns."); - -GTEST_DEFINE_bool_(list_tests, false, - "List all tests without running them."); - -GTEST_DEFINE_string_( - output, - internal::StringFromGTestEnv("output", ""), - "A format (currently must be \"xml\"), optionally followed " - "by a colon and an output file name or directory. A directory " - "is indicated by a trailing pathname separator. " - "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " - "If a directory is specified, output files will be created " - "within that directory, with file-names based on the test " - "executable's name and, if necessary, made unique by adding " - "digits."); - -GTEST_DEFINE_bool_( - print_time, - internal::BoolFromGTestEnv("print_time", true), - "True iff " GTEST_NAME_ - " should display elapsed time in text output."); - -GTEST_DEFINE_int32_( - random_seed, - internal::Int32FromGTestEnv("random_seed", 0), - "Random number seed to use when shuffling test orders. Must be in range " - "[1, 99999], or 0 to use a seed based on the current time."); - -GTEST_DEFINE_int32_( - repeat, - internal::Int32FromGTestEnv("repeat", 1), - "How many times to repeat each test. Specify a negative number " - "for repeating forever. Useful for shaking out flaky tests."); - -GTEST_DEFINE_bool_( - show_internal_stack_frames, false, - "True iff " GTEST_NAME_ " should include internal stack frames when " - "printing test failure stack traces."); - -GTEST_DEFINE_bool_( - shuffle, - internal::BoolFromGTestEnv("shuffle", false), - "True iff " GTEST_NAME_ - " should randomize tests' order on every run."); - -GTEST_DEFINE_int32_( - stack_trace_depth, - internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), - "The maximum number of stack frames to print when an " - "assertion fails. The valid range is 0 through 100, inclusive."); - -GTEST_DEFINE_string_( - stream_result_to, - internal::StringFromGTestEnv("stream_result_to", ""), - "This flag specifies the host name and the port number on which to stream " - "test results. Example: \"localhost:555\". The flag is effective only on " - "Linux."); - -GTEST_DEFINE_bool_( - throw_on_failure, - internal::BoolFromGTestEnv("throw_on_failure", false), - "When this flag is specified, a failed assertion will throw an exception " - "if exceptions are enabled or exit the program with a non-zero code " - "otherwise."); - -namespace internal { - -// Generates a random number from [0, range), using a Linear -// Congruential Generator (LCG). Crashes if 'range' is 0 or greater -// than kMaxRange. -UInt32 Random::Generate(UInt32 range) { - // These constants are the same as are used in glibc's rand(3). - state_ = (1103515245U*state_ + 12345U) % kMaxRange; - - GTEST_CHECK_(range > 0) - << "Cannot generate a number in the range [0, 0)."; - GTEST_CHECK_(range <= kMaxRange) - << "Generation of a number in [0, " << range << ") was requested, " - << "but this can only generate numbers in [0, " << kMaxRange << ")."; - - // Converting via modulus introduces a bit of downward bias, but - // it's simple, and a linear congruential generator isn't too good - // to begin with. - return state_ % range; -} - -// GTestIsInitialized() returns true iff the user has initialized -// Google Test. Useful for catching the user mistake of not initializing -// Google Test before calling RUN_ALL_TESTS(). -// -// A user must call testing::InitGoogleTest() to initialize Google -// Test. g_init_gtest_count is set to the number of times -// InitGoogleTest() has been called. We don't protect this variable -// under a mutex as it is only accessed in the main thread. -int g_init_gtest_count = 0; -static bool GTestIsInitialized() { return g_init_gtest_count != 0; } - -// Iterates over a vector of TestCases, keeping a running sum of the -// results of calling a given int-returning method on each. -// Returns the sum. -static int SumOverTestCaseList(const std::vector& case_list, - int (TestCase::*method)() const) { - int sum = 0; - for (size_t i = 0; i < case_list.size(); i++) { - sum += (case_list[i]->*method)(); - } - return sum; -} - -// Returns true iff the test case passed. -static bool TestCasePassed(const TestCase* test_case) { - return test_case->should_run() && test_case->Passed(); -} - -// Returns true iff the test case failed. -static bool TestCaseFailed(const TestCase* test_case) { - return test_case->should_run() && test_case->Failed(); -} - -// Returns true iff test_case contains at least one test that should -// run. -static bool ShouldRunTestCase(const TestCase* test_case) { - return test_case->should_run(); -} - -// AssertHelper constructor. -AssertHelper::AssertHelper(TestPartResult::Type type, - const char* file, - int line, - const char* message) - : data_(new AssertHelperData(type, file, line, message)) { -} - -AssertHelper::~AssertHelper() { - delete data_; -} - -// Message assignment, for assertion streaming support. -void AssertHelper::operator=(const Message& message) const { - UnitTest::GetInstance()-> - AddTestPartResult(data_->type, data_->file, data_->line, - AppendUserMessage(data_->message, message), - UnitTest::GetInstance()->impl() - ->CurrentOsStackTraceExceptTop(1) - // Skips the stack frame for this function itself. - ); // NOLINT -} - -// Mutex for linked pointers. -GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); - -// Application pathname gotten in InitGoogleTest. -String g_executable_path; - -// Returns the current application's name, removing directory path if that -// is present. -FilePath GetCurrentExecutableName() { - FilePath result; - -#if GTEST_OS_WINDOWS - result.Set(FilePath(g_executable_path).RemoveExtension("exe")); -#else - result.Set(FilePath(g_executable_path)); -#endif // GTEST_OS_WINDOWS - - return result.RemoveDirectoryName(); -} - -// Functions for processing the gtest_output flag. - -// Returns the output format, or "" for normal printed output. -String UnitTestOptions::GetOutputFormat() { - const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); - if (gtest_output_flag == NULL) return String(""); - - const char* const colon = strchr(gtest_output_flag, ':'); - return (colon == NULL) ? - String(gtest_output_flag) : - String(gtest_output_flag, colon - gtest_output_flag); -} - -// Returns the name of the requested output file, or the default if none -// was explicitly specified. -String UnitTestOptions::GetAbsolutePathToOutputFile() { - const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); - if (gtest_output_flag == NULL) - return String(""); - - const char* const colon = strchr(gtest_output_flag, ':'); - if (colon == NULL) - return String(internal::FilePath::ConcatPaths( - internal::FilePath( - UnitTest::GetInstance()->original_working_dir()), - internal::FilePath(kDefaultOutputFile)).ToString() ); - - internal::FilePath output_name(colon + 1); - if (!output_name.IsAbsolutePath()) - // TODO(wan@google.com): on Windows \some\path is not an absolute - // path (as its meaning depends on the current drive), yet the - // following logic for turning it into an absolute path is wrong. - // Fix it. - output_name = internal::FilePath::ConcatPaths( - internal::FilePath(UnitTest::GetInstance()->original_working_dir()), - internal::FilePath(colon + 1)); - - if (!output_name.IsDirectory()) - return output_name.ToString(); - - internal::FilePath result(internal::FilePath::GenerateUniqueFileName( - output_name, internal::GetCurrentExecutableName(), - GetOutputFormat().c_str())); - return result.ToString(); -} - -// Returns true iff the wildcard pattern matches the string. The -// first ':' or '\0' character in pattern marks the end of it. -// -// This recursive algorithm isn't very efficient, but is clear and -// works well enough for matching test names, which are short. -bool UnitTestOptions::PatternMatchesString(const char *pattern, - const char *str) { - switch (*pattern) { - case '\0': - case ':': // Either ':' or '\0' marks the end of the pattern. - return *str == '\0'; - case '?': // Matches any single character. - return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); - case '*': // Matches any string (possibly empty) of characters. - return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || - PatternMatchesString(pattern + 1, str); - default: // Non-special character. Matches itself. - return *pattern == *str && - PatternMatchesString(pattern + 1, str + 1); - } -} - -bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) { - const char *cur_pattern = filter; - for (;;) { - if (PatternMatchesString(cur_pattern, name.c_str())) { - return true; - } - - // Finds the next pattern in the filter. - cur_pattern = strchr(cur_pattern, ':'); - - // Returns if no more pattern can be found. - if (cur_pattern == NULL) { - return false; - } - - // Skips the pattern separater (the ':' character). - cur_pattern++; - } -} - -// TODO(keithray): move String function implementations to gtest-string.cc. - -// Returns true iff the user-specified filter matches the test case -// name and the test name. -bool UnitTestOptions::FilterMatchesTest(const String &test_case_name, - const String &test_name) { - const String& full_name = String::Format("%s.%s", - test_case_name.c_str(), - test_name.c_str()); - - // Split --gtest_filter at '-', if there is one, to separate into - // positive filter and negative filter portions - const char* const p = GTEST_FLAG(filter).c_str(); - const char* const dash = strchr(p, '-'); - String positive; - String negative; - if (dash == NULL) { - positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter - negative = String(""); - } else { - positive = String(p, dash - p); // Everything up to the dash - negative = String(dash+1); // Everything after the dash - if (positive.empty()) { - // Treat '-test1' as the same as '*-test1' - positive = kUniversalFilter; - } - } - - // A filter is a colon-separated list of patterns. It matches a - // test if any pattern in it matches the test. - return (MatchesFilter(full_name, positive.c_str()) && - !MatchesFilter(full_name, negative.c_str())); -} - -#if GTEST_HAS_SEH -// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the -// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. -// This function is useful as an __except condition. -int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { - // Google Test should handle a SEH exception if: - // 1. the user wants it to, AND - // 2. this is not a breakpoint exception, AND - // 3. this is not a C++ exception (VC++ implements them via SEH, - // apparently). - // - // SEH exception code for C++ exceptions. - // (see http://support.microsoft.com/kb/185294 for more information). - const DWORD kCxxExceptionCode = 0xe06d7363; - - bool should_handle = true; - - if (!GTEST_FLAG(catch_exceptions)) - should_handle = false; - else if (exception_code == EXCEPTION_BREAKPOINT) - should_handle = false; - else if (exception_code == kCxxExceptionCode) - should_handle = false; - - return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; -} -#endif // GTEST_HAS_SEH - -} // namespace internal - -// The c'tor sets this object as the test part result reporter used by -// Google Test. The 'result' parameter specifies where to report the -// results. Intercepts only failures from the current thread. -ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( - TestPartResultArray* result) - : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), - result_(result) { - Init(); -} - -// The c'tor sets this object as the test part result reporter used by -// Google Test. The 'result' parameter specifies where to report the -// results. -ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( - InterceptMode intercept_mode, TestPartResultArray* result) - : intercept_mode_(intercept_mode), - result_(result) { - Init(); -} - -void ScopedFakeTestPartResultReporter::Init() { - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - if (intercept_mode_ == INTERCEPT_ALL_THREADS) { - old_reporter_ = impl->GetGlobalTestPartResultReporter(); - impl->SetGlobalTestPartResultReporter(this); - } else { - old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); - impl->SetTestPartResultReporterForCurrentThread(this); - } -} - -// The d'tor restores the test part result reporter used by Google Test -// before. -ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - if (intercept_mode_ == INTERCEPT_ALL_THREADS) { - impl->SetGlobalTestPartResultReporter(old_reporter_); - } else { - impl->SetTestPartResultReporterForCurrentThread(old_reporter_); - } -} - -// Increments the test part result count and remembers the result. -// This method is from the TestPartResultReporterInterface interface. -void ScopedFakeTestPartResultReporter::ReportTestPartResult( - const TestPartResult& result) { - result_->Append(result); -} - -namespace internal { - -// Returns the type ID of ::testing::Test. We should always call this -// instead of GetTypeId< ::testing::Test>() to get the type ID of -// testing::Test. This is to work around a suspected linker bug when -// using Google Test as a framework on Mac OS X. The bug causes -// GetTypeId< ::testing::Test>() to return different values depending -// on whether the call is from the Google Test framework itself or -// from user test code. GetTestTypeId() is guaranteed to always -// return the same value, as it always calls GetTypeId<>() from the -// gtest.cc, which is within the Google Test framework. -TypeId GetTestTypeId() { - return GetTypeId(); -} - -// The value of GetTestTypeId() as seen from within the Google Test -// library. This is solely for testing GetTestTypeId(). -extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); - -// This predicate-formatter checks that 'results' contains a test part -// failure of the given type and that the failure message contains the -// given substring. -AssertionResult HasOneFailure(const char* /* results_expr */, - const char* /* type_expr */, - const char* /* substr_expr */, - const TestPartResultArray& results, - TestPartResult::Type type, - const string& substr) { - const String expected(type == TestPartResult::kFatalFailure ? - "1 fatal failure" : - "1 non-fatal failure"); - Message msg; - if (results.size() != 1) { - msg << "Expected: " << expected << "\n" - << " Actual: " << results.size() << " failures"; - for (int i = 0; i < results.size(); i++) { - msg << "\n" << results.GetTestPartResult(i); - } - return AssertionFailure() << msg; - } - - const TestPartResult& r = results.GetTestPartResult(0); - if (r.type() != type) { - return AssertionFailure() << "Expected: " << expected << "\n" - << " Actual:\n" - << r; - } - - if (strstr(r.message(), substr.c_str()) == NULL) { - return AssertionFailure() << "Expected: " << expected << " containing \"" - << substr << "\"\n" - << " Actual:\n" - << r; - } - - return AssertionSuccess(); -} - -// The constructor of SingleFailureChecker remembers where to look up -// test part results, what type of failure we expect, and what -// substring the failure message should contain. -SingleFailureChecker:: SingleFailureChecker( - const TestPartResultArray* results, - TestPartResult::Type type, - const string& substr) - : results_(results), - type_(type), - substr_(substr) {} - -// The destructor of SingleFailureChecker verifies that the given -// TestPartResultArray contains exactly one failure that has the given -// type and contains the given substring. If that's not the case, a -// non-fatal failure will be generated. -SingleFailureChecker::~SingleFailureChecker() { - EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); -} - -DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( - UnitTestImpl* unit_test) : unit_test_(unit_test) {} - -void DefaultGlobalTestPartResultReporter::ReportTestPartResult( - const TestPartResult& result) { - unit_test_->current_test_result()->AddTestPartResult(result); - unit_test_->listeners()->repeater()->OnTestPartResult(result); -} - -DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( - UnitTestImpl* unit_test) : unit_test_(unit_test) {} - -void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( - const TestPartResult& result) { - unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); -} - -// Returns the global test part result reporter. -TestPartResultReporterInterface* -UnitTestImpl::GetGlobalTestPartResultReporter() { - internal::MutexLock lock(&global_test_part_result_reporter_mutex_); - return global_test_part_result_repoter_; -} - -// Sets the global test part result reporter. -void UnitTestImpl::SetGlobalTestPartResultReporter( - TestPartResultReporterInterface* reporter) { - internal::MutexLock lock(&global_test_part_result_reporter_mutex_); - global_test_part_result_repoter_ = reporter; -} - -// Returns the test part result reporter for the current thread. -TestPartResultReporterInterface* -UnitTestImpl::GetTestPartResultReporterForCurrentThread() { - return per_thread_test_part_result_reporter_.get(); -} - -// Sets the test part result reporter for the current thread. -void UnitTestImpl::SetTestPartResultReporterForCurrentThread( - TestPartResultReporterInterface* reporter) { - per_thread_test_part_result_reporter_.set(reporter); -} - -// Gets the number of successful test cases. -int UnitTestImpl::successful_test_case_count() const { - return CountIf(test_cases_, TestCasePassed); -} - -// Gets the number of failed test cases. -int UnitTestImpl::failed_test_case_count() const { - return CountIf(test_cases_, TestCaseFailed); -} - -// Gets the number of all test cases. -int UnitTestImpl::total_test_case_count() const { - return static_cast(test_cases_.size()); -} - -// Gets the number of all test cases that contain at least one test -// that should run. -int UnitTestImpl::test_case_to_run_count() const { - return CountIf(test_cases_, ShouldRunTestCase); -} - -// Gets the number of successful tests. -int UnitTestImpl::successful_test_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count); -} - -// Gets the number of failed tests. -int UnitTestImpl::failed_test_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); -} - -// Gets the number of disabled tests. -int UnitTestImpl::disabled_test_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count); -} - -// Gets the number of all tests. -int UnitTestImpl::total_test_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); -} - -// Gets the number of tests that should run. -int UnitTestImpl::test_to_run_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); -} - -// Returns the current OS stack trace as a String. -// -// The maximum number of stack frames to be included is specified by -// the gtest_stack_trace_depth flag. The skip_count parameter -// specifies the number of top frames to be skipped, which doesn't -// count against the number of frames to be included. -// -// For example, if Foo() calls Bar(), which in turn calls -// CurrentOsStackTraceExceptTop(1), Foo() will be included in the -// trace but Bar() and CurrentOsStackTraceExceptTop() won't. -String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { - (void)skip_count; - return String(""); -} - -// Returns the current time in milliseconds. -TimeInMillis GetTimeInMillis() { -#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) - // Difference between 1970-01-01 and 1601-01-01 in milliseconds. - // http://analogous.blogspot.com/2005/04/epoch.html - const TimeInMillis kJavaEpochToWinFileTimeDelta = - static_cast(116444736UL) * 100000UL; - const DWORD kTenthMicrosInMilliSecond = 10000; - - SYSTEMTIME now_systime; - FILETIME now_filetime; - ULARGE_INTEGER now_int64; - // TODO(kenton@google.com): Shouldn't this just use - // GetSystemTimeAsFileTime()? - GetSystemTime(&now_systime); - if (SystemTimeToFileTime(&now_systime, &now_filetime)) { - now_int64.LowPart = now_filetime.dwLowDateTime; - now_int64.HighPart = now_filetime.dwHighDateTime; - now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - - kJavaEpochToWinFileTimeDelta; - return now_int64.QuadPart; - } - return 0; -#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ - __timeb64 now; - -# ifdef _MSC_VER - - // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 - // (deprecated function) there. - // TODO(kenton@google.com): Use GetTickCount()? Or use - // SystemTimeToFileTime() -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4996) // Temporarily disables warning 4996. - _ftime64(&now); -# pragma warning(pop) // Restores the warning state. -# else - - _ftime64(&now); - -# endif // _MSC_VER - - return static_cast(now.time) * 1000 + now.millitm; -#elif GTEST_HAS_GETTIMEOFDAY_ - struct timeval now; - gettimeofday(&now, NULL); - return static_cast(now.tv_sec) * 1000 + now.tv_usec / 1000; -#else -# error "Don't know how to get the current time on your system." -#endif -} - -// Utilities - -// class String - -// Returns the input enclosed in double quotes if it's not NULL; -// otherwise returns "(null)". For example, "\"Hello\"" is returned -// for input "Hello". -// -// This is useful for printing a C string in the syntax of a literal. -// -// Known issue: escape sequences are not handled yet. -String String::ShowCStringQuoted(const char* c_str) { - return c_str ? String::Format("\"%s\"", c_str) : String("(null)"); -} - -// Copies at most length characters from str into a newly-allocated -// piece of memory of size length+1. The memory is allocated with new[]. -// A terminating null byte is written to the memory, and a pointer to it -// is returned. If str is NULL, NULL is returned. -static char* CloneString(const char* str, size_t length) { - if (str == NULL) { - return NULL; - } else { - char* const clone = new char[length + 1]; - posix::StrNCpy(clone, str, length); - clone[length] = '\0'; - return clone; - } -} - -// Clones a 0-terminated C string, allocating memory using new. The -// caller is responsible for deleting[] the return value. Returns the -// cloned string, or NULL if the input is NULL. -const char * String::CloneCString(const char* c_str) { - return (c_str == NULL) ? - NULL : CloneString(c_str, strlen(c_str)); -} - -#if GTEST_OS_WINDOWS_MOBILE -// Creates a UTF-16 wide string from the given ANSI string, allocating -// memory using new. The caller is responsible for deleting the return -// value using delete[]. Returns the wide string, or NULL if the -// input is NULL. -LPCWSTR String::AnsiToUtf16(const char* ansi) { - if (!ansi) return NULL; - const int length = strlen(ansi); - const int unicode_length = - MultiByteToWideChar(CP_ACP, 0, ansi, length, - NULL, 0); - WCHAR* unicode = new WCHAR[unicode_length + 1]; - MultiByteToWideChar(CP_ACP, 0, ansi, length, - unicode, unicode_length); - unicode[unicode_length] = 0; - return unicode; -} - -// Creates an ANSI string from the given wide string, allocating -// memory using new. The caller is responsible for deleting the return -// value using delete[]. Returns the ANSI string, or NULL if the -// input is NULL. -const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { - if (!utf16_str) return NULL; - const int ansi_length = - WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, - NULL, 0, NULL, NULL); - char* ansi = new char[ansi_length + 1]; - WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, - ansi, ansi_length, NULL, NULL); - ansi[ansi_length] = 0; - return ansi; -} - -#endif // GTEST_OS_WINDOWS_MOBILE - -// Compares two C strings. Returns true iff they have the same content. -// -// Unlike strcmp(), this function can handle NULL argument(s). A NULL -// C string is considered different to any non-NULL C string, -// including the empty string. -bool String::CStringEquals(const char * lhs, const char * rhs) { - if ( lhs == NULL ) return rhs == NULL; - - if ( rhs == NULL ) return false; - - return strcmp(lhs, rhs) == 0; -} - -#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING - -// Converts an array of wide chars to a narrow string using the UTF-8 -// encoding, and streams the result to the given Message object. -static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, - Message* msg) { - // TODO(wan): consider allowing a testing::String object to - // contain '\0'. This will make it behave more like std::string, - // and will allow ToUtf8String() to return the correct encoding - // for '\0' s.t. we can get rid of the conditional here (and in - // several other places). - for (size_t i = 0; i != length; ) { // NOLINT - if (wstr[i] != L'\0') { - *msg << WideStringToUtf8(wstr + i, static_cast(length - i)); - while (i != length && wstr[i] != L'\0') - i++; - } else { - *msg << '\0'; - i++; - } - } -} - -#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING - -} // namespace internal - -#if GTEST_HAS_STD_WSTRING -// Converts the given wide string to a narrow string using the UTF-8 -// encoding, and streams the result to this Message object. -Message& Message::operator <<(const ::std::wstring& wstr) { - internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); - return *this; -} -#endif // GTEST_HAS_STD_WSTRING - -#if GTEST_HAS_GLOBAL_WSTRING -// Converts the given wide string to a narrow string using the UTF-8 -// encoding, and streams the result to this Message object. -Message& Message::operator <<(const ::wstring& wstr) { - internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); - return *this; -} -#endif // GTEST_HAS_GLOBAL_WSTRING - -// AssertionResult constructors. -// Used in EXPECT_TRUE/FALSE(assertion_result). -AssertionResult::AssertionResult(const AssertionResult& other) - : success_(other.success_), - message_(other.message_.get() != NULL ? - new ::std::string(*other.message_) : - static_cast< ::std::string*>(NULL)) { -} - -// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. -AssertionResult AssertionResult::operator!() const { - AssertionResult negation(!success_); - if (message_.get() != NULL) - negation << *message_; - return negation; -} - -// Makes a successful assertion result. -AssertionResult AssertionSuccess() { - return AssertionResult(true); -} - -// Makes a failed assertion result. -AssertionResult AssertionFailure() { - return AssertionResult(false); -} - -// Makes a failed assertion result with the given failure message. -// Deprecated; use AssertionFailure() << message. -AssertionResult AssertionFailure(const Message& message) { - return AssertionFailure() << message; -} - -namespace internal { - -// Constructs and returns the message for an equality assertion -// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. -// -// The first four parameters are the expressions used in the assertion -// and their values, as strings. For example, for ASSERT_EQ(foo, bar) -// where foo is 5 and bar is 6, we have: -// -// expected_expression: "foo" -// actual_expression: "bar" -// expected_value: "5" -// actual_value: "6" -// -// The ignoring_case parameter is true iff the assertion is a -// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will -// be inserted into the message. -AssertionResult EqFailure(const char* expected_expression, - const char* actual_expression, - const String& expected_value, - const String& actual_value, - bool ignoring_case) { - Message msg; - msg << "Value of: " << actual_expression; - if (actual_value != actual_expression) { - msg << "\n Actual: " << actual_value; - } - - msg << "\nExpected: " << expected_expression; - if (ignoring_case) { - msg << " (ignoring case)"; - } - if (expected_value != expected_expression) { - msg << "\nWhich is: " << expected_value; - } - - return AssertionFailure() << msg; -} - -// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. -String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result, - const char* expression_text, - const char* actual_predicate_value, - const char* expected_predicate_value) { - const char* actual_message = assertion_result.message(); - Message msg; - msg << "Value of: " << expression_text - << "\n Actual: " << actual_predicate_value; - if (actual_message[0] != '\0') - msg << " (" << actual_message << ")"; - msg << "\nExpected: " << expected_predicate_value; - return msg.GetString(); -} - -// Helper function for implementing ASSERT_NEAR. -AssertionResult DoubleNearPredFormat(const char* expr1, - const char* expr2, - const char* abs_error_expr, - double val1, - double val2, - double abs_error) { - const double diff = fabs(val1 - val2); - if (diff <= abs_error) return AssertionSuccess(); - - // TODO(wan): do not print the value of an expression if it's - // already a literal. - return AssertionFailure() - << "The difference between " << expr1 << " and " << expr2 - << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" - << expr1 << " evaluates to " << val1 << ",\n" - << expr2 << " evaluates to " << val2 << ", and\n" - << abs_error_expr << " evaluates to " << abs_error << "."; -} - - -// Helper template for implementing FloatLE() and DoubleLE(). -template -AssertionResult FloatingPointLE(const char* expr1, - const char* expr2, - RawType val1, - RawType val2) { - // Returns success if val1 is less than val2, - if (val1 < val2) { - return AssertionSuccess(); - } - - // or if val1 is almost equal to val2. - const FloatingPoint lhs(val1), rhs(val2); - if (lhs.AlmostEquals(rhs)) { - return AssertionSuccess(); - } - - // Note that the above two checks will both fail if either val1 or - // val2 is NaN, as the IEEE floating-point standard requires that - // any predicate involving a NaN must return false. - - ::std::stringstream val1_ss; - val1_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << val1; - - ::std::stringstream val2_ss; - val2_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << val2; - - return AssertionFailure() - << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" - << " Actual: " << StringStreamToString(&val1_ss) << " vs " - << StringStreamToString(&val2_ss); -} - -} // namespace internal - -// Asserts that val1 is less than, or almost equal to, val2. Fails -// otherwise. In particular, it fails if either val1 or val2 is NaN. -AssertionResult FloatLE(const char* expr1, const char* expr2, - float val1, float val2) { - return internal::FloatingPointLE(expr1, expr2, val1, val2); -} - -// Asserts that val1 is less than, or almost equal to, val2. Fails -// otherwise. In particular, it fails if either val1 or val2 is NaN. -AssertionResult DoubleLE(const char* expr1, const char* expr2, - double val1, double val2) { - return internal::FloatingPointLE(expr1, expr2, val1, val2); -} - -namespace internal { - -// The helper function for {ASSERT|EXPECT}_EQ with int or enum -// arguments. -AssertionResult CmpHelperEQ(const char* expected_expression, - const char* actual_expression, - BiggestInt expected, - BiggestInt actual) { - if (expected == actual) { - return AssertionSuccess(); - } - - return EqFailure(expected_expression, - actual_expression, - FormatForComparisonFailureMessage(expected, actual), - FormatForComparisonFailureMessage(actual, expected), - false); -} - -// A macro for implementing the helper functions needed to implement -// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here -// just to avoid copy-and-paste of similar code. -#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ -AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ - BiggestInt val1, BiggestInt val2) {\ - if (val1 op val2) {\ - return AssertionSuccess();\ - } else {\ - return AssertionFailure() \ - << "Expected: (" << expr1 << ") " #op " (" << expr2\ - << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ - << " vs " << FormatForComparisonFailureMessage(val2, val1);\ - }\ -} - -// Implements the helper function for {ASSERT|EXPECT}_NE with int or -// enum arguments. -GTEST_IMPL_CMP_HELPER_(NE, !=) -// Implements the helper function for {ASSERT|EXPECT}_LE with int or -// enum arguments. -GTEST_IMPL_CMP_HELPER_(LE, <=) -// Implements the helper function for {ASSERT|EXPECT}_LT with int or -// enum arguments. -GTEST_IMPL_CMP_HELPER_(LT, < ) -// Implements the helper function for {ASSERT|EXPECT}_GE with int or -// enum arguments. -GTEST_IMPL_CMP_HELPER_(GE, >=) -// Implements the helper function for {ASSERT|EXPECT}_GT with int or -// enum arguments. -GTEST_IMPL_CMP_HELPER_(GT, > ) - -#undef GTEST_IMPL_CMP_HELPER_ - -// The helper function for {ASSERT|EXPECT}_STREQ. -AssertionResult CmpHelperSTREQ(const char* expected_expression, - const char* actual_expression, - const char* expected, - const char* actual) { - if (String::CStringEquals(expected, actual)) { - return AssertionSuccess(); - } - - return EqFailure(expected_expression, - actual_expression, - String::ShowCStringQuoted(expected), - String::ShowCStringQuoted(actual), - false); -} - -// The helper function for {ASSERT|EXPECT}_STRCASEEQ. -AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, - const char* actual_expression, - const char* expected, - const char* actual) { - if (String::CaseInsensitiveCStringEquals(expected, actual)) { - return AssertionSuccess(); - } - - return EqFailure(expected_expression, - actual_expression, - String::ShowCStringQuoted(expected), - String::ShowCStringQuoted(actual), - true); -} - -// The helper function for {ASSERT|EXPECT}_STRNE. -AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2) { - if (!String::CStringEquals(s1, s2)) { - return AssertionSuccess(); - } else { - return AssertionFailure() << "Expected: (" << s1_expression << ") != (" - << s2_expression << "), actual: \"" - << s1 << "\" vs \"" << s2 << "\""; - } -} - -// The helper function for {ASSERT|EXPECT}_STRCASENE. -AssertionResult CmpHelperSTRCASENE(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2) { - if (!String::CaseInsensitiveCStringEquals(s1, s2)) { - return AssertionSuccess(); - } else { - return AssertionFailure() - << "Expected: (" << s1_expression << ") != (" - << s2_expression << ") (ignoring case), actual: \"" - << s1 << "\" vs \"" << s2 << "\""; - } -} - -} // namespace internal - -namespace { - -// Helper functions for implementing IsSubString() and IsNotSubstring(). - -// This group of overloaded functions return true iff needle is a -// substring of haystack. NULL is considered a substring of itself -// only. - -bool IsSubstringPred(const char* needle, const char* haystack) { - if (needle == NULL || haystack == NULL) - return needle == haystack; - - return strstr(haystack, needle) != NULL; -} - -bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { - if (needle == NULL || haystack == NULL) - return needle == haystack; - - return wcsstr(haystack, needle) != NULL; -} - -// StringType here can be either ::std::string or ::std::wstring. -template -bool IsSubstringPred(const StringType& needle, - const StringType& haystack) { - return haystack.find(needle) != StringType::npos; -} - -// This function implements either IsSubstring() or IsNotSubstring(), -// depending on the value of the expected_to_be_substring parameter. -// StringType here can be const char*, const wchar_t*, ::std::string, -// or ::std::wstring. -template -AssertionResult IsSubstringImpl( - bool expected_to_be_substring, - const char* needle_expr, const char* haystack_expr, - const StringType& needle, const StringType& haystack) { - if (IsSubstringPred(needle, haystack) == expected_to_be_substring) - return AssertionSuccess(); - - const bool is_wide_string = sizeof(needle[0]) > 1; - const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; - return AssertionFailure() - << "Value of: " << needle_expr << "\n" - << " Actual: " << begin_string_quote << needle << "\"\n" - << "Expected: " << (expected_to_be_substring ? "" : "not ") - << "a substring of " << haystack_expr << "\n" - << "Which is: " << begin_string_quote << haystack << "\""; -} - -} // namespace - -// IsSubstring() and IsNotSubstring() check whether needle is a -// substring of haystack (NULL is considered a substring of itself -// only), and return an appropriate error message when they fail. - -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack) { - return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); -} - -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack) { - return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); -} - -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack) { - return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); -} - -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack) { - return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); -} - -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack) { - return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); -} - -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack) { - return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); -} - -#if GTEST_HAS_STD_WSTRING -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack) { - return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); -} - -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack) { - return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); -} -#endif // GTEST_HAS_STD_WSTRING - -namespace internal { - -#if GTEST_OS_WINDOWS - -namespace { - -// Helper function for IsHRESULT{SuccessFailure} predicates -AssertionResult HRESULTFailureHelper(const char* expr, - const char* expected, - long hr) { // NOLINT -# if GTEST_OS_WINDOWS_MOBILE - - // Windows CE doesn't support FormatMessage. - const char error_text[] = ""; - -# else - - // Looks up the human-readable system message for the HRESULT code - // and since we're not passing any params to FormatMessage, we don't - // want inserts expanded. - const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS; - const DWORD kBufSize = 4096; // String::Format can't exceed this length. - // Gets the system's human readable message string for this HRESULT. - char error_text[kBufSize] = { '\0' }; - DWORD message_length = ::FormatMessageA(kFlags, - 0, // no source, we're asking system - hr, // the error - 0, // no line width restrictions - error_text, // output buffer - kBufSize, // buf size - NULL); // no arguments for inserts - // Trims tailing white space (FormatMessage leaves a trailing cr-lf) - for (; message_length && IsSpace(error_text[message_length - 1]); - --message_length) { - error_text[message_length - 1] = '\0'; - } - -# endif // GTEST_OS_WINDOWS_MOBILE - - const String error_hex(String::Format("0x%08X ", hr)); - return ::testing::AssertionFailure() - << "Expected: " << expr << " " << expected << ".\n" - << " Actual: " << error_hex << error_text << "\n"; -} - -} // namespace - -AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT - if (SUCCEEDED(hr)) { - return AssertionSuccess(); - } - return HRESULTFailureHelper(expr, "succeeds", hr); -} - -AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT - if (FAILED(hr)) { - return AssertionSuccess(); - } - return HRESULTFailureHelper(expr, "fails", hr); -} - -#endif // GTEST_OS_WINDOWS - -// Utility functions for encoding Unicode text (wide strings) in -// UTF-8. - -// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8 -// like this: -// -// Code-point length Encoding -// 0 - 7 bits 0xxxxxxx -// 8 - 11 bits 110xxxxx 10xxxxxx -// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx -// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - -// The maximum code-point a one-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint1 = (static_cast(1) << 7) - 1; - -// The maximum code-point a two-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint2 = (static_cast(1) << (5 + 6)) - 1; - -// The maximum code-point a three-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint3 = (static_cast(1) << (4 + 2*6)) - 1; - -// The maximum code-point a four-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint4 = (static_cast(1) << (3 + 3*6)) - 1; - -// Chops off the n lowest bits from a bit pattern. Returns the n -// lowest bits. As a side effect, the original bit pattern will be -// shifted to the right by n bits. -inline UInt32 ChopLowBits(UInt32* bits, int n) { - const UInt32 low_bits = *bits & ((static_cast(1) << n) - 1); - *bits >>= n; - return low_bits; -} - -// Converts a Unicode code point to a narrow string in UTF-8 encoding. -// code_point parameter is of type UInt32 because wchar_t may not be -// wide enough to contain a code point. -// The output buffer str must containt at least 32 characters. -// The function returns the address of the output buffer. -// If the code_point is not a valid Unicode code point -// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output -// as '(Invalid Unicode 0xXXXXXXXX)'. -char* CodePointToUtf8(UInt32 code_point, char* str) { - if (code_point <= kMaxCodePoint1) { - str[1] = '\0'; - str[0] = static_cast(code_point); // 0xxxxxxx - } else if (code_point <= kMaxCodePoint2) { - str[2] = '\0'; - str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx - str[0] = static_cast(0xC0 | code_point); // 110xxxxx - } else if (code_point <= kMaxCodePoint3) { - str[3] = '\0'; - str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx - str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx - str[0] = static_cast(0xE0 | code_point); // 1110xxxx - } else if (code_point <= kMaxCodePoint4) { - str[4] = '\0'; - str[3] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx - str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx - str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx - str[0] = static_cast(0xF0 | code_point); // 11110xxx - } else { - // The longest string String::Format can produce when invoked - // with these parameters is 28 character long (not including - // the terminating nul character). We are asking for 32 character - // buffer just in case. This is also enough for strncpy to - // null-terminate the destination string. - posix::StrNCpy( - str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32); - str[31] = '\0'; // Makes sure no change in the format to strncpy leaves - // the result unterminated. - } - return str; -} - -// The following two functions only make sense if the the system -// uses UTF-16 for wide string encoding. All supported systems -// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16. - -// Determines if the arguments constitute UTF-16 surrogate pair -// and thus should be combined into a single Unicode code point -// using CreateCodePointFromUtf16SurrogatePair. -inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { - return sizeof(wchar_t) == 2 && - (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; -} - -// Creates a Unicode code point from UTF16 surrogate pair. -inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, - wchar_t second) { - const UInt32 mask = (1 << 10) - 1; - return (sizeof(wchar_t) == 2) ? - (((first & mask) << 10) | (second & mask)) + 0x10000 : - // This function should not be called when the condition is - // false, but we provide a sensible default in case it is. - static_cast(first); -} - -// Converts a wide string to a narrow string in UTF-8 encoding. -// The wide string is assumed to have the following encoding: -// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) -// UTF-32 if sizeof(wchar_t) == 4 (on Linux) -// Parameter str points to a null-terminated wide string. -// Parameter num_chars may additionally limit the number -// of wchar_t characters processed. -1 is used when the entire string -// should be processed. -// If the string contains code points that are not valid Unicode code points -// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output -// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding -// and contains invalid UTF-16 surrogate pairs, values in those pairs -// will be encoded as individual Unicode characters from Basic Normal Plane. -String WideStringToUtf8(const wchar_t* str, int num_chars) { - if (num_chars == -1) - num_chars = static_cast(wcslen(str)); - - ::std::stringstream stream; - for (int i = 0; i < num_chars; ++i) { - UInt32 unicode_code_point; - - if (str[i] == L'\0') { - break; - } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { - unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], - str[i + 1]); - i++; - } else { - unicode_code_point = static_cast(str[i]); - } - - char buffer[32]; // CodePointToUtf8 requires a buffer this big. - stream << CodePointToUtf8(unicode_code_point, buffer); - } - return StringStreamToString(&stream); -} - -// Converts a wide C string to a String using the UTF-8 encoding. -// NULL will be converted to "(null)". -String String::ShowWideCString(const wchar_t * wide_c_str) { - if (wide_c_str == NULL) return String("(null)"); - - return String(internal::WideStringToUtf8(wide_c_str, -1).c_str()); -} - -// Similar to ShowWideCString(), except that this function encloses -// the converted string in double quotes. -String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) { - if (wide_c_str == NULL) return String("(null)"); - - return String::Format("L\"%s\"", - String::ShowWideCString(wide_c_str).c_str()); -} - -// Compares two wide C strings. Returns true iff they have the same -// content. -// -// Unlike wcscmp(), this function can handle NULL argument(s). A NULL -// C string is considered different to any non-NULL C string, -// including the empty string. -bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { - if (lhs == NULL) return rhs == NULL; - - if (rhs == NULL) return false; - - return wcscmp(lhs, rhs) == 0; -} - -// Helper function for *_STREQ on wide strings. -AssertionResult CmpHelperSTREQ(const char* expected_expression, - const char* actual_expression, - const wchar_t* expected, - const wchar_t* actual) { - if (String::WideCStringEquals(expected, actual)) { - return AssertionSuccess(); - } - - return EqFailure(expected_expression, - actual_expression, - String::ShowWideCStringQuoted(expected), - String::ShowWideCStringQuoted(actual), - false); -} - -// Helper function for *_STRNE on wide strings. -AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const wchar_t* s1, - const wchar_t* s2) { - if (!String::WideCStringEquals(s1, s2)) { - return AssertionSuccess(); - } - - return AssertionFailure() << "Expected: (" << s1_expression << ") != (" - << s2_expression << "), actual: " - << String::ShowWideCStringQuoted(s1) - << " vs " << String::ShowWideCStringQuoted(s2); -} - -// Compares two C strings, ignoring case. Returns true iff they have -// the same content. -// -// Unlike strcasecmp(), this function can handle NULL argument(s). A -// NULL C string is considered different to any non-NULL C string, -// including the empty string. -bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { - if (lhs == NULL) - return rhs == NULL; - if (rhs == NULL) - return false; - return posix::StrCaseCmp(lhs, rhs) == 0; -} - - // Compares two wide C strings, ignoring case. Returns true iff they - // have the same content. - // - // Unlike wcscasecmp(), this function can handle NULL argument(s). - // A NULL C string is considered different to any non-NULL wide C string, - // including the empty string. - // NB: The implementations on different platforms slightly differ. - // On windows, this method uses _wcsicmp which compares according to LC_CTYPE - // environment variable. On GNU platform this method uses wcscasecmp - // which compares according to LC_CTYPE category of the current locale. - // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the - // current locale. -bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, - const wchar_t* rhs) { - if (lhs == NULL) return rhs == NULL; - - if (rhs == NULL) return false; - -#if GTEST_OS_WINDOWS - return _wcsicmp(lhs, rhs) == 0; -#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID - return wcscasecmp(lhs, rhs) == 0; -#else - // Android, Mac OS X and Cygwin don't define wcscasecmp. - // Other unknown OSes may not define it either. - wint_t left, right; - do { - left = towlower(*lhs++); - right = towlower(*rhs++); - } while (left && left == right); - return left == right; -#endif // OS selector -} - -// Compares this with another String. -// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0 -// if this is greater than rhs. -int String::Compare(const String & rhs) const { - const char* const lhs_c_str = c_str(); - const char* const rhs_c_str = rhs.c_str(); - - if (lhs_c_str == NULL) { - return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL - } else if (rhs_c_str == NULL) { - return 1; - } - - const size_t shorter_str_len = - length() <= rhs.length() ? length() : rhs.length(); - for (size_t i = 0; i != shorter_str_len; i++) { - if (lhs_c_str[i] < rhs_c_str[i]) { - return -1; - } else if (lhs_c_str[i] > rhs_c_str[i]) { - return 1; - } - } - return (length() < rhs.length()) ? -1 : - (length() > rhs.length()) ? 1 : 0; -} - -// Returns true iff this String ends with the given suffix. *Any* -// String is considered to end with a NULL or empty suffix. -bool String::EndsWith(const char* suffix) const { - if (suffix == NULL || CStringEquals(suffix, "")) return true; - - if (c_str() == NULL) return false; - - const size_t this_len = strlen(c_str()); - const size_t suffix_len = strlen(suffix); - return (this_len >= suffix_len) && - CStringEquals(c_str() + this_len - suffix_len, suffix); -} - -// Returns true iff this String ends with the given suffix, ignoring case. -// Any String is considered to end with a NULL or empty suffix. -bool String::EndsWithCaseInsensitive(const char* suffix) const { - if (suffix == NULL || CStringEquals(suffix, "")) return true; - - if (c_str() == NULL) return false; - - const size_t this_len = strlen(c_str()); - const size_t suffix_len = strlen(suffix); - return (this_len >= suffix_len) && - CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix); -} - -// Formats a list of arguments to a String, using the same format -// spec string as for printf. -// -// We do not use the StringPrintf class as it is not universally -// available. -// -// The result is limited to 4096 characters (including the tailing 0). -// If 4096 characters are not enough to format the input, or if -// there's an error, "" is -// returned. -String String::Format(const char * format, ...) { - va_list args; - va_start(args, format); - - char buffer[4096]; - const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]); - - // MSVC 8 deprecates vsnprintf(), so we want to suppress warning - // 4996 (deprecated function) there. -#ifdef _MSC_VER // We are using MSVC. -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4996) // Temporarily disables warning 4996. - - const int size = vsnprintf(buffer, kBufferSize, format, args); - -# pragma warning(pop) // Restores the warning state. -#else // We are not using MSVC. - const int size = vsnprintf(buffer, kBufferSize, format, args); -#endif // _MSC_VER - va_end(args); - - // vsnprintf()'s behavior is not portable. When the buffer is not - // big enough, it returns a negative value in MSVC, and returns the - // needed buffer size on Linux. When there is an output error, it - // always returns a negative value. For simplicity, we lump the two - // error cases together. - if (size < 0 || size >= kBufferSize) { - return String(""); - } else { - return String(buffer, size); - } -} - -// Converts the buffer in a stringstream to a String, converting NUL -// bytes to "\\0" along the way. -String StringStreamToString(::std::stringstream* ss) { - const ::std::string& str = ss->str(); - const char* const start = str.c_str(); - const char* const end = start + str.length(); - - // We need to use a helper stringstream to do this transformation - // because String doesn't support push_back(). - ::std::stringstream helper; - for (const char* ch = start; ch != end; ++ch) { - if (*ch == '\0') { - helper << "\\0"; // Replaces NUL with "\\0"; - } else { - helper.put(*ch); - } - } - - return String(helper.str().c_str()); -} - -// Appends the user-supplied message to the Google-Test-generated message. -String AppendUserMessage(const String& gtest_msg, - const Message& user_msg) { - // Appends the user message if it's non-empty. - const String user_msg_string = user_msg.GetString(); - if (user_msg_string.empty()) { - return gtest_msg; - } - - Message msg; - msg << gtest_msg << "\n" << user_msg_string; - - return msg.GetString(); -} - -} // namespace internal - -// class TestResult - -// Creates an empty TestResult. -TestResult::TestResult() - : death_test_count_(0), - elapsed_time_(0) { -} - -// D'tor. -TestResult::~TestResult() { -} - -// Returns the i-th test part result among all the results. i can -// range from 0 to total_part_count() - 1. If i is not in that range, -// aborts the program. -const TestPartResult& TestResult::GetTestPartResult(int i) const { - if (i < 0 || i >= total_part_count()) - internal::posix::Abort(); - return test_part_results_.at(i); -} - -// Returns the i-th test property. i can range from 0 to -// test_property_count() - 1. If i is not in that range, aborts the -// program. -const TestProperty& TestResult::GetTestProperty(int i) const { - if (i < 0 || i >= test_property_count()) - internal::posix::Abort(); - return test_properties_.at(i); -} - -// Clears the test part results. -void TestResult::ClearTestPartResults() { - test_part_results_.clear(); -} - -// Adds a test part result to the list. -void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { - test_part_results_.push_back(test_part_result); -} - -// Adds a test property to the list. If a property with the same key as the -// supplied property is already represented, the value of this test_property -// replaces the old value for that key. -void TestResult::RecordProperty(const TestProperty& test_property) { - if (!ValidateTestProperty(test_property)) { - return; - } - internal::MutexLock lock(&test_properites_mutex_); - const std::vector::iterator property_with_matching_key = - std::find_if(test_properties_.begin(), test_properties_.end(), - internal::TestPropertyKeyIs(test_property.key())); - if (property_with_matching_key == test_properties_.end()) { - test_properties_.push_back(test_property); - return; - } - property_with_matching_key->SetValue(test_property.value()); -} - -// Adds a failure if the key is a reserved attribute of Google Test -// testcase tags. Returns true if the property is valid. -bool TestResult::ValidateTestProperty(const TestProperty& test_property) { - internal::String key(test_property.key()); - if (key == "name" || key == "status" || key == "time" || key == "classname") { - ADD_FAILURE() - << "Reserved key used in RecordProperty(): " - << key - << " ('name', 'status', 'time', and 'classname' are reserved by " - << GTEST_NAME_ << ")"; - return false; - } - return true; -} - -// Clears the object. -void TestResult::Clear() { - test_part_results_.clear(); - test_properties_.clear(); - death_test_count_ = 0; - elapsed_time_ = 0; -} - -// Returns true iff the test failed. -bool TestResult::Failed() const { - for (int i = 0; i < total_part_count(); ++i) { - if (GetTestPartResult(i).failed()) - return true; - } - return false; -} - -// Returns true iff the test part fatally failed. -static bool TestPartFatallyFailed(const TestPartResult& result) { - return result.fatally_failed(); -} - -// Returns true iff the test fatally failed. -bool TestResult::HasFatalFailure() const { - return CountIf(test_part_results_, TestPartFatallyFailed) > 0; -} - -// Returns true iff the test part non-fatally failed. -static bool TestPartNonfatallyFailed(const TestPartResult& result) { - return result.nonfatally_failed(); -} - -// Returns true iff the test has a non-fatal failure. -bool TestResult::HasNonfatalFailure() const { - return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; -} - -// Gets the number of all test parts. This is the sum of the number -// of successful test parts and the number of failed test parts. -int TestResult::total_part_count() const { - return static_cast(test_part_results_.size()); -} - -// Returns the number of the test properties. -int TestResult::test_property_count() const { - return static_cast(test_properties_.size()); -} - -// class Test - -// Creates a Test object. - -// The c'tor saves the values of all Google Test flags. -Test::Test() - : gtest_flag_saver_(new internal::GTestFlagSaver) { -} - -// The d'tor restores the values of all Google Test flags. -Test::~Test() { - delete gtest_flag_saver_; -} - -// Sets up the test fixture. -// -// A sub-class may override this. -void Test::SetUp() { -} - -// Tears down the test fixture. -// -// A sub-class may override this. -void Test::TearDown() { -} - -// Allows user supplied key value pairs to be recorded for later output. -void Test::RecordProperty(const char* key, const char* value) { - UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value); -} - -// Allows user supplied key value pairs to be recorded for later output. -void Test::RecordProperty(const char* key, int value) { - Message value_message; - value_message << value; - RecordProperty(key, value_message.GetString().c_str()); -} - -namespace internal { - -void ReportFailureInUnknownLocation(TestPartResult::Type result_type, - const String& message) { - // This function is a friend of UnitTest and as such has access to - // AddTestPartResult. - UnitTest::GetInstance()->AddTestPartResult( - result_type, - NULL, // No info about the source file where the exception occurred. - -1, // We have no info on which line caused the exception. - message, - String()); // No stack trace, either. -} - -} // namespace internal - -// Google Test requires all tests in the same test case to use the same test -// fixture class. This function checks if the current test has the -// same fixture class as the first test in the current test case. If -// yes, it returns true; otherwise it generates a Google Test failure and -// returns false. -bool Test::HasSameFixtureClass() { - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - const TestCase* const test_case = impl->current_test_case(); - - // Info about the first test in the current test case. - const TestInfo* const first_test_info = test_case->test_info_list()[0]; - const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; - const char* const first_test_name = first_test_info->name(); - - // Info about the current test. - const TestInfo* const this_test_info = impl->current_test_info(); - const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; - const char* const this_test_name = this_test_info->name(); - - if (this_fixture_id != first_fixture_id) { - // Is the first test defined using TEST? - const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); - // Is this test defined using TEST? - const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); - - if (first_is_TEST || this_is_TEST) { - // The user mixed TEST and TEST_F in this test case - we'll tell - // him/her how to fix it. - - // Gets the name of the TEST and the name of the TEST_F. Note - // that first_is_TEST and this_is_TEST cannot both be true, as - // the fixture IDs are different for the two tests. - const char* const TEST_name = - first_is_TEST ? first_test_name : this_test_name; - const char* const TEST_F_name = - first_is_TEST ? this_test_name : first_test_name; - - ADD_FAILURE() - << "All tests in the same test case must use the same test fixture\n" - << "class, so mixing TEST_F and TEST in the same test case is\n" - << "illegal. In test case " << this_test_info->test_case_name() - << ",\n" - << "test " << TEST_F_name << " is defined using TEST_F but\n" - << "test " << TEST_name << " is defined using TEST. You probably\n" - << "want to change the TEST to TEST_F or move it to another test\n" - << "case."; - } else { - // The user defined two fixture classes with the same name in - // two namespaces - we'll tell him/her how to fix it. - ADD_FAILURE() - << "All tests in the same test case must use the same test fixture\n" - << "class. However, in test case " - << this_test_info->test_case_name() << ",\n" - << "you defined test " << first_test_name - << " and test " << this_test_name << "\n" - << "using two different test fixture classes. This can happen if\n" - << "the two classes are from different namespaces or translation\n" - << "units and have the same name. You should probably rename one\n" - << "of the classes to put the tests into different test cases."; - } - return false; - } - - return true; -} - -#if GTEST_HAS_SEH - -// Adds an "exception thrown" fatal failure to the current test. This -// function returns its result via an output parameter pointer because VC++ -// prohibits creation of objects with destructors on stack in functions -// using __try (see error C2712). -static internal::String* FormatSehExceptionMessage(DWORD exception_code, - const char* location) { - Message message; - message << "SEH exception with code 0x" << std::setbase(16) << - exception_code << std::setbase(10) << " thrown in " << location << "."; - - return new internal::String(message.GetString()); -} - -#endif // GTEST_HAS_SEH - -#if GTEST_HAS_EXCEPTIONS - -// Adds an "exception thrown" fatal failure to the current test. -static internal::String FormatCxxExceptionMessage(const char* description, - const char* location) { - Message message; - if (description != NULL) { - message << "C++ exception with description \"" << description << "\""; - } else { - message << "Unknown C++ exception"; - } - message << " thrown in " << location << "."; - - return message.GetString(); -} - -static internal::String PrintTestPartResultToString( - const TestPartResult& test_part_result); - -// A failed Google Test assertion will throw an exception of this type when -// GTEST_FLAG(throw_on_failure) is true (if exceptions are enabled). We -// derive it from std::runtime_error, which is for errors presumably -// detectable only at run time. Since std::runtime_error inherits from -// std::exception, many testing frameworks know how to extract and print the -// message inside it. -class GoogleTestFailureException : public ::std::runtime_error { - public: - explicit GoogleTestFailureException(const TestPartResult& failure) - : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} -}; -#endif // GTEST_HAS_EXCEPTIONS - -namespace internal { -// We put these helper functions in the internal namespace as IBM's xlC -// compiler rejects the code if they were declared static. - -// Runs the given method and handles SEH exceptions it throws, when -// SEH is supported; returns the 0-value for type Result in case of an -// SEH exception. (Microsoft compilers cannot handle SEH and C++ -// exceptions in the same function. Therefore, we provide a separate -// wrapper function for handling SEH exceptions.) -template -Result HandleSehExceptionsInMethodIfSupported( - T* object, Result (T::*method)(), const char* location) { -#if GTEST_HAS_SEH - __try { - return (object->*method)(); - } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT - GetExceptionCode())) { - // We create the exception message on the heap because VC++ prohibits - // creation of objects with destructors on stack in functions using __try - // (see error C2712). - internal::String* exception_message = FormatSehExceptionMessage( - GetExceptionCode(), location); - internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, - *exception_message); - delete exception_message; - return static_cast(0); - } -#else - (void)location; - return (object->*method)(); -#endif // GTEST_HAS_SEH -} - -// Runs the given method and catches and reports C++ and/or SEH-style -// exceptions, if they are supported; returns the 0-value for type -// Result in case of an SEH exception. -template -Result HandleExceptionsInMethodIfSupported( - T* object, Result (T::*method)(), const char* location) { - // NOTE: The user code can affect the way in which Google Test handles - // exceptions by setting GTEST_FLAG(catch_exceptions), but only before - // RUN_ALL_TESTS() starts. It is technically possible to check the flag - // after the exception is caught and either report or re-throw the - // exception based on the flag's value: - // - // try { - // // Perform the test method. - // } catch (...) { - // if (GTEST_FLAG(catch_exceptions)) - // // Report the exception as failure. - // else - // throw; // Re-throws the original exception. - // } - // - // However, the purpose of this flag is to allow the program to drop into - // the debugger when the exception is thrown. On most platforms, once the - // control enters the catch block, the exception origin information is - // lost and the debugger will stop the program at the point of the - // re-throw in this function -- instead of at the point of the original - // throw statement in the code under test. For this reason, we perform - // the check early, sacrificing the ability to affect Google Test's - // exception handling in the method where the exception is thrown. - if (internal::GetUnitTestImpl()->catch_exceptions()) { -#if GTEST_HAS_EXCEPTIONS - try { - return HandleSehExceptionsInMethodIfSupported(object, method, location); - } catch (const GoogleTestFailureException&) { // NOLINT - // This exception doesn't originate in code under test. It makes no - // sense to report it as a test failure. - throw; - } catch (const std::exception& e) { // NOLINT - internal::ReportFailureInUnknownLocation( - TestPartResult::kFatalFailure, - FormatCxxExceptionMessage(e.what(), location)); - } catch (...) { // NOLINT - internal::ReportFailureInUnknownLocation( - TestPartResult::kFatalFailure, - FormatCxxExceptionMessage(NULL, location)); - } - return static_cast(0); -#else - return HandleSehExceptionsInMethodIfSupported(object, method, location); -#endif // GTEST_HAS_EXCEPTIONS - } else { - return (object->*method)(); - } -} - -} // namespace internal - -// Runs the test and updates the test result. -void Test::Run() { - if (!HasSameFixtureClass()) return; - - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); - // We will run the test only if SetUp() was successful. - if (!HasFatalFailure()) { - impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &Test::TestBody, "the test body"); - } - - // However, we want to clean up as much as possible. Hence we will - // always call TearDown(), even if SetUp() or the test body has - // failed. - impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &Test::TearDown, "TearDown()"); -} - -// Returns true iff the current test has a fatal failure. -bool Test::HasFatalFailure() { - return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); -} - -// Returns true iff the current test has a non-fatal failure. -bool Test::HasNonfatalFailure() { - return internal::GetUnitTestImpl()->current_test_result()-> - HasNonfatalFailure(); -} - -// class TestInfo - -// Constructs a TestInfo object. It assumes ownership of the test factory -// object. -// TODO(vladl@google.com): Make a_test_case_name and a_name const string&'s -// to signify they cannot be NULLs. -TestInfo::TestInfo(const char* a_test_case_name, - const char* a_name, - const char* a_type_param, - const char* a_value_param, - internal::TypeId fixture_class_id, - internal::TestFactoryBase* factory) - : test_case_name_(a_test_case_name), - name_(a_name), - type_param_(a_type_param ? new std::string(a_type_param) : NULL), - value_param_(a_value_param ? new std::string(a_value_param) : NULL), - fixture_class_id_(fixture_class_id), - should_run_(false), - is_disabled_(false), - matches_filter_(false), - factory_(factory), - result_() {} - -// Destructs a TestInfo object. -TestInfo::~TestInfo() { delete factory_; } - -namespace internal { - -// Creates a new TestInfo object and registers it with Google Test; -// returns the created object. -// -// Arguments: -// -// test_case_name: name of the test case -// name: name of the test -// type_param: the name of the test's type parameter, or NULL if -// this is not a typed or a type-parameterized test. -// value_param: text representation of the test's value parameter, -// or NULL if this is not a value-parameterized test. -// fixture_class_id: ID of the test fixture class -// set_up_tc: pointer to the function that sets up the test case -// tear_down_tc: pointer to the function that tears down the test case -// factory: pointer to the factory that creates a test object. -// The newly created TestInfo instance will assume -// ownership of the factory object. -TestInfo* MakeAndRegisterTestInfo( - const char* test_case_name, const char* name, - const char* type_param, - const char* value_param, - TypeId fixture_class_id, - SetUpTestCaseFunc set_up_tc, - TearDownTestCaseFunc tear_down_tc, - TestFactoryBase* factory) { - TestInfo* const test_info = - new TestInfo(test_case_name, name, type_param, value_param, - fixture_class_id, factory); - GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); - return test_info; -} - -#if GTEST_HAS_PARAM_TEST -void ReportInvalidTestCaseType(const char* test_case_name, - const char* file, int line) { - Message errors; - errors - << "Attempted redefinition of test case " << test_case_name << ".\n" - << "All tests in the same test case must use the same test fixture\n" - << "class. However, in test case " << test_case_name << ", you tried\n" - << "to define a test using a fixture class different from the one\n" - << "used earlier. This can happen if the two fixture classes are\n" - << "from different namespaces and have the same name. You should\n" - << "probably rename one of the classes to put the tests into different\n" - << "test cases."; - - fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), - errors.GetString().c_str()); -} -#endif // GTEST_HAS_PARAM_TEST - -} // namespace internal - -namespace { - -// A predicate that checks the test name of a TestInfo against a known -// value. -// -// This is used for implementation of the TestCase class only. We put -// it in the anonymous namespace to prevent polluting the outer -// namespace. -// -// TestNameIs is copyable. -class TestNameIs { - public: - // Constructor. - // - // TestNameIs has NO default constructor. - explicit TestNameIs(const char* name) - : name_(name) {} - - // Returns true iff the test name of test_info matches name_. - bool operator()(const TestInfo * test_info) const { - return test_info && internal::String(test_info->name()).Compare(name_) == 0; - } - - private: - internal::String name_; -}; - -} // namespace - -namespace internal { - -// This method expands all parameterized tests registered with macros TEST_P -// and INSTANTIATE_TEST_CASE_P into regular tests and registers those. -// This will be done just once during the program runtime. -void UnitTestImpl::RegisterParameterizedTests() { -#if GTEST_HAS_PARAM_TEST - if (!parameterized_tests_registered_) { - parameterized_test_registry_.RegisterTests(); - parameterized_tests_registered_ = true; - } -#endif -} - -} // namespace internal - -// Creates the test object, runs it, records its result, and then -// deletes it. -void TestInfo::Run() { - if (!should_run_) return; - - // Tells UnitTest where to store test result. - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_info(this); - - TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); - - // Notifies the unit test event listeners that a test is about to start. - repeater->OnTestStart(*this); - - const TimeInMillis start = internal::GetTimeInMillis(); - - impl->os_stack_trace_getter()->UponLeavingGTest(); - - // Creates the test object. - Test* const test = internal::HandleExceptionsInMethodIfSupported( - factory_, &internal::TestFactoryBase::CreateTest, - "the test fixture's constructor"); - - // Runs the test only if the test object was created and its - // constructor didn't generate a fatal failure. - if ((test != NULL) && !Test::HasFatalFailure()) { - // This doesn't throw as all user code that can throw are wrapped into - // exception handling code. - test->Run(); - } - - // Deletes the test object. - impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - test, &Test::DeleteSelf_, "the test fixture's destructor"); - - result_.set_elapsed_time(internal::GetTimeInMillis() - start); - - // Notifies the unit test event listener that a test has just finished. - repeater->OnTestEnd(*this); - - // Tells UnitTest to stop associating assertion results to this - // test. - impl->set_current_test_info(NULL); -} - -// class TestCase - -// Gets the number of successful tests in this test case. -int TestCase::successful_test_count() const { - return CountIf(test_info_list_, TestPassed); -} - -// Gets the number of failed tests in this test case. -int TestCase::failed_test_count() const { - return CountIf(test_info_list_, TestFailed); -} - -int TestCase::disabled_test_count() const { - return CountIf(test_info_list_, TestDisabled); -} - -// Get the number of tests in this test case that should run. -int TestCase::test_to_run_count() const { - return CountIf(test_info_list_, ShouldRunTest); -} - -// Gets the number of all tests. -int TestCase::total_test_count() const { - return static_cast(test_info_list_.size()); -} - -// Creates a TestCase with the given name. -// -// Arguments: -// -// name: name of the test case -// a_type_param: the name of the test case's type parameter, or NULL if -// this is not a typed or a type-parameterized test case. -// set_up_tc: pointer to the function that sets up the test case -// tear_down_tc: pointer to the function that tears down the test case -TestCase::TestCase(const char* a_name, const char* a_type_param, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc) - : name_(a_name), - type_param_(a_type_param ? new std::string(a_type_param) : NULL), - set_up_tc_(set_up_tc), - tear_down_tc_(tear_down_tc), - should_run_(false), - elapsed_time_(0) { -} - -// Destructor of TestCase. -TestCase::~TestCase() { - // Deletes every Test in the collection. - ForEach(test_info_list_, internal::Delete); -} - -// Returns the i-th test among all the tests. i can range from 0 to -// total_test_count() - 1. If i is not in that range, returns NULL. -const TestInfo* TestCase::GetTestInfo(int i) const { - const int index = GetElementOr(test_indices_, i, -1); - return index < 0 ? NULL : test_info_list_[index]; -} - -// Returns the i-th test among all the tests. i can range from 0 to -// total_test_count() - 1. If i is not in that range, returns NULL. -TestInfo* TestCase::GetMutableTestInfo(int i) { - const int index = GetElementOr(test_indices_, i, -1); - return index < 0 ? NULL : test_info_list_[index]; -} - -// Adds a test to this test case. Will delete the test upon -// destruction of the TestCase object. -void TestCase::AddTestInfo(TestInfo * test_info) { - test_info_list_.push_back(test_info); - test_indices_.push_back(static_cast(test_indices_.size())); -} - -// Runs every test in this TestCase. -void TestCase::Run() { - if (!should_run_) return; - - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_case(this); - - TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); - - repeater->OnTestCaseStart(*this); - impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &TestCase::RunSetUpTestCase, "SetUpTestCase()"); - - const internal::TimeInMillis start = internal::GetTimeInMillis(); - for (int i = 0; i < total_test_count(); i++) { - GetMutableTestInfo(i)->Run(); - } - elapsed_time_ = internal::GetTimeInMillis() - start; - - impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &TestCase::RunTearDownTestCase, "TearDownTestCase()"); - - repeater->OnTestCaseEnd(*this); - impl->set_current_test_case(NULL); -} - -// Clears the results of all tests in this test case. -void TestCase::ClearResult() { - ForEach(test_info_list_, TestInfo::ClearTestResult); -} - -// Shuffles the tests in this test case. -void TestCase::ShuffleTests(internal::Random* random) { - Shuffle(random, &test_indices_); -} - -// Restores the test order to before the first shuffle. -void TestCase::UnshuffleTests() { - for (size_t i = 0; i < test_indices_.size(); i++) { - test_indices_[i] = static_cast(i); - } -} - -// Formats a countable noun. Depending on its quantity, either the -// singular form or the plural form is used. e.g. -// -// FormatCountableNoun(1, "formula", "formuli") returns "1 formula". -// FormatCountableNoun(5, "book", "books") returns "5 books". -static internal::String FormatCountableNoun(int count, - const char * singular_form, - const char * plural_form) { - return internal::String::Format("%d %s", count, - count == 1 ? singular_form : plural_form); -} - -// Formats the count of tests. -static internal::String FormatTestCount(int test_count) { - return FormatCountableNoun(test_count, "test", "tests"); -} - -// Formats the count of test cases. -static internal::String FormatTestCaseCount(int test_case_count) { - return FormatCountableNoun(test_case_count, "test case", "test cases"); -} - -// Converts a TestPartResult::Type enum to human-friendly string -// representation. Both kNonFatalFailure and kFatalFailure are translated -// to "Failure", as the user usually doesn't care about the difference -// between the two when viewing the test result. -static const char * TestPartResultTypeToString(TestPartResult::Type type) { - switch (type) { - case TestPartResult::kSuccess: - return "Success"; - - case TestPartResult::kNonFatalFailure: - case TestPartResult::kFatalFailure: -#ifdef _MSC_VER - return "error: "; -#else - return "Failure\n"; -#endif - default: - return "Unknown result type"; - } -} - -// Prints a TestPartResult to a String. -static internal::String PrintTestPartResultToString( - const TestPartResult& test_part_result) { - return (Message() - << internal::FormatFileLocation(test_part_result.file_name(), - test_part_result.line_number()) - << " " << TestPartResultTypeToString(test_part_result.type()) - << test_part_result.message()).GetString(); -} - -// Prints a TestPartResult. -static void PrintTestPartResult(const TestPartResult& test_part_result) { - const internal::String& result = - PrintTestPartResultToString(test_part_result); - printf("%s\n", result.c_str()); - fflush(stdout); - // If the test program runs in Visual Studio or a debugger, the - // following statements add the test part result message to the Output - // window such that the user can double-click on it to jump to the - // corresponding source code location; otherwise they do nothing. -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE - // We don't call OutputDebugString*() on Windows Mobile, as printing - // to stdout is done by OutputDebugString() there already - we don't - // want the same message printed twice. - ::OutputDebugStringA(result.c_str()); - ::OutputDebugStringA("\n"); -#endif -} - -// class PrettyUnitTestResultPrinter - -namespace internal { - -enum GTestColor { - COLOR_DEFAULT, - COLOR_RED, - COLOR_GREEN, - COLOR_YELLOW -}; - -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE - -// Returns the character attribute for the given color. -WORD GetColorAttribute(GTestColor color) { - switch (color) { - case COLOR_RED: return FOREGROUND_RED; - case COLOR_GREEN: return FOREGROUND_GREEN; - case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; - default: return 0; - } -} - -#else - -// Returns the ANSI color code for the given color. COLOR_DEFAULT is -// an invalid input. -const char* GetAnsiColorCode(GTestColor color) { - switch (color) { - case COLOR_RED: return "1"; - case COLOR_GREEN: return "2"; - case COLOR_YELLOW: return "3"; - default: return NULL; - }; -} - -#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE - -// Returns true iff Google Test should use colors in the output. -bool ShouldUseColor(bool stdout_is_tty) { - const char* const gtest_color = GTEST_FLAG(color).c_str(); - - if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { -#if GTEST_OS_WINDOWS - // On Windows the TERM variable is usually not set, but the - // console there does support colors. - return stdout_is_tty; -#else - // On non-Windows platforms, we rely on the TERM variable. - const char* const term = posix::GetEnv("TERM"); - const bool term_supports_color = - String::CStringEquals(term, "xterm") || - String::CStringEquals(term, "xterm-color") || - String::CStringEquals(term, "xterm-256color") || - String::CStringEquals(term, "screen") || - String::CStringEquals(term, "linux") || - String::CStringEquals(term, "cygwin"); - return stdout_is_tty && term_supports_color; -#endif // GTEST_OS_WINDOWS - } - - return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || - String::CaseInsensitiveCStringEquals(gtest_color, "true") || - String::CaseInsensitiveCStringEquals(gtest_color, "t") || - String::CStringEquals(gtest_color, "1"); - // We take "yes", "true", "t", and "1" as meaning "yes". If the - // value is neither one of these nor "auto", we treat it as "no" to - // be conservative. -} - -// Helpers for printing colored strings to stdout. Note that on Windows, we -// cannot simply emit special characters and have the terminal change colors. -// This routine must actually emit the characters rather than return a string -// that would be colored when printed, as can be done on Linux. -void ColoredPrintf(GTestColor color, const char* fmt, ...) { - va_list args; - va_start(args, fmt); - -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS - const bool use_color = false; -#else - static const bool in_color_mode = - ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); - const bool use_color = in_color_mode && (color != COLOR_DEFAULT); -#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS - // The '!= 0' comparison is necessary to satisfy MSVC 7.1. - - if (!use_color) { - vprintf(fmt, args); - va_end(args); - return; - } - -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE - const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); - - // Gets the current text color. - CONSOLE_SCREEN_BUFFER_INFO buffer_info; - GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); - const WORD old_color_attrs = buffer_info.wAttributes; - - // We need to flush the stream buffers into the console before each - // SetConsoleTextAttribute call lest it affect the text that is already - // printed but has not yet reached the console. - fflush(stdout); - SetConsoleTextAttribute(stdout_handle, - GetColorAttribute(color) | FOREGROUND_INTENSITY); - vprintf(fmt, args); - - fflush(stdout); - // Restores the text color. - SetConsoleTextAttribute(stdout_handle, old_color_attrs); -#else - printf("\033[0;3%sm", GetAnsiColorCode(color)); - vprintf(fmt, args); - printf("\033[m"); // Resets the terminal to default. -#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE - va_end(args); -} - -void PrintFullTestCommentIfPresent(const TestInfo& test_info) { - const char* const type_param = test_info.type_param(); - const char* const value_param = test_info.value_param(); - - if (type_param != NULL || value_param != NULL) { - printf(", where "); - if (type_param != NULL) { - printf("TypeParam = %s", type_param); - if (value_param != NULL) - printf(" and "); - } - if (value_param != NULL) { - printf("GetParam() = %s", value_param); - } - } -} - -// This class implements the TestEventListener interface. -// -// Class PrettyUnitTestResultPrinter is copyable. -class PrettyUnitTestResultPrinter : public TestEventListener { - public: - PrettyUnitTestResultPrinter() {} - static void PrintTestName(const char * test_case, const char * test) { - printf("%s.%s", test_case, test); - } - - // The following methods override what's in the TestEventListener class. - virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} - virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); - virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); - virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} - virtual void OnTestCaseStart(const TestCase& test_case); - virtual void OnTestStart(const TestInfo& test_info); - virtual void OnTestPartResult(const TestPartResult& result); - virtual void OnTestEnd(const TestInfo& test_info); - virtual void OnTestCaseEnd(const TestCase& test_case); - virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); - virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} - virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); - virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} - - private: - static void PrintFailedTests(const UnitTest& unit_test); - - internal::String test_case_name_; -}; - - // Fired before each iteration of tests starts. -void PrettyUnitTestResultPrinter::OnTestIterationStart( - const UnitTest& unit_test, int iteration) { - if (GTEST_FLAG(repeat) != 1) - printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); - - const char* const filter = GTEST_FLAG(filter).c_str(); - - // Prints the filter if it's not *. This reminds the user that some - // tests may be skipped. - if (!internal::String::CStringEquals(filter, kUniversalFilter)) { - ColoredPrintf(COLOR_YELLOW, - "Note: %s filter = %s\n", GTEST_NAME_, filter); - } - - if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { - const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); - ColoredPrintf(COLOR_YELLOW, - "Note: This is test shard %d of %s.\n", - static_cast(shard_index) + 1, - internal::posix::GetEnv(kTestTotalShards)); - } - - if (GTEST_FLAG(shuffle)) { - ColoredPrintf(COLOR_YELLOW, - "Note: Randomizing tests' orders with a seed of %d .\n", - unit_test.random_seed()); - } - - ColoredPrintf(COLOR_GREEN, "[==========] "); - printf("Running %s from %s.\n", - FormatTestCount(unit_test.test_to_run_count()).c_str(), - FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); - fflush(stdout); -} - -void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( - const UnitTest& /*unit_test*/) { - ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("Global test environment set-up.\n"); - fflush(stdout); -} - -void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { - test_case_name_ = test_case.name(); - const internal::String counts = - FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); - ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("%s from %s", counts.c_str(), test_case_name_.c_str()); - if (test_case.type_param() == NULL) { - printf("\n"); - } else { - printf(", where TypeParam = %s\n", test_case.type_param()); - } - fflush(stdout); -} - -void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { - ColoredPrintf(COLOR_GREEN, "[ RUN ] "); - PrintTestName(test_case_name_.c_str(), test_info.name()); - printf("\n"); - fflush(stdout); -} - -// Called after an assertion failure. -void PrettyUnitTestResultPrinter::OnTestPartResult( - const TestPartResult& result) { - // If the test part succeeded, we don't need to do anything. - if (result.type() == TestPartResult::kSuccess) - return; - - // Print failure message from the assertion (e.g. expected this and got that). - PrintTestPartResult(result); - fflush(stdout); -} - -void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { - if (test_info.result()->Passed()) { - ColoredPrintf(COLOR_GREEN, "[ OK ] "); - } else { - ColoredPrintf(COLOR_RED, "[ FAILED ] "); - } - PrintTestName(test_case_name_.c_str(), test_info.name()); - if (test_info.result()->Failed()) - PrintFullTestCommentIfPresent(test_info); - - if (GTEST_FLAG(print_time)) { - printf(" (%s ms)\n", internal::StreamableToString( - test_info.result()->elapsed_time()).c_str()); - } else { - printf("\n"); - } - fflush(stdout); -} - -void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { - if (!GTEST_FLAG(print_time)) return; - - test_case_name_ = test_case.name(); - const internal::String counts = - FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); - ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("%s from %s (%s ms total)\n\n", - counts.c_str(), test_case_name_.c_str(), - internal::StreamableToString(test_case.elapsed_time()).c_str()); - fflush(stdout); -} - -void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( - const UnitTest& /*unit_test*/) { - ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("Global test environment tear-down\n"); - fflush(stdout); -} - -// Internal helper for printing the list of failed tests. -void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { - const int failed_test_count = unit_test.failed_test_count(); - if (failed_test_count == 0) { - return; - } - - for (int i = 0; i < unit_test.total_test_case_count(); ++i) { - const TestCase& test_case = *unit_test.GetTestCase(i); - if (!test_case.should_run() || (test_case.failed_test_count() == 0)) { - continue; - } - for (int j = 0; j < test_case.total_test_count(); ++j) { - const TestInfo& test_info = *test_case.GetTestInfo(j); - if (!test_info.should_run() || test_info.result()->Passed()) { - continue; - } - ColoredPrintf(COLOR_RED, "[ FAILED ] "); - printf("%s.%s", test_case.name(), test_info.name()); - PrintFullTestCommentIfPresent(test_info); - printf("\n"); - } - } -} - -void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, - int /*iteration*/) { - ColoredPrintf(COLOR_GREEN, "[==========] "); - printf("%s from %s ran.", - FormatTestCount(unit_test.test_to_run_count()).c_str(), - FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); - if (GTEST_FLAG(print_time)) { - printf(" (%s ms total)", - internal::StreamableToString(unit_test.elapsed_time()).c_str()); - } - printf("\n"); - ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); - printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); - - int num_failures = unit_test.failed_test_count(); - if (!unit_test.Passed()) { - const int failed_test_count = unit_test.failed_test_count(); - ColoredPrintf(COLOR_RED, "[ FAILED ] "); - printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); - PrintFailedTests(unit_test); - printf("\n%2d FAILED %s\n", num_failures, - num_failures == 1 ? "TEST" : "TESTS"); - } - - int num_disabled = unit_test.disabled_test_count(); - if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { - if (!num_failures) { - printf("\n"); // Add a spacer if no FAILURE banner is displayed. - } - ColoredPrintf(COLOR_YELLOW, - " YOU HAVE %d DISABLED %s\n\n", - num_disabled, - num_disabled == 1 ? "TEST" : "TESTS"); - } - // Ensure that Google Test output is printed before, e.g., heapchecker output. - fflush(stdout); -} - -// End PrettyUnitTestResultPrinter - -// class TestEventRepeater -// -// This class forwards events to other event listeners. -class TestEventRepeater : public TestEventListener { - public: - TestEventRepeater() : forwarding_enabled_(true) {} - virtual ~TestEventRepeater(); - void Append(TestEventListener *listener); - TestEventListener* Release(TestEventListener* listener); - - // Controls whether events will be forwarded to listeners_. Set to false - // in death test child processes. - bool forwarding_enabled() const { return forwarding_enabled_; } - void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } - - virtual void OnTestProgramStart(const UnitTest& unit_test); - virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); - virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); - virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test); - virtual void OnTestCaseStart(const TestCase& test_case); - virtual void OnTestStart(const TestInfo& test_info); - virtual void OnTestPartResult(const TestPartResult& result); - virtual void OnTestEnd(const TestInfo& test_info); - virtual void OnTestCaseEnd(const TestCase& test_case); - virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); - virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test); - virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); - virtual void OnTestProgramEnd(const UnitTest& unit_test); - - private: - // Controls whether events will be forwarded to listeners_. Set to false - // in death test child processes. - bool forwarding_enabled_; - // The list of listeners that receive events. - std::vector listeners_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); -}; - -TestEventRepeater::~TestEventRepeater() { - ForEach(listeners_, Delete); -} - -void TestEventRepeater::Append(TestEventListener *listener) { - listeners_.push_back(listener); -} - -// TODO(vladl@google.com): Factor the search functionality into Vector::Find. -TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { - for (size_t i = 0; i < listeners_.size(); ++i) { - if (listeners_[i] == listener) { - listeners_.erase(listeners_.begin() + i); - return listener; - } - } - - return NULL; -} - -// Since most methods are very similar, use macros to reduce boilerplate. -// This defines a member that forwards the call to all listeners. -#define GTEST_REPEATER_METHOD_(Name, Type) \ -void TestEventRepeater::Name(const Type& parameter) { \ - if (forwarding_enabled_) { \ - for (size_t i = 0; i < listeners_.size(); i++) { \ - listeners_[i]->Name(parameter); \ - } \ - } \ -} -// This defines a member that forwards the call to all listeners in reverse -// order. -#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ -void TestEventRepeater::Name(const Type& parameter) { \ - if (forwarding_enabled_) { \ - for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { \ - listeners_[i]->Name(parameter); \ - } \ - } \ -} - -GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) -GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) -GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase) -GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) -GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) -GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) -GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) -GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) -GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) -GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase) -GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) - -#undef GTEST_REPEATER_METHOD_ -#undef GTEST_REVERSE_REPEATER_METHOD_ - -void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, - int iteration) { - if (forwarding_enabled_) { - for (size_t i = 0; i < listeners_.size(); i++) { - listeners_[i]->OnTestIterationStart(unit_test, iteration); - } - } -} - -void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, - int iteration) { - if (forwarding_enabled_) { - for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { - listeners_[i]->OnTestIterationEnd(unit_test, iteration); - } - } -} - -// End TestEventRepeater - -// This class generates an XML output file. -class XmlUnitTestResultPrinter : public EmptyTestEventListener { - public: - explicit XmlUnitTestResultPrinter(const char* output_file); - - virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); - - private: - // Is c a whitespace character that is normalized to a space character - // when it appears in an XML attribute value? - static bool IsNormalizableWhitespace(char c) { - return c == 0x9 || c == 0xA || c == 0xD; - } - - // May c appear in a well-formed XML document? - static bool IsValidXmlCharacter(char c) { - return IsNormalizableWhitespace(c) || c >= 0x20; - } - - // Returns an XML-escaped copy of the input string str. If - // is_attribute is true, the text is meant to appear as an attribute - // value, and normalizable whitespace is preserved by replacing it - // with character references. - static String EscapeXml(const char* str, bool is_attribute); - - // Returns the given string with all characters invalid in XML removed. - static string RemoveInvalidXmlCharacters(const string& str); - - // Convenience wrapper around EscapeXml when str is an attribute value. - static String EscapeXmlAttribute(const char* str) { - return EscapeXml(str, true); - } - - // Convenience wrapper around EscapeXml when str is not an attribute value. - static String EscapeXmlText(const char* str) { return EscapeXml(str, false); } - - // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. - static void OutputXmlCDataSection(::std::ostream* stream, const char* data); - - // Streams an XML representation of a TestInfo object. - static void OutputXmlTestInfo(::std::ostream* stream, - const char* test_case_name, - const TestInfo& test_info); - - // Prints an XML representation of a TestCase object - static void PrintXmlTestCase(FILE* out, const TestCase& test_case); - - // Prints an XML summary of unit_test to output stream out. - static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test); - - // Produces a string representing the test properties in a result as space - // delimited XML attributes based on the property key="value" pairs. - // When the String is not empty, it includes a space at the beginning, - // to delimit this attribute from prior attributes. - static String TestPropertiesAsXmlAttributes(const TestResult& result); - - // The output file. - const String output_file_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); -}; - -// Creates a new XmlUnitTestResultPrinter. -XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) - : output_file_(output_file) { - if (output_file_.c_str() == NULL || output_file_.empty()) { - fprintf(stderr, "XML output file may not be null\n"); - fflush(stderr); - exit(EXIT_FAILURE); - } -} - -// Called after the unit test ends. -void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, - int /*iteration*/) { - FILE* xmlout = NULL; - FilePath output_file(output_file_); - FilePath output_dir(output_file.RemoveFileName()); - - if (output_dir.CreateDirectoriesRecursively()) { - xmlout = posix::FOpen(output_file_.c_str(), "w"); - } - if (xmlout == NULL) { - // TODO(wan): report the reason of the failure. - // - // We don't do it for now as: - // - // 1. There is no urgent need for it. - // 2. It's a bit involved to make the errno variable thread-safe on - // all three operating systems (Linux, Windows, and Mac OS). - // 3. To interpret the meaning of errno in a thread-safe way, - // we need the strerror_r() function, which is not available on - // Windows. - fprintf(stderr, - "Unable to open file \"%s\"\n", - output_file_.c_str()); - fflush(stderr); - exit(EXIT_FAILURE); - } - PrintXmlUnitTest(xmlout, unit_test); - fclose(xmlout); -} - -// Returns an XML-escaped copy of the input string str. If is_attribute -// is true, the text is meant to appear as an attribute value, and -// normalizable whitespace is preserved by replacing it with character -// references. -// -// Invalid XML characters in str, if any, are stripped from the output. -// It is expected that most, if not all, of the text processed by this -// module will consist of ordinary English text. -// If this module is ever modified to produce version 1.1 XML output, -// most invalid characters can be retained using character references. -// TODO(wan): It might be nice to have a minimally invasive, human-readable -// escaping scheme for invalid characters, rather than dropping them. -String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) { - Message m; - - if (str != NULL) { - for (const char* src = str; *src; ++src) { - switch (*src) { - case '<': - m << "<"; - break; - case '>': - m << ">"; - break; - case '&': - m << "&"; - break; - case '\'': - if (is_attribute) - m << "'"; - else - m << '\''; - break; - case '"': - if (is_attribute) - m << """; - else - m << '"'; - break; - default: - if (IsValidXmlCharacter(*src)) { - if (is_attribute && IsNormalizableWhitespace(*src)) - m << String::Format("&#x%02X;", unsigned(*src)); - else - m << *src; - } - break; - } - } - } - - return m.GetString(); -} - -// Returns the given string with all characters invalid in XML removed. -// Currently invalid characters are dropped from the string. An -// alternative is to replace them with certain characters such as . or ?. -string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) { - string output; - output.reserve(str.size()); - for (string::const_iterator it = str.begin(); it != str.end(); ++it) - if (IsValidXmlCharacter(*it)) - output.push_back(*it); - - return output; -} - -// The following routines generate an XML representation of a UnitTest -// object. -// -// This is how Google Test concepts map to the DTD: -// -// <-- corresponds to a UnitTest object -// <-- corresponds to a TestCase object -// <-- corresponds to a TestInfo object -// ... -// ... -// ... -// <-- individual assertion failures -// -// -// - -// Formats the given time in milliseconds as seconds. -std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { - ::std::stringstream ss; - ss << ms/1000.0; - return ss.str(); -} - -// Streams an XML CDATA section, escaping invalid CDATA sequences as needed. -void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, - const char* data) { - const char* segment = data; - *stream << ""); - if (next_segment != NULL) { - stream->write( - segment, static_cast(next_segment - segment)); - *stream << "]]>]]>"); - } else { - *stream << segment; - break; - } - } - *stream << "]]>"; -} - -// Prints an XML representation of a TestInfo object. -// TODO(wan): There is also value in printing properties with the plain printer. -void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, - const char* test_case_name, - const TestInfo& test_info) { - const TestResult& result = *test_info.result(); - *stream << " \n"; - *stream << " "; - const string location = internal::FormatCompilerIndependentFileLocation( - part.file_name(), part.line_number()); - const string message = location + "\n" + part.message(); - OutputXmlCDataSection(stream, - RemoveInvalidXmlCharacters(message).c_str()); - *stream << "\n"; - } - } - - if (failures == 0) - *stream << " />\n"; - else - *stream << " \n"; -} - -// Prints an XML representation of a TestCase object -void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out, - const TestCase& test_case) { - fprintf(out, - " \n", - FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str()); - for (int i = 0; i < test_case.total_test_count(); ++i) { - ::std::stringstream stream; - OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i)); - fprintf(out, "%s", StringStreamToString(&stream).c_str()); - } - fprintf(out, " \n"); -} - -// Prints an XML summary of unit_test to output stream out. -void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out, - const UnitTest& unit_test) { - fprintf(out, "\n"); - fprintf(out, - "\n"); - for (int i = 0; i < unit_test.total_test_case_count(); ++i) - PrintXmlTestCase(out, *unit_test.GetTestCase(i)); - fprintf(out, "\n"); -} - -// Produces a string representing the test properties in a result as space -// delimited XML attributes based on the property key="value" pairs. -String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( - const TestResult& result) { - Message attributes; - for (int i = 0; i < result.test_property_count(); ++i) { - const TestProperty& property = result.GetTestProperty(i); - attributes << " " << property.key() << "=" - << "\"" << EscapeXmlAttribute(property.value()) << "\""; - } - return attributes.GetString(); -} - -// End XmlUnitTestResultPrinter - -#if GTEST_CAN_STREAM_RESULTS_ - -// Streams test results to the given port on the given host machine. -class StreamingListener : public EmptyTestEventListener { - public: - // Escapes '=', '&', '%', and '\n' characters in str as "%xx". - static string UrlEncode(const char* str); - - StreamingListener(const string& host, const string& port) - : sockfd_(-1), host_name_(host), port_num_(port) { - MakeConnection(); - Send("gtest_streaming_protocol_version=1.0\n"); - } - - virtual ~StreamingListener() { - if (sockfd_ != -1) - CloseConnection(); - } - - void OnTestProgramStart(const UnitTest& /* unit_test */) { - Send("event=TestProgramStart\n"); - } - - void OnTestProgramEnd(const UnitTest& unit_test) { - // Note that Google Test current only report elapsed time for each - // test iteration, not for the entire test program. - Send(String::Format("event=TestProgramEnd&passed=%d\n", - unit_test.Passed())); - - // Notify the streaming server to stop. - CloseConnection(); - } - - void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) { - Send(String::Format("event=TestIterationStart&iteration=%d\n", - iteration)); - } - - void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) { - Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n", - unit_test.Passed(), - StreamableToString(unit_test.elapsed_time()).c_str())); - } - - void OnTestCaseStart(const TestCase& test_case) { - Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name())); - } - - void OnTestCaseEnd(const TestCase& test_case) { - Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n", - test_case.Passed(), - StreamableToString(test_case.elapsed_time()).c_str())); - } - - void OnTestStart(const TestInfo& test_info) { - Send(String::Format("event=TestStart&name=%s\n", test_info.name())); - } - - void OnTestEnd(const TestInfo& test_info) { - Send(String::Format( - "event=TestEnd&passed=%d&elapsed_time=%sms\n", - (test_info.result())->Passed(), - StreamableToString((test_info.result())->elapsed_time()).c_str())); - } - - void OnTestPartResult(const TestPartResult& test_part_result) { - const char* file_name = test_part_result.file_name(); - if (file_name == NULL) - file_name = ""; - Send(String::Format("event=TestPartResult&file=%s&line=%d&message=", - UrlEncode(file_name).c_str(), - test_part_result.line_number())); - Send(UrlEncode(test_part_result.message()) + "\n"); - } - - private: - // Creates a client socket and connects to the server. - void MakeConnection(); - - // Closes the socket. - void CloseConnection() { - GTEST_CHECK_(sockfd_ != -1) - << "CloseConnection() can be called only when there is a connection."; - - close(sockfd_); - sockfd_ = -1; - } - - // Sends a string to the socket. - void Send(const string& message) { - GTEST_CHECK_(sockfd_ != -1) - << "Send() can be called only when there is a connection."; - - const int len = static_cast(message.length()); - if (write(sockfd_, message.c_str(), len) != len) { - GTEST_LOG_(WARNING) - << "stream_result_to: failed to stream to " - << host_name_ << ":" << port_num_; - } - } - - int sockfd_; // socket file descriptor - const string host_name_; - const string port_num_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); -}; // class StreamingListener - -// Checks if str contains '=', '&', '%' or '\n' characters. If yes, -// replaces them by "%xx" where xx is their hexadecimal value. For -// example, replaces "=" with "%3D". This algorithm is O(strlen(str)) -// in both time and space -- important as the input str may contain an -// arbitrarily long test failure message and stack trace. -string StreamingListener::UrlEncode(const char* str) { - string result; - result.reserve(strlen(str) + 1); - for (char ch = *str; ch != '\0'; ch = *++str) { - switch (ch) { - case '%': - case '=': - case '&': - case '\n': - result.append(String::Format("%%%02x", static_cast(ch))); - break; - default: - result.push_back(ch); - break; - } - } - return result; -} - -void StreamingListener::MakeConnection() { - GTEST_CHECK_(sockfd_ == -1) - << "MakeConnection() can't be called when there is already a connection."; - - addrinfo hints; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. - hints.ai_socktype = SOCK_STREAM; - addrinfo* servinfo = NULL; - - // Use the getaddrinfo() to get a linked list of IP addresses for - // the given host name. - const int error_num = getaddrinfo( - host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); - if (error_num != 0) { - GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " - << gai_strerror(error_num); - } - - // Loop through all the results and connect to the first we can. - for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL; - cur_addr = cur_addr->ai_next) { - sockfd_ = socket( - cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); - if (sockfd_ != -1) { - // Connect the client socket to the server socket. - if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { - close(sockfd_); - sockfd_ = -1; - } - } - } - - freeaddrinfo(servinfo); // all done with this structure - - if (sockfd_ == -1) { - GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " - << host_name_ << ":" << port_num_; - } -} - -// End of class Streaming Listener -#endif // GTEST_CAN_STREAM_RESULTS__ - -// Class ScopedTrace - -// Pushes the given source file location and message onto a per-thread -// trace stack maintained by Google Test. -// L < UnitTest::mutex_ -ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) { - TraceInfo trace; - trace.file = file; - trace.line = line; - trace.message = message.GetString(); - - UnitTest::GetInstance()->PushGTestTrace(trace); -} - -// Pops the info pushed by the c'tor. -// L < UnitTest::mutex_ -ScopedTrace::~ScopedTrace() { - UnitTest::GetInstance()->PopGTestTrace(); -} - - -// class OsStackTraceGetter - -// Returns the current OS stack trace as a String. Parameters: -// -// max_depth - the maximum number of stack frames to be included -// in the trace. -// skip_count - the number of top frames to be skipped; doesn't count -// against max_depth. -// -// L < mutex_ -// We use "L < mutex_" to denote that the function may acquire mutex_. -String OsStackTraceGetter::CurrentStackTrace(int, int) { - return String(""); -} - -// L < mutex_ -void OsStackTraceGetter::UponLeavingGTest() { -} - -const char* const -OsStackTraceGetter::kElidedFramesMarker = - "... " GTEST_NAME_ " internal frames ..."; - -} // namespace internal - -// class TestEventListeners - -TestEventListeners::TestEventListeners() - : repeater_(new internal::TestEventRepeater()), - default_result_printer_(NULL), - default_xml_generator_(NULL) { -} - -TestEventListeners::~TestEventListeners() { delete repeater_; } - -// Returns the standard listener responsible for the default console -// output. Can be removed from the listeners list to shut down default -// console output. Note that removing this object from the listener list -// with Release transfers its ownership to the user. -void TestEventListeners::Append(TestEventListener* listener) { - repeater_->Append(listener); -} - -// Removes the given event listener from the list and returns it. It then -// becomes the caller's responsibility to delete the listener. Returns -// NULL if the listener is not found in the list. -TestEventListener* TestEventListeners::Release(TestEventListener* listener) { - if (listener == default_result_printer_) - default_result_printer_ = NULL; - else if (listener == default_xml_generator_) - default_xml_generator_ = NULL; - return repeater_->Release(listener); -} - -// Returns repeater that broadcasts the TestEventListener events to all -// subscribers. -TestEventListener* TestEventListeners::repeater() { return repeater_; } - -// Sets the default_result_printer attribute to the provided listener. -// The listener is also added to the listener list and previous -// default_result_printer is removed from it and deleted. The listener can -// also be NULL in which case it will not be added to the list. Does -// nothing if the previous and the current listener objects are the same. -void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { - if (default_result_printer_ != listener) { - // It is an error to pass this method a listener that is already in the - // list. - delete Release(default_result_printer_); - default_result_printer_ = listener; - if (listener != NULL) - Append(listener); - } -} - -// Sets the default_xml_generator attribute to the provided listener. The -// listener is also added to the listener list and previous -// default_xml_generator is removed from it and deleted. The listener can -// also be NULL in which case it will not be added to the list. Does -// nothing if the previous and the current listener objects are the same. -void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { - if (default_xml_generator_ != listener) { - // It is an error to pass this method a listener that is already in the - // list. - delete Release(default_xml_generator_); - default_xml_generator_ = listener; - if (listener != NULL) - Append(listener); - } -} - -// Controls whether events will be forwarded by the repeater to the -// listeners in the list. -bool TestEventListeners::EventForwardingEnabled() const { - return repeater_->forwarding_enabled(); -} - -void TestEventListeners::SuppressEventForwarding() { - repeater_->set_forwarding_enabled(false); -} - -// class UnitTest - -// Gets the singleton UnitTest object. The first time this method is -// called, a UnitTest object is constructed and returned. Consecutive -// calls will return the same object. -// -// We don't protect this under mutex_ as a user is not supposed to -// call this before main() starts, from which point on the return -// value will never change. -UnitTest * UnitTest::GetInstance() { - // When compiled with MSVC 7.1 in optimized mode, destroying the - // UnitTest object upon exiting the program messes up the exit code, - // causing successful tests to appear failed. We have to use a - // different implementation in this case to bypass the compiler bug. - // This implementation makes the compiler happy, at the cost of - // leaking the UnitTest object. - - // CodeGear C++Builder insists on a public destructor for the - // default implementation. Use this implementation to keep good OO - // design with private destructor. - -#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) - static UnitTest* const instance = new UnitTest; - return instance; -#else - static UnitTest instance; - return &instance; -#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) -} - -// Gets the number of successful test cases. -int UnitTest::successful_test_case_count() const { - return impl()->successful_test_case_count(); -} - -// Gets the number of failed test cases. -int UnitTest::failed_test_case_count() const { - return impl()->failed_test_case_count(); -} - -// Gets the number of all test cases. -int UnitTest::total_test_case_count() const { - return impl()->total_test_case_count(); -} - -// Gets the number of all test cases that contain at least one test -// that should run. -int UnitTest::test_case_to_run_count() const { - return impl()->test_case_to_run_count(); -} - -// Gets the number of successful tests. -int UnitTest::successful_test_count() const { - return impl()->successful_test_count(); -} - -// Gets the number of failed tests. -int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } - -// Gets the number of disabled tests. -int UnitTest::disabled_test_count() const { - return impl()->disabled_test_count(); -} - -// Gets the number of all tests. -int UnitTest::total_test_count() const { return impl()->total_test_count(); } - -// Gets the number of tests that should run. -int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } - -// Gets the elapsed time, in milliseconds. -internal::TimeInMillis UnitTest::elapsed_time() const { - return impl()->elapsed_time(); -} - -// Returns true iff the unit test passed (i.e. all test cases passed). -bool UnitTest::Passed() const { return impl()->Passed(); } - -// Returns true iff the unit test failed (i.e. some test case failed -// or something outside of all tests failed). -bool UnitTest::Failed() const { return impl()->Failed(); } - -// Gets the i-th test case among all the test cases. i can range from 0 to -// total_test_case_count() - 1. If i is not in that range, returns NULL. -const TestCase* UnitTest::GetTestCase(int i) const { - return impl()->GetTestCase(i); -} - -// Gets the i-th test case among all the test cases. i can range from 0 to -// total_test_case_count() - 1. If i is not in that range, returns NULL. -TestCase* UnitTest::GetMutableTestCase(int i) { - return impl()->GetMutableTestCase(i); -} - -// Returns the list of event listeners that can be used to track events -// inside Google Test. -TestEventListeners& UnitTest::listeners() { - return *impl()->listeners(); -} - -// Registers and returns a global test environment. When a test -// program is run, all global test environments will be set-up in the -// order they were registered. After all tests in the program have -// finished, all global test environments will be torn-down in the -// *reverse* order they were registered. -// -// The UnitTest object takes ownership of the given environment. -// -// We don't protect this under mutex_, as we only support calling it -// from the main thread. -Environment* UnitTest::AddEnvironment(Environment* env) { - if (env == NULL) { - return NULL; - } - - impl_->environments().push_back(env); - return env; -} - -// Adds a TestPartResult to the current TestResult object. All Google Test -// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call -// this to report their results. The user code should use the -// assertion macros instead of calling this directly. -// L < mutex_ -void UnitTest::AddTestPartResult(TestPartResult::Type result_type, - const char* file_name, - int line_number, - const internal::String& message, - const internal::String& os_stack_trace) { - Message msg; - msg << message; - - internal::MutexLock lock(&mutex_); - if (impl_->gtest_trace_stack().size() > 0) { - msg << "\n" << GTEST_NAME_ << " trace:"; - - for (int i = static_cast(impl_->gtest_trace_stack().size()); - i > 0; --i) { - const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; - msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) - << " " << trace.message; - } - } - - if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) { - msg << internal::kStackTraceMarker << os_stack_trace; - } - - const TestPartResult result = - TestPartResult(result_type, file_name, line_number, - msg.GetString().c_str()); - impl_->GetTestPartResultReporterForCurrentThread()-> - ReportTestPartResult(result); - - if (result_type != TestPartResult::kSuccess) { - // gtest_break_on_failure takes precedence over - // gtest_throw_on_failure. This allows a user to set the latter - // in the code (perhaps in order to use Google Test assertions - // with another testing framework) and specify the former on the - // command line for debugging. - if (GTEST_FLAG(break_on_failure)) { -#if GTEST_OS_WINDOWS - // Using DebugBreak on Windows allows gtest to still break into a debugger - // when a failure happens and both the --gtest_break_on_failure and - // the --gtest_catch_exceptions flags are specified. - DebugBreak(); -#else - // Dereference NULL through a volatile pointer to prevent the compiler - // from removing. We use this rather than abort() or __builtin_trap() for - // portability: Symbian doesn't implement abort() well, and some debuggers - // don't correctly trap abort(). - *static_cast(NULL) = 1; -#endif // GTEST_OS_WINDOWS - } else if (GTEST_FLAG(throw_on_failure)) { -#if GTEST_HAS_EXCEPTIONS - throw GoogleTestFailureException(result); -#else - // We cannot call abort() as it generates a pop-up in debug mode - // that cannot be suppressed in VC 7.1 or below. - exit(1); -#endif - } - } -} - -// Creates and adds a property to the current TestResult. If a property matching -// the supplied value already exists, updates its value instead. -void UnitTest::RecordPropertyForCurrentTest(const char* key, - const char* value) { - const TestProperty test_property(key, value); - impl_->current_test_result()->RecordProperty(test_property); -} - -// Runs all tests in this UnitTest object and prints the result. -// Returns 0 if successful, or 1 otherwise. -// -// We don't protect this under mutex_, as we only support calling it -// from the main thread. -int UnitTest::Run() { - // Captures the value of GTEST_FLAG(catch_exceptions). This value will be - // used for the duration of the program. - impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); - -#if GTEST_HAS_SEH - const bool in_death_test_child_process = - internal::GTEST_FLAG(internal_run_death_test).length() > 0; - - // Either the user wants Google Test to catch exceptions thrown by the - // tests or this is executing in the context of death test child - // process. In either case the user does not want to see pop-up dialogs - // about crashes - they are expected. - if (impl()->catch_exceptions() || in_death_test_child_process) { - -# if !GTEST_OS_WINDOWS_MOBILE - // SetErrorMode doesn't exist on CE. - SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | - SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); -# endif // !GTEST_OS_WINDOWS_MOBILE - -# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE - // Death test children can be terminated with _abort(). On Windows, - // _abort() can show a dialog with a warning message. This forces the - // abort message to go to stderr instead. - _set_error_mode(_OUT_TO_STDERR); -# endif - -# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE - // In the debug version, Visual Studio pops up a separate dialog - // offering a choice to debug the aborted program. We need to suppress - // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement - // executed. Google Test will notify the user of any unexpected - // failure via stderr. - // - // VC++ doesn't define _set_abort_behavior() prior to the version 8.0. - // Users of prior VC versions shall suffer the agony and pain of - // clicking through the countless debug dialogs. - // TODO(vladl@google.com): find a way to suppress the abort dialog() in the - // debug mode when compiled with VC 7.1 or lower. - if (!GTEST_FLAG(break_on_failure)) - _set_abort_behavior( - 0x0, // Clear the following flags: - _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. -# endif - - } -#endif // GTEST_HAS_SEH - - return internal::HandleExceptionsInMethodIfSupported( - impl(), - &internal::UnitTestImpl::RunAllTests, - "auxiliary test code (environments or event listeners)") ? 0 : 1; -} - -// Returns the working directory when the first TEST() or TEST_F() was -// executed. -const char* UnitTest::original_working_dir() const { - return impl_->original_working_dir_.c_str(); -} - -// Returns the TestCase object for the test that's currently running, -// or NULL if no test is running. -// L < mutex_ -const TestCase* UnitTest::current_test_case() const { - internal::MutexLock lock(&mutex_); - return impl_->current_test_case(); -} - -// Returns the TestInfo object for the test that's currently running, -// or NULL if no test is running. -// L < mutex_ -const TestInfo* UnitTest::current_test_info() const { - internal::MutexLock lock(&mutex_); - return impl_->current_test_info(); -} - -// Returns the random seed used at the start of the current test run. -int UnitTest::random_seed() const { return impl_->random_seed(); } - -#if GTEST_HAS_PARAM_TEST -// Returns ParameterizedTestCaseRegistry object used to keep track of -// value-parameterized tests and instantiate and register them. -// L < mutex_ -internal::ParameterizedTestCaseRegistry& - UnitTest::parameterized_test_registry() { - return impl_->parameterized_test_registry(); -} -#endif // GTEST_HAS_PARAM_TEST - -// Creates an empty UnitTest. -UnitTest::UnitTest() { - impl_ = new internal::UnitTestImpl(this); -} - -// Destructor of UnitTest. -UnitTest::~UnitTest() { - delete impl_; -} - -// Pushes a trace defined by SCOPED_TRACE() on to the per-thread -// Google Test trace stack. -// L < mutex_ -void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) { - internal::MutexLock lock(&mutex_); - impl_->gtest_trace_stack().push_back(trace); -} - -// Pops a trace from the per-thread Google Test trace stack. -// L < mutex_ -void UnitTest::PopGTestTrace() { - internal::MutexLock lock(&mutex_); - impl_->gtest_trace_stack().pop_back(); -} - -namespace internal { - -UnitTestImpl::UnitTestImpl(UnitTest* parent) - : parent_(parent), -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4355) // Temporarily disables warning 4355 - // (using this in initializer). - default_global_test_part_result_reporter_(this), - default_per_thread_test_part_result_reporter_(this), -# pragma warning(pop) // Restores the warning state again. -#else - default_global_test_part_result_reporter_(this), - default_per_thread_test_part_result_reporter_(this), -#endif // _MSC_VER - global_test_part_result_repoter_( - &default_global_test_part_result_reporter_), - per_thread_test_part_result_reporter_( - &default_per_thread_test_part_result_reporter_), -#if GTEST_HAS_PARAM_TEST - parameterized_test_registry_(), - parameterized_tests_registered_(false), -#endif // GTEST_HAS_PARAM_TEST - last_death_test_case_(-1), - current_test_case_(NULL), - current_test_info_(NULL), - ad_hoc_test_result_(), - os_stack_trace_getter_(NULL), - post_flag_parse_init_performed_(false), - random_seed_(0), // Will be overridden by the flag before first use. - random_(0), // Will be reseeded before first use. - elapsed_time_(0), -#if GTEST_HAS_DEATH_TEST - internal_run_death_test_flag_(NULL), - death_test_factory_(new DefaultDeathTestFactory), -#endif - // Will be overridden by the flag before first use. - catch_exceptions_(false) { - listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); -} - -UnitTestImpl::~UnitTestImpl() { - // Deletes every TestCase. - ForEach(test_cases_, internal::Delete); - - // Deletes every Environment. - ForEach(environments_, internal::Delete); - - delete os_stack_trace_getter_; -} - -#if GTEST_HAS_DEATH_TEST -// Disables event forwarding if the control is currently in a death test -// subprocess. Must not be called before InitGoogleTest. -void UnitTestImpl::SuppressTestEventsIfInSubprocess() { - if (internal_run_death_test_flag_.get() != NULL) - listeners()->SuppressEventForwarding(); -} -#endif // GTEST_HAS_DEATH_TEST - -// Initializes event listeners performing XML output as specified by -// UnitTestOptions. Must not be called before InitGoogleTest. -void UnitTestImpl::ConfigureXmlOutput() { - const String& output_format = UnitTestOptions::GetOutputFormat(); - if (output_format == "xml") { - listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( - UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); - } else if (output_format != "") { - printf("WARNING: unrecognized output format \"%s\" ignored.\n", - output_format.c_str()); - fflush(stdout); - } -} - -#if GTEST_CAN_STREAM_RESULTS_ -// Initializes event listeners for streaming test results in String form. -// Must not be called before InitGoogleTest. -void UnitTestImpl::ConfigureStreamingOutput() { - const string& target = GTEST_FLAG(stream_result_to); - if (!target.empty()) { - const size_t pos = target.find(':'); - if (pos != string::npos) { - listeners()->Append(new StreamingListener(target.substr(0, pos), - target.substr(pos+1))); - } else { - printf("WARNING: unrecognized streaming target \"%s\" ignored.\n", - target.c_str()); - fflush(stdout); - } - } -} -#endif // GTEST_CAN_STREAM_RESULTS_ - -// Performs initialization dependent upon flag values obtained in -// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to -// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest -// this function is also called from RunAllTests. Since this function can be -// called more than once, it has to be idempotent. -void UnitTestImpl::PostFlagParsingInit() { - // Ensures that this function does not execute more than once. - if (!post_flag_parse_init_performed_) { - post_flag_parse_init_performed_ = true; - -#if GTEST_HAS_DEATH_TEST - InitDeathTestSubprocessControlInfo(); - SuppressTestEventsIfInSubprocess(); -#endif // GTEST_HAS_DEATH_TEST - - // Registers parameterized tests. This makes parameterized tests - // available to the UnitTest reflection API without running - // RUN_ALL_TESTS. - RegisterParameterizedTests(); - - // Configures listeners for XML output. This makes it possible for users - // to shut down the default XML output before invoking RUN_ALL_TESTS. - ConfigureXmlOutput(); - -#if GTEST_CAN_STREAM_RESULTS_ - // Configures listeners for streaming test results to the specified server. - ConfigureStreamingOutput(); -#endif // GTEST_CAN_STREAM_RESULTS_ - } -} - -// A predicate that checks the name of a TestCase against a known -// value. -// -// This is used for implementation of the UnitTest class only. We put -// it in the anonymous namespace to prevent polluting the outer -// namespace. -// -// TestCaseNameIs is copyable. -class TestCaseNameIs { - public: - // Constructor. - explicit TestCaseNameIs(const String& name) - : name_(name) {} - - // Returns true iff the name of test_case matches name_. - bool operator()(const TestCase* test_case) const { - return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0; - } - - private: - String name_; -}; - -// Finds and returns a TestCase with the given name. If one doesn't -// exist, creates one and returns it. It's the CALLER'S -// RESPONSIBILITY to ensure that this function is only called WHEN THE -// TESTS ARE NOT SHUFFLED. -// -// Arguments: -// -// test_case_name: name of the test case -// type_param: the name of the test case's type parameter, or NULL if -// this is not a typed or a type-parameterized test case. -// set_up_tc: pointer to the function that sets up the test case -// tear_down_tc: pointer to the function that tears down the test case -TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, - const char* type_param, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc) { - // Can we find a TestCase with the given name? - const std::vector::const_iterator test_case = - std::find_if(test_cases_.begin(), test_cases_.end(), - TestCaseNameIs(test_case_name)); - - if (test_case != test_cases_.end()) - return *test_case; - - // No. Let's create one. - TestCase* const new_test_case = - new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); - - // Is this a death test case? - if (internal::UnitTestOptions::MatchesFilter(String(test_case_name), - kDeathTestCaseFilter)) { - // Yes. Inserts the test case after the last death test case - // defined so far. This only works when the test cases haven't - // been shuffled. Otherwise we may end up running a death test - // after a non-death test. - ++last_death_test_case_; - test_cases_.insert(test_cases_.begin() + last_death_test_case_, - new_test_case); - } else { - // No. Appends to the end of the list. - test_cases_.push_back(new_test_case); - } - - test_case_indices_.push_back(static_cast(test_case_indices_.size())); - return new_test_case; -} - -// Helpers for setting up / tearing down the given environment. They -// are for use in the ForEach() function. -static void SetUpEnvironment(Environment* env) { env->SetUp(); } -static void TearDownEnvironment(Environment* env) { env->TearDown(); } - -// Runs all tests in this UnitTest object, prints the result, and -// returns true if all tests are successful. If any exception is -// thrown during a test, the test is considered to be failed, but the -// rest of the tests will still be run. -// -// When parameterized tests are enabled, it expands and registers -// parameterized tests first in RegisterParameterizedTests(). -// All other functions called from RunAllTests() may safely assume that -// parameterized tests are ready to be counted and run. -bool UnitTestImpl::RunAllTests() { - // Makes sure InitGoogleTest() was called. - if (!GTestIsInitialized()) { - printf("%s", - "\nThis test program did NOT call ::testing::InitGoogleTest " - "before calling RUN_ALL_TESTS(). Please fix it.\n"); - return false; - } - - // Do not run any test if the --help flag was specified. - if (g_help_flag) - return true; - - // Repeats the call to the post-flag parsing initialization in case the - // user didn't call InitGoogleTest. - PostFlagParsingInit(); - - // Even if sharding is not on, test runners may want to use the - // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding - // protocol. - internal::WriteToShardStatusFileIfNeeded(); - - // True iff we are in a subprocess for running a thread-safe-style - // death test. - bool in_subprocess_for_death_test = false; - -#if GTEST_HAS_DEATH_TEST - in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL); -#endif // GTEST_HAS_DEATH_TEST - - const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, - in_subprocess_for_death_test); - - // Compares the full test names with the filter to decide which - // tests to run. - const bool has_tests_to_run = FilterTests(should_shard - ? HONOR_SHARDING_PROTOCOL - : IGNORE_SHARDING_PROTOCOL) > 0; - - // Lists the tests and exits if the --gtest_list_tests flag was specified. - if (GTEST_FLAG(list_tests)) { - // This must be called *after* FilterTests() has been called. - ListTestsMatchingFilter(); - return true; - } - - random_seed_ = GTEST_FLAG(shuffle) ? - GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; - - // True iff at least one test has failed. - bool failed = false; - - TestEventListener* repeater = listeners()->repeater(); - - repeater->OnTestProgramStart(*parent_); - - // How many times to repeat the tests? We don't want to repeat them - // when we are inside the subprocess of a death test. - const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); - // Repeats forever if the repeat count is negative. - const bool forever = repeat < 0; - for (int i = 0; forever || i != repeat; i++) { - // We want to preserve failures generated by ad-hoc test - // assertions executed before RUN_ALL_TESTS(). - ClearNonAdHocTestResult(); - - const TimeInMillis start = GetTimeInMillis(); - - // Shuffles test cases and tests if requested. - if (has_tests_to_run && GTEST_FLAG(shuffle)) { - random()->Reseed(random_seed_); - // This should be done before calling OnTestIterationStart(), - // such that a test event listener can see the actual test order - // in the event. - ShuffleTests(); - } - - // Tells the unit test event listeners that the tests are about to start. - repeater->OnTestIterationStart(*parent_, i); - - // Runs each test case if there is at least one test to run. - if (has_tests_to_run) { - // Sets up all environments beforehand. - repeater->OnEnvironmentsSetUpStart(*parent_); - ForEach(environments_, SetUpEnvironment); - repeater->OnEnvironmentsSetUpEnd(*parent_); - - // Runs the tests only if there was no fatal failure during global - // set-up. - if (!Test::HasFatalFailure()) { - for (int test_index = 0; test_index < total_test_case_count(); - test_index++) { - GetMutableTestCase(test_index)->Run(); - } - } - - // Tears down all environments in reverse order afterwards. - repeater->OnEnvironmentsTearDownStart(*parent_); - std::for_each(environments_.rbegin(), environments_.rend(), - TearDownEnvironment); - repeater->OnEnvironmentsTearDownEnd(*parent_); - } - - elapsed_time_ = GetTimeInMillis() - start; - - // Tells the unit test event listener that the tests have just finished. - repeater->OnTestIterationEnd(*parent_, i); - - // Gets the result and clears it. - if (!Passed()) { - failed = true; - } - - // Restores the original test order after the iteration. This - // allows the user to quickly repro a failure that happens in the - // N-th iteration without repeating the first (N - 1) iterations. - // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in - // case the user somehow changes the value of the flag somewhere - // (it's always safe to unshuffle the tests). - UnshuffleTests(); - - if (GTEST_FLAG(shuffle)) { - // Picks a new random seed for each iteration. - random_seed_ = GetNextRandomSeed(random_seed_); - } - } - - repeater->OnTestProgramEnd(*parent_); - - return !failed; -} - -// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file -// if the variable is present. If a file already exists at this location, this -// function will write over it. If the variable is present, but the file cannot -// be created, prints an error and exits. -void WriteToShardStatusFileIfNeeded() { - const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); - if (test_shard_file != NULL) { - FILE* const file = posix::FOpen(test_shard_file, "w"); - if (file == NULL) { - ColoredPrintf(COLOR_RED, - "Could not write to the test shard status file \"%s\" " - "specified by the %s environment variable.\n", - test_shard_file, kTestShardStatusFile); - fflush(stdout); - exit(EXIT_FAILURE); - } - fclose(file); - } -} - -// Checks whether sharding is enabled by examining the relevant -// environment variable values. If the variables are present, -// but inconsistent (i.e., shard_index >= total_shards), prints -// an error and exits. If in_subprocess_for_death_test, sharding is -// disabled because it must only be applied to the original test -// process. Otherwise, we could filter out death tests we intended to execute. -bool ShouldShard(const char* total_shards_env, - const char* shard_index_env, - bool in_subprocess_for_death_test) { - if (in_subprocess_for_death_test) { - return false; - } - - const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); - const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); - - if (total_shards == -1 && shard_index == -1) { - return false; - } else if (total_shards == -1 && shard_index != -1) { - const Message msg = Message() - << "Invalid environment variables: you have " - << kTestShardIndex << " = " << shard_index - << ", but have left " << kTestTotalShards << " unset.\n"; - ColoredPrintf(COLOR_RED, msg.GetString().c_str()); - fflush(stdout); - exit(EXIT_FAILURE); - } else if (total_shards != -1 && shard_index == -1) { - const Message msg = Message() - << "Invalid environment variables: you have " - << kTestTotalShards << " = " << total_shards - << ", but have left " << kTestShardIndex << " unset.\n"; - ColoredPrintf(COLOR_RED, msg.GetString().c_str()); - fflush(stdout); - exit(EXIT_FAILURE); - } else if (shard_index < 0 || shard_index >= total_shards) { - const Message msg = Message() - << "Invalid environment variables: we require 0 <= " - << kTestShardIndex << " < " << kTestTotalShards - << ", but you have " << kTestShardIndex << "=" << shard_index - << ", " << kTestTotalShards << "=" << total_shards << ".\n"; - ColoredPrintf(COLOR_RED, msg.GetString().c_str()); - fflush(stdout); - exit(EXIT_FAILURE); - } - - return total_shards > 1; -} - -// Parses the environment variable var as an Int32. If it is unset, -// returns default_val. If it is not an Int32, prints an error -// and aborts. -Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { - const char* str_val = posix::GetEnv(var); - if (str_val == NULL) { - return default_val; - } - - Int32 result; - if (!ParseInt32(Message() << "The value of environment variable " << var, - str_val, &result)) { - exit(EXIT_FAILURE); - } - return result; -} - -// Given the total number of shards, the shard index, and the test id, -// returns true iff the test should be run on this shard. The test id is -// some arbitrary but unique non-negative integer assigned to each test -// method. Assumes that 0 <= shard_index < total_shards. -bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { - return (test_id % total_shards) == shard_index; -} - -// Compares the name of each test with the user-specified filter to -// decide whether the test should be run, then records the result in -// each TestCase and TestInfo object. -// If shard_tests == true, further filters tests based on sharding -// variables in the environment - see -// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide. -// Returns the number of tests that should run. -int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { - const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? - Int32FromEnvOrDie(kTestTotalShards, -1) : -1; - const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? - Int32FromEnvOrDie(kTestShardIndex, -1) : -1; - - // num_runnable_tests are the number of tests that will - // run across all shards (i.e., match filter and are not disabled). - // num_selected_tests are the number of tests to be run on - // this shard. - int num_runnable_tests = 0; - int num_selected_tests = 0; - for (size_t i = 0; i < test_cases_.size(); i++) { - TestCase* const test_case = test_cases_[i]; - const String &test_case_name = test_case->name(); - test_case->set_should_run(false); - - for (size_t j = 0; j < test_case->test_info_list().size(); j++) { - TestInfo* const test_info = test_case->test_info_list()[j]; - const String test_name(test_info->name()); - // A test is disabled if test case name or test name matches - // kDisableTestFilter. - const bool is_disabled = - internal::UnitTestOptions::MatchesFilter(test_case_name, - kDisableTestFilter) || - internal::UnitTestOptions::MatchesFilter(test_name, - kDisableTestFilter); - test_info->is_disabled_ = is_disabled; - - const bool matches_filter = - internal::UnitTestOptions::FilterMatchesTest(test_case_name, - test_name); - test_info->matches_filter_ = matches_filter; - - const bool is_runnable = - (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && - matches_filter; - - const bool is_selected = is_runnable && - (shard_tests == IGNORE_SHARDING_PROTOCOL || - ShouldRunTestOnShard(total_shards, shard_index, - num_runnable_tests)); - - num_runnable_tests += is_runnable; - num_selected_tests += is_selected; - - test_info->should_run_ = is_selected; - test_case->set_should_run(test_case->should_run() || is_selected); - } - } - return num_selected_tests; -} - -// Prints the names of the tests matching the user-specified filter flag. -void UnitTestImpl::ListTestsMatchingFilter() { - for (size_t i = 0; i < test_cases_.size(); i++) { - const TestCase* const test_case = test_cases_[i]; - bool printed_test_case_name = false; - - for (size_t j = 0; j < test_case->test_info_list().size(); j++) { - const TestInfo* const test_info = - test_case->test_info_list()[j]; - if (test_info->matches_filter_) { - if (!printed_test_case_name) { - printed_test_case_name = true; - printf("%s.\n", test_case->name()); - } - printf(" %s\n", test_info->name()); - } - } - } - fflush(stdout); -} - -// Sets the OS stack trace getter. -// -// Does nothing if the input and the current OS stack trace getter are -// the same; otherwise, deletes the old getter and makes the input the -// current getter. -void UnitTestImpl::set_os_stack_trace_getter( - OsStackTraceGetterInterface* getter) { - if (os_stack_trace_getter_ != getter) { - delete os_stack_trace_getter_; - os_stack_trace_getter_ = getter; - } -} - -// Returns the current OS stack trace getter if it is not NULL; -// otherwise, creates an OsStackTraceGetter, makes it the current -// getter, and returns it. -OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { - if (os_stack_trace_getter_ == NULL) { - os_stack_trace_getter_ = new OsStackTraceGetter; - } - - return os_stack_trace_getter_; -} - -// Returns the TestResult for the test that's currently running, or -// the TestResult for the ad hoc test if no test is running. -TestResult* UnitTestImpl::current_test_result() { - return current_test_info_ ? - &(current_test_info_->result_) : &ad_hoc_test_result_; -} - -// Shuffles all test cases, and the tests within each test case, -// making sure that death tests are still run first. -void UnitTestImpl::ShuffleTests() { - // Shuffles the death test cases. - ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_); - - // Shuffles the non-death test cases. - ShuffleRange(random(), last_death_test_case_ + 1, - static_cast(test_cases_.size()), &test_case_indices_); - - // Shuffles the tests inside each test case. - for (size_t i = 0; i < test_cases_.size(); i++) { - test_cases_[i]->ShuffleTests(random()); - } -} - -// Restores the test cases and tests to their order before the first shuffle. -void UnitTestImpl::UnshuffleTests() { - for (size_t i = 0; i < test_cases_.size(); i++) { - // Unshuffles the tests in each test case. - test_cases_[i]->UnshuffleTests(); - // Resets the index of each test case. - test_case_indices_[i] = static_cast(i); - } -} - -// Returns the current OS stack trace as a String. -// -// The maximum number of stack frames to be included is specified by -// the gtest_stack_trace_depth flag. The skip_count parameter -// specifies the number of top frames to be skipped, which doesn't -// count against the number of frames to be included. -// -// For example, if Foo() calls Bar(), which in turn calls -// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in -// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. -String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, - int skip_count) { - // We pass skip_count + 1 to skip this wrapper function in addition - // to what the user really wants to skip. - return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); -} - -// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to -// suppress unreachable code warnings. -namespace { -class ClassUniqueToAlwaysTrue {}; -} - -bool IsTrue(bool condition) { return condition; } - -bool AlwaysTrue() { -#if GTEST_HAS_EXCEPTIONS - // This condition is always false so AlwaysTrue() never actually throws, - // but it makes the compiler think that it may throw. - if (IsTrue(false)) - throw ClassUniqueToAlwaysTrue(); -#endif // GTEST_HAS_EXCEPTIONS - return true; -} - -// If *pstr starts with the given prefix, modifies *pstr to be right -// past the prefix and returns true; otherwise leaves *pstr unchanged -// and returns false. None of pstr, *pstr, and prefix can be NULL. -bool SkipPrefix(const char* prefix, const char** pstr) { - const size_t prefix_len = strlen(prefix); - if (strncmp(*pstr, prefix, prefix_len) == 0) { - *pstr += prefix_len; - return true; - } - return false; -} - -// Parses a string as a command line flag. The string should have -// the format "--flag=value". When def_optional is true, the "=value" -// part can be omitted. -// -// Returns the value of the flag, or NULL if the parsing failed. -const char* ParseFlagValue(const char* str, - const char* flag, - bool def_optional) { - // str and flag must not be NULL. - if (str == NULL || flag == NULL) return NULL; - - // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. - const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag); - const size_t flag_len = flag_str.length(); - if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; - - // Skips the flag name. - const char* flag_end = str + flag_len; - - // When def_optional is true, it's OK to not have a "=value" part. - if (def_optional && (flag_end[0] == '\0')) { - return flag_end; - } - - // If def_optional is true and there are more characters after the - // flag name, or if def_optional is false, there must be a '=' after - // the flag name. - if (flag_end[0] != '=') return NULL; - - // Returns the string after "=". - return flag_end + 1; -} - -// Parses a string for a bool flag, in the form of either -// "--flag=value" or "--flag". -// -// In the former case, the value is taken as true as long as it does -// not start with '0', 'f', or 'F'. -// -// In the latter case, the value is taken as true. -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseBoolFlag(const char* str, const char* flag, bool* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, true); - - // Aborts if the parsing failed. - if (value_str == NULL) return false; - - // Converts the string value to a bool. - *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); - return true; -} - -// Parses a string for an Int32 flag, in the form of -// "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, false); - - // Aborts if the parsing failed. - if (value_str == NULL) return false; - - // Sets *value to the value of the flag. - return ParseInt32(Message() << "The value of flag --" << flag, - value_str, value); -} - -// Parses a string for a string flag, in the form of -// "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseStringFlag(const char* str, const char* flag, String* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, false); - - // Aborts if the parsing failed. - if (value_str == NULL) return false; - - // Sets *value to the value of the flag. - *value = value_str; - return true; -} - -// Determines whether a string has a prefix that Google Test uses for its -// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. -// If Google Test detects that a command line flag has its prefix but is not -// recognized, it will print its help message. Flags starting with -// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test -// internal flags and do not trigger the help message. -static bool HasGoogleTestFlagPrefix(const char* str) { - return (SkipPrefix("--", &str) || - SkipPrefix("-", &str) || - SkipPrefix("/", &str)) && - !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && - (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || - SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); -} - -// Prints a string containing code-encoded text. The following escape -// sequences can be used in the string to control the text color: -// -// @@ prints a single '@' character. -// @R changes the color to red. -// @G changes the color to green. -// @Y changes the color to yellow. -// @D changes to the default terminal text color. -// -// TODO(wan@google.com): Write tests for this once we add stdout -// capturing to Google Test. -static void PrintColorEncoded(const char* str) { - GTestColor color = COLOR_DEFAULT; // The current color. - - // Conceptually, we split the string into segments divided by escape - // sequences. Then we print one segment at a time. At the end of - // each iteration, the str pointer advances to the beginning of the - // next segment. - for (;;) { - const char* p = strchr(str, '@'); - if (p == NULL) { - ColoredPrintf(color, "%s", str); - return; - } - - ColoredPrintf(color, "%s", String(str, p - str).c_str()); - - const char ch = p[1]; - str = p + 2; - if (ch == '@') { - ColoredPrintf(color, "@"); - } else if (ch == 'D') { - color = COLOR_DEFAULT; - } else if (ch == 'R') { - color = COLOR_RED; - } else if (ch == 'G') { - color = COLOR_GREEN; - } else if (ch == 'Y') { - color = COLOR_YELLOW; - } else { - --str; - } - } -} - -static const char kColorEncodedHelpMessage[] = -"This program contains tests written using " GTEST_NAME_ ". You can use the\n" -"following command line flags to control its behavior:\n" -"\n" -"Test Selection:\n" -" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" -" List the names of all tests instead of running them. The name of\n" -" TEST(Foo, Bar) is \"Foo.Bar\".\n" -" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" - "[@G-@YNEGATIVE_PATTERNS]@D\n" -" Run only the tests whose name matches one of the positive patterns but\n" -" none of the negative patterns. '?' matches any single character; '*'\n" -" matches any substring; ':' separates two patterns.\n" -" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" -" Run all disabled tests too.\n" -"\n" -"Test Execution:\n" -" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" -" Run the tests repeatedly; use a negative count to repeat forever.\n" -" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" -" Randomize tests' orders on every iteration.\n" -" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" -" Random number seed to use for shuffling test orders (between 1 and\n" -" 99999, or 0 to use a seed based on the current time).\n" -"\n" -"Test Output:\n" -" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" -" Enable/disable colored output. The default is @Gauto@D.\n" -" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n" -" Don't print the elapsed time of each test.\n" -" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G" - GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" -" Generate an XML report in the given directory or with the given file\n" -" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" -#if GTEST_CAN_STREAM_RESULTS_ -" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" -" Stream test results to the given server.\n" -#endif // GTEST_CAN_STREAM_RESULTS_ -"\n" -"Assertion Behavior:\n" -#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS -" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" -" Set the default death test style.\n" -#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS -" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" -" Turn assertion failures into debugger break-points.\n" -" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" -" Turn assertion failures into C++ exceptions.\n" -" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" -" Do not report exceptions as test failures. Instead, allow them\n" -" to crash the program or throw a pop-up (on Windows).\n" -"\n" -"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " - "the corresponding\n" -"environment variable of a flag (all letters in upper-case). For example, to\n" -"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ - "color=no@D or set\n" -"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" -"\n" -"For more information, please read the " GTEST_NAME_ " documentation at\n" -"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" -"(not one in your own code or tests), please report it to\n" -"@G<" GTEST_DEV_EMAIL_ ">@D.\n"; - -// Parses the command line for Google Test flags, without initializing -// other parts of Google Test. The type parameter CharType can be -// instantiated to either char or wchar_t. -template -void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { - for (int i = 1; i < *argc; i++) { - const String arg_string = StreamableToString(argv[i]); - const char* const arg = arg_string.c_str(); - - using internal::ParseBoolFlag; - using internal::ParseInt32Flag; - using internal::ParseStringFlag; - - // Do we see a Google Test flag? - if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, - >EST_FLAG(also_run_disabled_tests)) || - ParseBoolFlag(arg, kBreakOnFailureFlag, - >EST_FLAG(break_on_failure)) || - ParseBoolFlag(arg, kCatchExceptionsFlag, - >EST_FLAG(catch_exceptions)) || - ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || - ParseStringFlag(arg, kDeathTestStyleFlag, - >EST_FLAG(death_test_style)) || - ParseBoolFlag(arg, kDeathTestUseFork, - >EST_FLAG(death_test_use_fork)) || - ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || - ParseStringFlag(arg, kInternalRunDeathTestFlag, - >EST_FLAG(internal_run_death_test)) || - ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || - ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || - ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || - ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || - ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || - ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || - ParseInt32Flag(arg, kStackTraceDepthFlag, - >EST_FLAG(stack_trace_depth)) || - ParseStringFlag(arg, kStreamResultToFlag, - >EST_FLAG(stream_result_to)) || - ParseBoolFlag(arg, kThrowOnFailureFlag, - >EST_FLAG(throw_on_failure)) - ) { - // Yes. Shift the remainder of the argv list left by one. Note - // that argv has (*argc + 1) elements, the last one always being - // NULL. The following loop moves the trailing NULL element as - // well. - for (int j = i; j != *argc; j++) { - argv[j] = argv[j + 1]; - } - - // Decrements the argument count. - (*argc)--; - - // We also need to decrement the iterator as we just removed - // an element. - i--; - } else if (arg_string == "--help" || arg_string == "-h" || - arg_string == "-?" || arg_string == "/?" || - HasGoogleTestFlagPrefix(arg)) { - // Both help flag and unrecognized Google Test flags (excluding - // internal ones) trigger help display. - g_help_flag = true; - } - } - - if (g_help_flag) { - // We print the help here instead of in RUN_ALL_TESTS(), as the - // latter may not be called at all if the user is using Google - // Test with another testing framework. - PrintColorEncoded(kColorEncodedHelpMessage); - } -} - -// Parses the command line for Google Test flags, without initializing -// other parts of Google Test. -void ParseGoogleTestFlagsOnly(int* argc, char** argv) { - ParseGoogleTestFlagsOnlyImpl(argc, argv); -} -void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { - ParseGoogleTestFlagsOnlyImpl(argc, argv); -} - -// The internal implementation of InitGoogleTest(). -// -// The type parameter CharType can be instantiated to either char or -// wchar_t. -template -void InitGoogleTestImpl(int* argc, CharType** argv) { - g_init_gtest_count++; - - // We don't want to run the initialization code twice. - if (g_init_gtest_count != 1) return; - - if (*argc <= 0) return; - - internal::g_executable_path = internal::StreamableToString(argv[0]); - -#if GTEST_HAS_DEATH_TEST - - g_argvs.clear(); - for (int i = 0; i != *argc; i++) { - g_argvs.push_back(StreamableToString(argv[i])); - } - -#endif // GTEST_HAS_DEATH_TEST - - ParseGoogleTestFlagsOnly(argc, argv); - GetUnitTestImpl()->PostFlagParsingInit(); -} - -} // namespace internal - -// Initializes Google Test. This must be called before calling -// RUN_ALL_TESTS(). In particular, it parses a command line for the -// flags that Google Test recognizes. Whenever a Google Test flag is -// seen, it is removed from argv, and *argc is decremented. -// -// No value is returned. Instead, the Google Test flag variables are -// updated. -// -// Calling the function for the second time has no user-visible effect. -void InitGoogleTest(int* argc, char** argv) { - internal::InitGoogleTestImpl(argc, argv); -} - -// This overloaded version can be used in Windows programs compiled in -// UNICODE mode. -void InitGoogleTest(int* argc, wchar_t** argv) { - internal::InitGoogleTestImpl(argc, argv); -} - -} // namespace testing -// Copyright 2005, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) -// -// This file implements death tests. - - -#if GTEST_HAS_DEATH_TEST - -# if GTEST_OS_MAC -# include -# endif // GTEST_OS_MAC - -# include -# include -# include -# include - -# if GTEST_OS_WINDOWS -# include -# else -# include -# include -# endif // GTEST_OS_WINDOWS - -#endif // GTEST_HAS_DEATH_TEST - - -// Indicates that this translation unit is part of Google Test's -// implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. -#define GTEST_IMPLEMENTATION_ 1 -#undef GTEST_IMPLEMENTATION_ - -namespace testing { - -// Constants. - -// The default death test style. -static const char kDefaultDeathTestStyle[] = "fast"; - -GTEST_DEFINE_string_( - death_test_style, - internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), - "Indicates how to run a death test in a forked child process: " - "\"threadsafe\" (child process re-executes the test binary " - "from the beginning, running only the specific death test) or " - "\"fast\" (child process runs the death test immediately " - "after forking)."); - -GTEST_DEFINE_bool_( - death_test_use_fork, - internal::BoolFromGTestEnv("death_test_use_fork", false), - "Instructs to use fork()/_exit() instead of clone() in death tests. " - "Ignored and always uses fork() on POSIX systems where clone() is not " - "implemented. Useful when running under valgrind or similar tools if " - "those do not support clone(). Valgrind 3.3.1 will just fail if " - "it sees an unsupported combination of clone() flags. " - "It is not recommended to use this flag w/o valgrind though it will " - "work in 99% of the cases. Once valgrind is fixed, this flag will " - "most likely be removed."); - -namespace internal { -GTEST_DEFINE_string_( - internal_run_death_test, "", - "Indicates the file, line number, temporal index of " - "the single death test to run, and a file descriptor to " - "which a success code may be sent, all separated by " - "colons. This flag is specified if and only if the current " - "process is a sub-process launched for running a thread-safe " - "death test. FOR INTERNAL USE ONLY."); -} // namespace internal - -#if GTEST_HAS_DEATH_TEST - -// ExitedWithCode constructor. -ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { -} - -// ExitedWithCode function-call operator. -bool ExitedWithCode::operator()(int exit_status) const { -# if GTEST_OS_WINDOWS - - return exit_status == exit_code_; - -# else - - return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; - -# endif // GTEST_OS_WINDOWS -} - -# if !GTEST_OS_WINDOWS -// KilledBySignal constructor. -KilledBySignal::KilledBySignal(int signum) : signum_(signum) { -} - -// KilledBySignal function-call operator. -bool KilledBySignal::operator()(int exit_status) const { - return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; -} -# endif // !GTEST_OS_WINDOWS - -namespace internal { - -// Utilities needed for death tests. - -// Generates a textual description of a given exit code, in the format -// specified by wait(2). -static String ExitSummary(int exit_code) { - Message m; - -# if GTEST_OS_WINDOWS - - m << "Exited with exit status " << exit_code; - -# else - - if (WIFEXITED(exit_code)) { - m << "Exited with exit status " << WEXITSTATUS(exit_code); - } else if (WIFSIGNALED(exit_code)) { - m << "Terminated by signal " << WTERMSIG(exit_code); - } -# ifdef WCOREDUMP - if (WCOREDUMP(exit_code)) { - m << " (core dumped)"; - } -# endif -# endif // GTEST_OS_WINDOWS - - return m.GetString(); -} - -// Returns true if exit_status describes a process that was terminated -// by a signal, or exited normally with a nonzero exit code. -bool ExitedUnsuccessfully(int exit_status) { - return !ExitedWithCode(0)(exit_status); -} - -# if !GTEST_OS_WINDOWS -// Generates a textual failure message when a death test finds more than -// one thread running, or cannot determine the number of threads, prior -// to executing the given statement. It is the responsibility of the -// caller not to pass a thread_count of 1. -static String DeathTestThreadWarning(size_t thread_count) { - Message msg; - msg << "Death tests use fork(), which is unsafe particularly" - << " in a threaded context. For this test, " << GTEST_NAME_ << " "; - if (thread_count == 0) - msg << "couldn't detect the number of threads."; - else - msg << "detected " << thread_count << " threads."; - return msg.GetString(); -} -# endif // !GTEST_OS_WINDOWS - -// Flag characters for reporting a death test that did not die. -static const char kDeathTestLived = 'L'; -static const char kDeathTestReturned = 'R'; -static const char kDeathTestThrew = 'T'; -static const char kDeathTestInternalError = 'I'; - -// An enumeration describing all of the possible ways that a death test can -// conclude. DIED means that the process died while executing the test -// code; LIVED means that process lived beyond the end of the test code; -// RETURNED means that the test statement attempted to execute a return -// statement, which is not allowed; THREW means that the test statement -// returned control by throwing an exception. IN_PROGRESS means the test -// has not yet concluded. -// TODO(vladl@google.com): Unify names and possibly values for -// AbortReason, DeathTestOutcome, and flag characters above. -enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; - -// Routine for aborting the program which is safe to call from an -// exec-style death test child process, in which case the error -// message is propagated back to the parent process. Otherwise, the -// message is simply printed to stderr. In either case, the program -// then exits with status 1. -void DeathTestAbort(const String& message) { - // On a POSIX system, this function may be called from a threadsafe-style - // death test child process, which operates on a very small stack. Use - // the heap for any additional non-minuscule memory requirements. - const InternalRunDeathTestFlag* const flag = - GetUnitTestImpl()->internal_run_death_test_flag(); - if (flag != NULL) { - FILE* parent = posix::FDOpen(flag->write_fd(), "w"); - fputc(kDeathTestInternalError, parent); - fprintf(parent, "%s", message.c_str()); - fflush(parent); - _exit(1); - } else { - fprintf(stderr, "%s", message.c_str()); - fflush(stderr); - posix::Abort(); - } -} - -// A replacement for CHECK that calls DeathTestAbort if the assertion -// fails. -# define GTEST_DEATH_TEST_CHECK_(expression) \ - do { \ - if (!::testing::internal::IsTrue(expression)) { \ - DeathTestAbort(::testing::internal::String::Format( \ - "CHECK failed: File %s, line %d: %s", \ - __FILE__, __LINE__, #expression)); \ - } \ - } while (::testing::internal::AlwaysFalse()) - -// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for -// evaluating any system call that fulfills two conditions: it must return -// -1 on failure, and set errno to EINTR when it is interrupted and -// should be tried again. The macro expands to a loop that repeatedly -// evaluates the expression as long as it evaluates to -1 and sets -// errno to EINTR. If the expression evaluates to -1 but errno is -// something other than EINTR, DeathTestAbort is called. -# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ - do { \ - int gtest_retval; \ - do { \ - gtest_retval = (expression); \ - } while (gtest_retval == -1 && errno == EINTR); \ - if (gtest_retval == -1) { \ - DeathTestAbort(::testing::internal::String::Format( \ - "CHECK failed: File %s, line %d: %s != -1", \ - __FILE__, __LINE__, #expression)); \ - } \ - } while (::testing::internal::AlwaysFalse()) - -// Returns the message describing the last system error in errno. -String GetLastErrnoDescription() { - return String(errno == 0 ? "" : posix::StrError(errno)); -} - -// This is called from a death test parent process to read a failure -// message from the death test child process and log it with the FATAL -// severity. On Windows, the message is read from a pipe handle. On other -// platforms, it is read from a file descriptor. -static void FailFromInternalError(int fd) { - Message error; - char buffer[256]; - int num_read; - - do { - while ((num_read = posix::Read(fd, buffer, 255)) > 0) { - buffer[num_read] = '\0'; - error << buffer; - } - } while (num_read == -1 && errno == EINTR); - - if (num_read == 0) { - GTEST_LOG_(FATAL) << error.GetString(); - } else { - const int last_error = errno; - GTEST_LOG_(FATAL) << "Error while reading death test internal: " - << GetLastErrnoDescription() << " [" << last_error << "]"; - } -} - -// Death test constructor. Increments the running death test count -// for the current test. -DeathTest::DeathTest() { - TestInfo* const info = GetUnitTestImpl()->current_test_info(); - if (info == NULL) { - DeathTestAbort("Cannot run a death test outside of a TEST or " - "TEST_F construct"); - } -} - -// Creates and returns a death test by dispatching to the current -// death test factory. -bool DeathTest::Create(const char* statement, const RE* regex, - const char* file, int line, DeathTest** test) { - return GetUnitTestImpl()->death_test_factory()->Create( - statement, regex, file, line, test); -} - -const char* DeathTest::LastMessage() { - return last_death_test_message_.c_str(); -} - -void DeathTest::set_last_death_test_message(const String& message) { - last_death_test_message_ = message; -} - -String DeathTest::last_death_test_message_; - -// Provides cross platform implementation for some death functionality. -class DeathTestImpl : public DeathTest { - protected: - DeathTestImpl(const char* a_statement, const RE* a_regex) - : statement_(a_statement), - regex_(a_regex), - spawned_(false), - status_(-1), - outcome_(IN_PROGRESS), - read_fd_(-1), - write_fd_(-1) {} - - // read_fd_ is expected to be closed and cleared by a derived class. - ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } - - void Abort(AbortReason reason); - virtual bool Passed(bool status_ok); - - const char* statement() const { return statement_; } - const RE* regex() const { return regex_; } - bool spawned() const { return spawned_; } - void set_spawned(bool is_spawned) { spawned_ = is_spawned; } - int status() const { return status_; } - void set_status(int a_status) { status_ = a_status; } - DeathTestOutcome outcome() const { return outcome_; } - void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } - int read_fd() const { return read_fd_; } - void set_read_fd(int fd) { read_fd_ = fd; } - int write_fd() const { return write_fd_; } - void set_write_fd(int fd) { write_fd_ = fd; } - - // Called in the parent process only. Reads the result code of the death - // test child process via a pipe, interprets it to set the outcome_ - // member, and closes read_fd_. Outputs diagnostics and terminates in - // case of unexpected codes. - void ReadAndInterpretStatusByte(); - - private: - // The textual content of the code this object is testing. This class - // doesn't own this string and should not attempt to delete it. - const char* const statement_; - // The regular expression which test output must match. DeathTestImpl - // doesn't own this object and should not attempt to delete it. - const RE* const regex_; - // True if the death test child process has been successfully spawned. - bool spawned_; - // The exit status of the child process. - int status_; - // How the death test concluded. - DeathTestOutcome outcome_; - // Descriptor to the read end of the pipe to the child process. It is - // always -1 in the child process. The child keeps its write end of the - // pipe in write_fd_. - int read_fd_; - // Descriptor to the child's write end of the pipe to the parent process. - // It is always -1 in the parent process. The parent keeps its end of the - // pipe in read_fd_. - int write_fd_; -}; - -// Called in the parent process only. Reads the result code of the death -// test child process via a pipe, interprets it to set the outcome_ -// member, and closes read_fd_. Outputs diagnostics and terminates in -// case of unexpected codes. -void DeathTestImpl::ReadAndInterpretStatusByte() { - char flag; - int bytes_read; - - // The read() here blocks until data is available (signifying the - // failure of the death test) or until the pipe is closed (signifying - // its success), so it's okay to call this in the parent before - // the child process has exited. - do { - bytes_read = posix::Read(read_fd(), &flag, 1); - } while (bytes_read == -1 && errno == EINTR); - - if (bytes_read == 0) { - set_outcome(DIED); - } else if (bytes_read == 1) { - switch (flag) { - case kDeathTestReturned: - set_outcome(RETURNED); - break; - case kDeathTestThrew: - set_outcome(THREW); - break; - case kDeathTestLived: - set_outcome(LIVED); - break; - case kDeathTestInternalError: - FailFromInternalError(read_fd()); // Does not return. - break; - default: - GTEST_LOG_(FATAL) << "Death test child process reported " - << "unexpected status byte (" - << static_cast(flag) << ")"; - } - } else { - GTEST_LOG_(FATAL) << "Read from death test child process failed: " - << GetLastErrnoDescription(); - } - GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); - set_read_fd(-1); -} - -// Signals that the death test code which should have exited, didn't. -// Should be called only in a death test child process. -// Writes a status byte to the child's status file descriptor, then -// calls _exit(1). -void DeathTestImpl::Abort(AbortReason reason) { - // The parent process considers the death test to be a failure if - // it finds any data in our pipe. So, here we write a single flag byte - // to the pipe, then exit. - const char status_ch = - reason == TEST_DID_NOT_DIE ? kDeathTestLived : - reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; - - GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); - // We are leaking the descriptor here because on some platforms (i.e., - // when built as Windows DLL), destructors of global objects will still - // run after calling _exit(). On such systems, write_fd_ will be - // indirectly closed from the destructor of UnitTestImpl, causing double - // close if it is also closed here. On debug configurations, double close - // may assert. As there are no in-process buffers to flush here, we are - // relying on the OS to close the descriptor after the process terminates - // when the destructors are not run. - _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) -} - -// Returns an indented copy of stderr output for a death test. -// This makes distinguishing death test output lines from regular log lines -// much easier. -static ::std::string FormatDeathTestOutput(const ::std::string& output) { - ::std::string ret; - for (size_t at = 0; ; ) { - const size_t line_end = output.find('\n', at); - ret += "[ DEATH ] "; - if (line_end == ::std::string::npos) { - ret += output.substr(at); - break; - } - ret += output.substr(at, line_end + 1 - at); - at = line_end + 1; - } - return ret; -} - -// Assesses the success or failure of a death test, using both private -// members which have previously been set, and one argument: -// -// Private data members: -// outcome: An enumeration describing how the death test -// concluded: DIED, LIVED, THREW, or RETURNED. The death test -// fails in the latter three cases. -// status: The exit status of the child process. On *nix, it is in the -// in the format specified by wait(2). On Windows, this is the -// value supplied to the ExitProcess() API or a numeric code -// of the exception that terminated the program. -// regex: A regular expression object to be applied to -// the test's captured standard error output; the death test -// fails if it does not match. -// -// Argument: -// status_ok: true if exit_status is acceptable in the context of -// this particular death test, which fails if it is false -// -// Returns true iff all of the above conditions are met. Otherwise, the -// first failing condition, in the order given above, is the one that is -// reported. Also sets the last death test message string. -bool DeathTestImpl::Passed(bool status_ok) { - if (!spawned()) - return false; - - const String error_message = GetCapturedStderr(); - - bool success = false; - Message buffer; - - buffer << "Death test: " << statement() << "\n"; - switch (outcome()) { - case LIVED: - buffer << " Result: failed to die.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); - break; - case THREW: - buffer << " Result: threw an exception.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); - break; - case RETURNED: - buffer << " Result: illegal return in test statement.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); - break; - case DIED: - if (status_ok) { - const bool matched = RE::PartialMatch(error_message.c_str(), *regex()); - if (matched) { - success = true; - } else { - buffer << " Result: died but not with expected error.\n" - << " Expected: " << regex()->pattern() << "\n" - << "Actual msg:\n" << FormatDeathTestOutput(error_message); - } - } else { - buffer << " Result: died but not with expected exit code:\n" - << " " << ExitSummary(status()) << "\n" - << "Actual msg:\n" << FormatDeathTestOutput(error_message); - } - break; - case IN_PROGRESS: - default: - GTEST_LOG_(FATAL) - << "DeathTest::Passed somehow called before conclusion of test"; - } - - DeathTest::set_last_death_test_message(buffer.GetString()); - return success; -} - -# if GTEST_OS_WINDOWS -// WindowsDeathTest implements death tests on Windows. Due to the -// specifics of starting new processes on Windows, death tests there are -// always threadsafe, and Google Test considers the -// --gtest_death_test_style=fast setting to be equivalent to -// --gtest_death_test_style=threadsafe there. -// -// A few implementation notes: Like the Linux version, the Windows -// implementation uses pipes for child-to-parent communication. But due to -// the specifics of pipes on Windows, some extra steps are required: -// -// 1. The parent creates a communication pipe and stores handles to both -// ends of it. -// 2. The parent starts the child and provides it with the information -// necessary to acquire the handle to the write end of the pipe. -// 3. The child acquires the write end of the pipe and signals the parent -// using a Windows event. -// 4. Now the parent can release the write end of the pipe on its side. If -// this is done before step 3, the object's reference count goes down to -// 0 and it is destroyed, preventing the child from acquiring it. The -// parent now has to release it, or read operations on the read end of -// the pipe will not return when the child terminates. -// 5. The parent reads child's output through the pipe (outcome code and -// any possible error messages) from the pipe, and its stderr and then -// determines whether to fail the test. -// -// Note: to distinguish Win32 API calls from the local method and function -// calls, the former are explicitly resolved in the global namespace. -// -class WindowsDeathTest : public DeathTestImpl { - public: - WindowsDeathTest(const char* a_statement, - const RE* a_regex, - const char* file, - int line) - : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {} - - // All of these virtual functions are inherited from DeathTest. - virtual int Wait(); - virtual TestRole AssumeRole(); - - private: - // The name of the file in which the death test is located. - const char* const file_; - // The line number on which the death test is located. - const int line_; - // Handle to the write end of the pipe to the child process. - AutoHandle write_handle_; - // Child process handle. - AutoHandle child_handle_; - // Event the child process uses to signal the parent that it has - // acquired the handle to the write end of the pipe. After seeing this - // event the parent can release its own handles to make sure its - // ReadFile() calls return when the child terminates. - AutoHandle event_handle_; -}; - -// Waits for the child in a death test to exit, returning its exit -// status, or 0 if no child process exists. As a side effect, sets the -// outcome data member. -int WindowsDeathTest::Wait() { - if (!spawned()) - return 0; - - // Wait until the child either signals that it has acquired the write end - // of the pipe or it dies. - const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; - switch (::WaitForMultipleObjects(2, - wait_handles, - FALSE, // Waits for any of the handles. - INFINITE)) { - case WAIT_OBJECT_0: - case WAIT_OBJECT_0 + 1: - break; - default: - GTEST_DEATH_TEST_CHECK_(false); // Should not get here. - } - - // The child has acquired the write end of the pipe or exited. - // We release the handle on our side and continue. - write_handle_.Reset(); - event_handle_.Reset(); - - ReadAndInterpretStatusByte(); - - // Waits for the child process to exit if it haven't already. This - // returns immediately if the child has already exited, regardless of - // whether previous calls to WaitForMultipleObjects synchronized on this - // handle or not. - GTEST_DEATH_TEST_CHECK_( - WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), - INFINITE)); - DWORD status_code; - GTEST_DEATH_TEST_CHECK_( - ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); - child_handle_.Reset(); - set_status(static_cast(status_code)); - return status(); -} - -// The AssumeRole process for a Windows death test. It creates a child -// process with the same executable as the current process to run the -// death test. The child process is given the --gtest_filter and -// --gtest_internal_run_death_test flags such that it knows to run the -// current death test only. -DeathTest::TestRole WindowsDeathTest::AssumeRole() { - const UnitTestImpl* const impl = GetUnitTestImpl(); - const InternalRunDeathTestFlag* const flag = - impl->internal_run_death_test_flag(); - const TestInfo* const info = impl->current_test_info(); - const int death_test_index = info->result()->death_test_count(); - - if (flag != NULL) { - // ParseInternalRunDeathTestFlag() has performed all the necessary - // processing. - set_write_fd(flag->write_fd()); - return EXECUTE_TEST; - } - - // WindowsDeathTest uses an anonymous pipe to communicate results of - // a death test. - SECURITY_ATTRIBUTES handles_are_inheritable = { - sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; - HANDLE read_handle, write_handle; - GTEST_DEATH_TEST_CHECK_( - ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, - 0) // Default buffer size. - != FALSE); - set_read_fd(::_open_osfhandle(reinterpret_cast(read_handle), - O_RDONLY)); - write_handle_.Reset(write_handle); - event_handle_.Reset(::CreateEvent( - &handles_are_inheritable, - TRUE, // The event will automatically reset to non-signaled state. - FALSE, // The initial state is non-signalled. - NULL)); // The even is unnamed. - GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); - const String filter_flag = String::Format("--%s%s=%s.%s", - GTEST_FLAG_PREFIX_, kFilterFlag, - info->test_case_name(), - info->name()); - const String internal_flag = String::Format( - "--%s%s=%s|%d|%d|%u|%Iu|%Iu", - GTEST_FLAG_PREFIX_, - kInternalRunDeathTestFlag, - file_, line_, - death_test_index, - static_cast(::GetCurrentProcessId()), - // size_t has the same with as pointers on both 32-bit and 64-bit - // Windows platforms. - // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. - reinterpret_cast(write_handle), - reinterpret_cast(event_handle_.Get())); - - char executable_path[_MAX_PATH + 1]; // NOLINT - GTEST_DEATH_TEST_CHECK_( - _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, - executable_path, - _MAX_PATH)); - - String command_line = String::Format("%s %s \"%s\"", - ::GetCommandLineA(), - filter_flag.c_str(), - internal_flag.c_str()); - - DeathTest::set_last_death_test_message(""); - - CaptureStderr(); - // Flush the log buffers since the log streams are shared with the child. - FlushInfoLog(); - - // The child process will share the standard handles with the parent. - STARTUPINFOA startup_info; - memset(&startup_info, 0, sizeof(STARTUPINFO)); - startup_info.dwFlags = STARTF_USESTDHANDLES; - startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); - startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE); - startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); - - PROCESS_INFORMATION process_info; - GTEST_DEATH_TEST_CHECK_(::CreateProcessA( - executable_path, - const_cast(command_line.c_str()), - NULL, // Retuned process handle is not inheritable. - NULL, // Retuned thread handle is not inheritable. - TRUE, // Child inherits all inheritable handles (for write_handle_). - 0x0, // Default creation flags. - NULL, // Inherit the parent's environment. - UnitTest::GetInstance()->original_working_dir(), - &startup_info, - &process_info) != FALSE); - child_handle_.Reset(process_info.hProcess); - ::CloseHandle(process_info.hThread); - set_spawned(true); - return OVERSEE_TEST; -} -# else // We are not on Windows. - -// ForkingDeathTest provides implementations for most of the abstract -// methods of the DeathTest interface. Only the AssumeRole method is -// left undefined. -class ForkingDeathTest : public DeathTestImpl { - public: - ForkingDeathTest(const char* statement, const RE* regex); - - // All of these virtual functions are inherited from DeathTest. - virtual int Wait(); - - protected: - void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } - - private: - // PID of child process during death test; 0 in the child process itself. - pid_t child_pid_; -}; - -// Constructs a ForkingDeathTest. -ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex) - : DeathTestImpl(a_statement, a_regex), - child_pid_(-1) {} - -// Waits for the child in a death test to exit, returning its exit -// status, or 0 if no child process exists. As a side effect, sets the -// outcome data member. -int ForkingDeathTest::Wait() { - if (!spawned()) - return 0; - - ReadAndInterpretStatusByte(); - - int status_value; - GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); - set_status(status_value); - return status_value; -} - -// A concrete death test class that forks, then immediately runs the test -// in the child process. -class NoExecDeathTest : public ForkingDeathTest { - public: - NoExecDeathTest(const char* a_statement, const RE* a_regex) : - ForkingDeathTest(a_statement, a_regex) { } - virtual TestRole AssumeRole(); -}; - -// The AssumeRole process for a fork-and-run death test. It implements a -// straightforward fork, with a simple pipe to transmit the status byte. -DeathTest::TestRole NoExecDeathTest::AssumeRole() { - const size_t thread_count = GetThreadCount(); - if (thread_count != 1) { - GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count); - } - - int pipe_fd[2]; - GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); - - DeathTest::set_last_death_test_message(""); - CaptureStderr(); - // When we fork the process below, the log file buffers are copied, but the - // file descriptors are shared. We flush all log files here so that closing - // the file descriptors in the child process doesn't throw off the - // synchronization between descriptors and buffers in the parent process. - // This is as close to the fork as possible to avoid a race condition in case - // there are multiple threads running before the death test, and another - // thread writes to the log file. - FlushInfoLog(); - - const pid_t child_pid = fork(); - GTEST_DEATH_TEST_CHECK_(child_pid != -1); - set_child_pid(child_pid); - if (child_pid == 0) { - GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0])); - set_write_fd(pipe_fd[1]); - // Redirects all logging to stderr in the child process to prevent - // concurrent writes to the log files. We capture stderr in the parent - // process and append the child process' output to a log. - LogToStderr(); - // Event forwarding to the listeners of event listener API mush be shut - // down in death test subprocesses. - GetUnitTestImpl()->listeners()->SuppressEventForwarding(); - return EXECUTE_TEST; - } else { - GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); - set_read_fd(pipe_fd[0]); - set_spawned(true); - return OVERSEE_TEST; - } -} - -// A concrete death test class that forks and re-executes the main -// program from the beginning, with command-line flags set that cause -// only this specific death test to be run. -class ExecDeathTest : public ForkingDeathTest { - public: - ExecDeathTest(const char* a_statement, const RE* a_regex, - const char* file, int line) : - ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } - virtual TestRole AssumeRole(); - private: - // The name of the file in which the death test is located. - const char* const file_; - // The line number on which the death test is located. - const int line_; -}; - -// Utility class for accumulating command-line arguments. -class Arguments { - public: - Arguments() { - args_.push_back(NULL); - } - - ~Arguments() { - for (std::vector::iterator i = args_.begin(); i != args_.end(); - ++i) { - free(*i); - } - } - void AddArgument(const char* argument) { - args_.insert(args_.end() - 1, posix::StrDup(argument)); - } - - template - void AddArguments(const ::std::vector& arguments) { - for (typename ::std::vector::const_iterator i = arguments.begin(); - i != arguments.end(); - ++i) { - args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); - } - } - char* const* Argv() { - return &args_[0]; - } - private: - std::vector args_; -}; - -// A struct that encompasses the arguments to the child process of a -// threadsafe-style death test process. -struct ExecDeathTestArgs { - char* const* argv; // Command-line arguments for the child's call to exec - int close_fd; // File descriptor to close; the read end of a pipe -}; - -# if GTEST_OS_MAC -inline char** GetEnviron() { - // When Google Test is built as a framework on MacOS X, the environ variable - // is unavailable. Apple's documentation (man environ) recommends using - // _NSGetEnviron() instead. - return *_NSGetEnviron(); -} -# else -// Some POSIX platforms expect you to declare environ. extern "C" makes -// it reside in the global namespace. -extern "C" char** environ; -inline char** GetEnviron() { return environ; } -# endif // GTEST_OS_MAC - -// The main function for a threadsafe-style death test child process. -// This function is called in a clone()-ed process and thus must avoid -// any potentially unsafe operations like malloc or libc functions. -static int ExecDeathTestChildMain(void* child_arg) { - ExecDeathTestArgs* const args = static_cast(child_arg); - GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd)); - - // We need to execute the test program in the same environment where - // it was originally invoked. Therefore we change to the original - // working directory first. - const char* const original_dir = - UnitTest::GetInstance()->original_working_dir(); - // We can safely call chdir() as it's a direct system call. - if (chdir(original_dir) != 0) { - DeathTestAbort(String::Format("chdir(\"%s\") failed: %s", - original_dir, - GetLastErrnoDescription().c_str())); - return EXIT_FAILURE; - } - - // We can safely call execve() as it's a direct system call. We - // cannot use execvp() as it's a libc function and thus potentially - // unsafe. Since execve() doesn't search the PATH, the user must - // invoke the test program via a valid path that contains at least - // one path separator. - execve(args->argv[0], args->argv, GetEnviron()); - DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s", - args->argv[0], - original_dir, - GetLastErrnoDescription().c_str())); - return EXIT_FAILURE; -} - -// Two utility routines that together determine the direction the stack -// grows. -// This could be accomplished more elegantly by a single recursive -// function, but we want to guard against the unlikely possibility of -// a smart compiler optimizing the recursion away. -// -// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining -// StackLowerThanAddress into StackGrowsDown, which then doesn't give -// correct answer. -bool StackLowerThanAddress(const void* ptr) GTEST_NO_INLINE_; -bool StackLowerThanAddress(const void* ptr) { - int dummy; - return &dummy < ptr; -} - -bool StackGrowsDown() { - int dummy; - return StackLowerThanAddress(&dummy); -} - -// A threadsafe implementation of fork(2) for threadsafe-style death tests -// that uses clone(2). It dies with an error message if anything goes -// wrong. -static pid_t ExecDeathTestFork(char* const* argv, int close_fd) { - ExecDeathTestArgs args = { argv, close_fd }; - pid_t child_pid = -1; - -# if GTEST_HAS_CLONE - const bool use_fork = GTEST_FLAG(death_test_use_fork); - - if (!use_fork) { - static const bool stack_grows_down = StackGrowsDown(); - const size_t stack_size = getpagesize(); - // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. - void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, - MAP_ANON | MAP_PRIVATE, -1, 0); - GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); - void* const stack_top = - static_cast(stack) + (stack_grows_down ? stack_size : 0); - - child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); - - GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); - } -# else - const bool use_fork = true; -# endif // GTEST_HAS_CLONE - - if (use_fork && (child_pid = fork()) == 0) { - ExecDeathTestChildMain(&args); - _exit(0); - } - - GTEST_DEATH_TEST_CHECK_(child_pid != -1); - return child_pid; -} - -// The AssumeRole process for a fork-and-exec death test. It re-executes the -// main program from the beginning, setting the --gtest_filter -// and --gtest_internal_run_death_test flags to cause only the current -// death test to be re-run. -DeathTest::TestRole ExecDeathTest::AssumeRole() { - const UnitTestImpl* const impl = GetUnitTestImpl(); - const InternalRunDeathTestFlag* const flag = - impl->internal_run_death_test_flag(); - const TestInfo* const info = impl->current_test_info(); - const int death_test_index = info->result()->death_test_count(); - - if (flag != NULL) { - set_write_fd(flag->write_fd()); - return EXECUTE_TEST; - } - - int pipe_fd[2]; - GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); - // Clear the close-on-exec flag on the write end of the pipe, lest - // it be closed when the child process does an exec: - GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); - - const String filter_flag = - String::Format("--%s%s=%s.%s", - GTEST_FLAG_PREFIX_, kFilterFlag, - info->test_case_name(), info->name()); - const String internal_flag = - String::Format("--%s%s=%s|%d|%d|%d", - GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag, - file_, line_, death_test_index, pipe_fd[1]); - Arguments args; - args.AddArguments(GetArgvs()); - args.AddArgument(filter_flag.c_str()); - args.AddArgument(internal_flag.c_str()); - - DeathTest::set_last_death_test_message(""); - - CaptureStderr(); - // See the comment in NoExecDeathTest::AssumeRole for why the next line - // is necessary. - FlushInfoLog(); - - const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]); - GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); - set_child_pid(child_pid); - set_read_fd(pipe_fd[0]); - set_spawned(true); - return OVERSEE_TEST; -} - -# endif // !GTEST_OS_WINDOWS - -// Creates a concrete DeathTest-derived class that depends on the -// --gtest_death_test_style flag, and sets the pointer pointed to -// by the "test" argument to its address. If the test should be -// skipped, sets that pointer to NULL. Returns true, unless the -// flag is set to an invalid value. -bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, - const char* file, int line, - DeathTest** test) { - UnitTestImpl* const impl = GetUnitTestImpl(); - const InternalRunDeathTestFlag* const flag = - impl->internal_run_death_test_flag(); - const int death_test_index = impl->current_test_info() - ->increment_death_test_count(); - - if (flag != NULL) { - if (death_test_index > flag->index()) { - DeathTest::set_last_death_test_message(String::Format( - "Death test count (%d) somehow exceeded expected maximum (%d)", - death_test_index, flag->index())); - return false; - } - - if (!(flag->file() == file && flag->line() == line && - flag->index() == death_test_index)) { - *test = NULL; - return true; - } - } - -# if GTEST_OS_WINDOWS - - if (GTEST_FLAG(death_test_style) == "threadsafe" || - GTEST_FLAG(death_test_style) == "fast") { - *test = new WindowsDeathTest(statement, regex, file, line); - } - -# else - - if (GTEST_FLAG(death_test_style) == "threadsafe") { - *test = new ExecDeathTest(statement, regex, file, line); - } else if (GTEST_FLAG(death_test_style) == "fast") { - *test = new NoExecDeathTest(statement, regex); - } - -# endif // GTEST_OS_WINDOWS - - else { // NOLINT - this is more readable than unbalanced brackets inside #if. - DeathTest::set_last_death_test_message(String::Format( - "Unknown death test style \"%s\" encountered", - GTEST_FLAG(death_test_style).c_str())); - return false; - } - - return true; -} - -// Splits a given string on a given delimiter, populating a given -// vector with the fields. GTEST_HAS_DEATH_TEST implies that we have -// ::std::string, so we can use it here. -static void SplitString(const ::std::string& str, char delimiter, - ::std::vector< ::std::string>* dest) { - ::std::vector< ::std::string> parsed; - ::std::string::size_type pos = 0; - while (::testing::internal::AlwaysTrue()) { - const ::std::string::size_type colon = str.find(delimiter, pos); - if (colon == ::std::string::npos) { - parsed.push_back(str.substr(pos)); - break; - } else { - parsed.push_back(str.substr(pos, colon - pos)); - pos = colon + 1; - } - } - dest->swap(parsed); -} - -# if GTEST_OS_WINDOWS -// Recreates the pipe and event handles from the provided parameters, -// signals the event, and returns a file descriptor wrapped around the pipe -// handle. This function is called in the child process only. -int GetStatusFileDescriptor(unsigned int parent_process_id, - size_t write_handle_as_size_t, - size_t event_handle_as_size_t) { - AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, - FALSE, // Non-inheritable. - parent_process_id)); - if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { - DeathTestAbort(String::Format("Unable to open parent process %u", - parent_process_id)); - } - - // TODO(vladl@google.com): Replace the following check with a - // compile-time assertion when available. - GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); - - const HANDLE write_handle = - reinterpret_cast(write_handle_as_size_t); - HANDLE dup_write_handle; - - // The newly initialized handle is accessible only in in the parent - // process. To obtain one accessible within the child, we need to use - // DuplicateHandle. - if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, - ::GetCurrentProcess(), &dup_write_handle, - 0x0, // Requested privileges ignored since - // DUPLICATE_SAME_ACCESS is used. - FALSE, // Request non-inheritable handler. - DUPLICATE_SAME_ACCESS)) { - DeathTestAbort(String::Format( - "Unable to duplicate the pipe handle %Iu from the parent process %u", - write_handle_as_size_t, parent_process_id)); - } - - const HANDLE event_handle = reinterpret_cast(event_handle_as_size_t); - HANDLE dup_event_handle; - - if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, - ::GetCurrentProcess(), &dup_event_handle, - 0x0, - FALSE, - DUPLICATE_SAME_ACCESS)) { - DeathTestAbort(String::Format( - "Unable to duplicate the event handle %Iu from the parent process %u", - event_handle_as_size_t, parent_process_id)); - } - - const int write_fd = - ::_open_osfhandle(reinterpret_cast(dup_write_handle), O_APPEND); - if (write_fd == -1) { - DeathTestAbort(String::Format( - "Unable to convert pipe handle %Iu to a file descriptor", - write_handle_as_size_t)); - } - - // Signals the parent that the write end of the pipe has been acquired - // so the parent can release its own write end. - ::SetEvent(dup_event_handle); - - return write_fd; -} -# endif // GTEST_OS_WINDOWS - -// Returns a newly created InternalRunDeathTestFlag object with fields -// initialized from the GTEST_FLAG(internal_run_death_test) flag if -// the flag is specified; otherwise returns NULL. -InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { - if (GTEST_FLAG(internal_run_death_test) == "") return NULL; - - // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we - // can use it here. - int line = -1; - int index = -1; - ::std::vector< ::std::string> fields; - SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); - int write_fd = -1; - -# if GTEST_OS_WINDOWS - - unsigned int parent_process_id = 0; - size_t write_handle_as_size_t = 0; - size_t event_handle_as_size_t = 0; - - if (fields.size() != 6 - || !ParseNaturalNumber(fields[1], &line) - || !ParseNaturalNumber(fields[2], &index) - || !ParseNaturalNumber(fields[3], &parent_process_id) - || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) - || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { - DeathTestAbort(String::Format( - "Bad --gtest_internal_run_death_test flag: %s", - GTEST_FLAG(internal_run_death_test).c_str())); - } - write_fd = GetStatusFileDescriptor(parent_process_id, - write_handle_as_size_t, - event_handle_as_size_t); -# else - - if (fields.size() != 4 - || !ParseNaturalNumber(fields[1], &line) - || !ParseNaturalNumber(fields[2], &index) - || !ParseNaturalNumber(fields[3], &write_fd)) { - DeathTestAbort(String::Format( - "Bad --gtest_internal_run_death_test flag: %s", - GTEST_FLAG(internal_run_death_test).c_str())); - } - -# endif // GTEST_OS_WINDOWS - - return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); -} - -} // namespace internal - -#endif // GTEST_HAS_DEATH_TEST - -} // namespace testing -// Copyright 2008, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Authors: keith.ray@gmail.com (Keith Ray) - - -#include - -#if GTEST_OS_WINDOWS_MOBILE -# include -#elif GTEST_OS_WINDOWS -# include -# include -#elif GTEST_OS_SYMBIAN || GTEST_OS_NACL -// Symbian OpenC and NaCl have PATH_MAX in sys/syslimits.h -# include -#else -# include -# include // Some Linux distributions define PATH_MAX here. -#endif // GTEST_OS_WINDOWS_MOBILE - -#if GTEST_OS_WINDOWS -# define GTEST_PATH_MAX_ _MAX_PATH -#elif defined(PATH_MAX) -# define GTEST_PATH_MAX_ PATH_MAX -#elif defined(_XOPEN_PATH_MAX) -# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX -#else -# define GTEST_PATH_MAX_ _POSIX_PATH_MAX -#endif // GTEST_OS_WINDOWS - - -namespace testing { -namespace internal { - -#if GTEST_OS_WINDOWS -// On Windows, '\\' is the standard path separator, but many tools and the -// Windows API also accept '/' as an alternate path separator. Unless otherwise -// noted, a file path can contain either kind of path separators, or a mixture -// of them. -const char kPathSeparator = '\\'; -const char kAlternatePathSeparator = '/'; -const char kPathSeparatorString[] = "\\"; -const char kAlternatePathSeparatorString[] = "/"; -# if GTEST_OS_WINDOWS_MOBILE -// Windows CE doesn't have a current directory. You should not use -// the current directory in tests on Windows CE, but this at least -// provides a reasonable fallback. -const char kCurrentDirectoryString[] = "\\"; -// Windows CE doesn't define INVALID_FILE_ATTRIBUTES -const DWORD kInvalidFileAttributes = 0xffffffff; -# else -const char kCurrentDirectoryString[] = ".\\"; -# endif // GTEST_OS_WINDOWS_MOBILE -#else -const char kPathSeparator = '/'; -const char kPathSeparatorString[] = "/"; -const char kCurrentDirectoryString[] = "./"; -#endif // GTEST_OS_WINDOWS - -// Returns whether the given character is a valid path separator. -static bool IsPathSeparator(char c) { -#if GTEST_HAS_ALT_PATH_SEP_ - return (c == kPathSeparator) || (c == kAlternatePathSeparator); -#else - return c == kPathSeparator; -#endif -} - -// Returns the current working directory, or "" if unsuccessful. -FilePath FilePath::GetCurrentDir() { -#if GTEST_OS_WINDOWS_MOBILE - // Windows CE doesn't have a current directory, so we just return - // something reasonable. - return FilePath(kCurrentDirectoryString); -#elif GTEST_OS_WINDOWS - char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; - return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); -#else - char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; - return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); -#endif // GTEST_OS_WINDOWS_MOBILE -} - -// Returns a copy of the FilePath with the case-insensitive extension removed. -// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns -// FilePath("dir/file"). If a case-insensitive extension is not -// found, returns a copy of the original FilePath. -FilePath FilePath::RemoveExtension(const char* extension) const { - String dot_extension(String::Format(".%s", extension)); - if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) { - return FilePath(String(pathname_.c_str(), pathname_.length() - 4)); - } - return *this; -} - -// Returns a pointer to the last occurence of a valid path separator in -// the FilePath. On Windows, for example, both '/' and '\' are valid path -// separators. Returns NULL if no path separator was found. -const char* FilePath::FindLastPathSeparator() const { - const char* const last_sep = strrchr(c_str(), kPathSeparator); -#if GTEST_HAS_ALT_PATH_SEP_ - const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); - // Comparing two pointers of which only one is NULL is undefined. - if (last_alt_sep != NULL && - (last_sep == NULL || last_alt_sep > last_sep)) { - return last_alt_sep; - } -#endif - return last_sep; -} - -// Returns a copy of the FilePath with the directory part removed. -// Example: FilePath("path/to/file").RemoveDirectoryName() returns -// FilePath("file"). If there is no directory part ("just_a_file"), it returns -// the FilePath unmodified. If there is no file part ("just_a_dir/") it -// returns an empty FilePath (""). -// On Windows platform, '\' is the path separator, otherwise it is '/'. -FilePath FilePath::RemoveDirectoryName() const { - const char* const last_sep = FindLastPathSeparator(); - return last_sep ? FilePath(String(last_sep + 1)) : *this; -} - -// RemoveFileName returns the directory path with the filename removed. -// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". -// If the FilePath is "a_file" or "/a_file", RemoveFileName returns -// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does -// not have a file, like "just/a/dir/", it returns the FilePath unmodified. -// On Windows platform, '\' is the path separator, otherwise it is '/'. -FilePath FilePath::RemoveFileName() const { - const char* const last_sep = FindLastPathSeparator(); - String dir; - if (last_sep) { - dir = String(c_str(), last_sep + 1 - c_str()); - } else { - dir = kCurrentDirectoryString; - } - return FilePath(dir); -} - -// Helper functions for naming files in a directory for xml output. - -// Given directory = "dir", base_name = "test", number = 0, -// extension = "xml", returns "dir/test.xml". If number is greater -// than zero (e.g., 12), returns "dir/test_12.xml". -// On Windows platform, uses \ as the separator rather than /. -FilePath FilePath::MakeFileName(const FilePath& directory, - const FilePath& base_name, - int number, - const char* extension) { - String file; - if (number == 0) { - file = String::Format("%s.%s", base_name.c_str(), extension); - } else { - file = String::Format("%s_%d.%s", base_name.c_str(), number, extension); - } - return ConcatPaths(directory, FilePath(file)); -} - -// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml". -// On Windows, uses \ as the separator rather than /. -FilePath FilePath::ConcatPaths(const FilePath& directory, - const FilePath& relative_path) { - if (directory.IsEmpty()) - return relative_path; - const FilePath dir(directory.RemoveTrailingPathSeparator()); - return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator, - relative_path.c_str())); -} - -// Returns true if pathname describes something findable in the file-system, -// either a file, directory, or whatever. -bool FilePath::FileOrDirectoryExists() const { -#if GTEST_OS_WINDOWS_MOBILE - LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); - const DWORD attributes = GetFileAttributes(unicode); - delete [] unicode; - return attributes != kInvalidFileAttributes; -#else - posix::StatStruct file_stat; - return posix::Stat(pathname_.c_str(), &file_stat) == 0; -#endif // GTEST_OS_WINDOWS_MOBILE -} - -// Returns true if pathname describes a directory in the file-system -// that exists. -bool FilePath::DirectoryExists() const { - bool result = false; -#if GTEST_OS_WINDOWS - // Don't strip off trailing separator if path is a root directory on - // Windows (like "C:\\"). - const FilePath& path(IsRootDirectory() ? *this : - RemoveTrailingPathSeparator()); -#else - const FilePath& path(*this); -#endif - -#if GTEST_OS_WINDOWS_MOBILE - LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); - const DWORD attributes = GetFileAttributes(unicode); - delete [] unicode; - if ((attributes != kInvalidFileAttributes) && - (attributes & FILE_ATTRIBUTE_DIRECTORY)) { - result = true; - } -#else - posix::StatStruct file_stat; - result = posix::Stat(path.c_str(), &file_stat) == 0 && - posix::IsDir(file_stat); -#endif // GTEST_OS_WINDOWS_MOBILE - - return result; -} - -// Returns true if pathname describes a root directory. (Windows has one -// root directory per disk drive.) -bool FilePath::IsRootDirectory() const { -#if GTEST_OS_WINDOWS - // TODO(wan@google.com): on Windows a network share like - // \\server\share can be a root directory, although it cannot be the - // current directory. Handle this properly. - return pathname_.length() == 3 && IsAbsolutePath(); -#else - return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); -#endif -} - -// Returns true if pathname describes an absolute path. -bool FilePath::IsAbsolutePath() const { - const char* const name = pathname_.c_str(); -#if GTEST_OS_WINDOWS - return pathname_.length() >= 3 && - ((name[0] >= 'a' && name[0] <= 'z') || - (name[0] >= 'A' && name[0] <= 'Z')) && - name[1] == ':' && - IsPathSeparator(name[2]); -#else - return IsPathSeparator(name[0]); -#endif -} - -// Returns a pathname for a file that does not currently exist. The pathname -// will be directory/base_name.extension or -// directory/base_name_.extension if directory/base_name.extension -// already exists. The number will be incremented until a pathname is found -// that does not already exist. -// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. -// There could be a race condition if two or more processes are calling this -// function at the same time -- they could both pick the same filename. -FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, - const FilePath& base_name, - const char* extension) { - FilePath full_pathname; - int number = 0; - do { - full_pathname.Set(MakeFileName(directory, base_name, number++, extension)); - } while (full_pathname.FileOrDirectoryExists()); - return full_pathname; -} - -// Returns true if FilePath ends with a path separator, which indicates that -// it is intended to represent a directory. Returns false otherwise. -// This does NOT check that a directory (or file) actually exists. -bool FilePath::IsDirectory() const { - return !pathname_.empty() && - IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); -} - -// Create directories so that path exists. Returns true if successful or if -// the directories already exist; returns false if unable to create directories -// for any reason. -bool FilePath::CreateDirectoriesRecursively() const { - if (!this->IsDirectory()) { - return false; - } - - if (pathname_.length() == 0 || this->DirectoryExists()) { - return true; - } - - const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName()); - return parent.CreateDirectoriesRecursively() && this->CreateFolder(); -} - -// Create the directory so that path exists. Returns true if successful or -// if the directory already exists; returns false if unable to create the -// directory for any reason, including if the parent directory does not -// exist. Not named "CreateDirectory" because that's a macro on Windows. -bool FilePath::CreateFolder() const { -#if GTEST_OS_WINDOWS_MOBILE - FilePath removed_sep(this->RemoveTrailingPathSeparator()); - LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); - int result = CreateDirectory(unicode, NULL) ? 0 : -1; - delete [] unicode; -#elif GTEST_OS_WINDOWS - int result = _mkdir(pathname_.c_str()); -#else - int result = mkdir(pathname_.c_str(), 0777); -#endif // GTEST_OS_WINDOWS_MOBILE - - if (result == -1) { - return this->DirectoryExists(); // An error is OK if the directory exists. - } - return true; // No error. -} - -// If input name has a trailing separator character, remove it and return the -// name, otherwise return the name string unmodified. -// On Windows platform, uses \ as the separator, other platforms use /. -FilePath FilePath::RemoveTrailingPathSeparator() const { - return IsDirectory() - ? FilePath(String(pathname_.c_str(), pathname_.length() - 1)) - : *this; -} - -// Removes any redundant separators that might be in the pathname. -// For example, "bar///foo" becomes "bar/foo". Does not eliminate other -// redundancies that might be in a pathname involving "." or "..". -// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share). -void FilePath::Normalize() { - if (pathname_.c_str() == NULL) { - pathname_ = ""; - return; - } - const char* src = pathname_.c_str(); - char* const dest = new char[pathname_.length() + 1]; - char* dest_ptr = dest; - memset(dest_ptr, 0, pathname_.length() + 1); - - while (*src != '\0') { - *dest_ptr = *src; - if (!IsPathSeparator(*src)) { - src++; - } else { -#if GTEST_HAS_ALT_PATH_SEP_ - if (*dest_ptr == kAlternatePathSeparator) { - *dest_ptr = kPathSeparator; - } -#endif - while (IsPathSeparator(*src)) - src++; - } - dest_ptr++; - } - *dest_ptr = '\0'; - pathname_ = dest; - delete[] dest; -} - -} // namespace internal -} // namespace testing -// Copyright 2008, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) - - -#include -#include -#include -#include - -#if GTEST_OS_WINDOWS_MOBILE -# include // For TerminateProcess() -#elif GTEST_OS_WINDOWS -# include -# include -#else -# include -#endif // GTEST_OS_WINDOWS_MOBILE - -#if GTEST_OS_MAC -# include -# include -# include -#endif // GTEST_OS_MAC - - -// Indicates that this translation unit is part of Google Test's -// implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. -#define GTEST_IMPLEMENTATION_ 1 -#undef GTEST_IMPLEMENTATION_ - -namespace testing { -namespace internal { - -#if defined(_MSC_VER) || defined(__BORLANDC__) -// MSVC and C++Builder do not provide a definition of STDERR_FILENO. -const int kStdOutFileno = 1; -const int kStdErrFileno = 2; -#else -const int kStdOutFileno = STDOUT_FILENO; -const int kStdErrFileno = STDERR_FILENO; -#endif // _MSC_VER - -#if GTEST_OS_MAC - -// Returns the number of threads running in the process, or 0 to indicate that -// we cannot detect it. -size_t GetThreadCount() { - const task_t task = mach_task_self(); - mach_msg_type_number_t thread_count; - thread_act_array_t thread_list; - const kern_return_t status = task_threads(task, &thread_list, &thread_count); - if (status == KERN_SUCCESS) { - // task_threads allocates resources in thread_list and we need to free them - // to avoid leaks. - vm_deallocate(task, - reinterpret_cast(thread_list), - sizeof(thread_t) * thread_count); - return static_cast(thread_count); - } else { - return 0; - } -} - -#else - -size_t GetThreadCount() { - // There's no portable way to detect the number of threads, so we just - // return 0 to indicate that we cannot detect it. - return 0; -} - -#endif // GTEST_OS_MAC - -#if GTEST_USES_POSIX_RE - -// Implements RE. Currently only needed for death tests. - -RE::~RE() { - if (is_valid_) { - // regfree'ing an invalid regex might crash because the content - // of the regex is undefined. Since the regex's are essentially - // the same, one cannot be valid (or invalid) without the other - // being so too. - regfree(&partial_regex_); - regfree(&full_regex_); - } - free(const_cast(pattern_)); -} - -// Returns true iff regular expression re matches the entire str. -bool RE::FullMatch(const char* str, const RE& re) { - if (!re.is_valid_) return false; - - regmatch_t match; - return regexec(&re.full_regex_, str, 1, &match, 0) == 0; -} - -// Returns true iff regular expression re matches a substring of str -// (including str itself). -bool RE::PartialMatch(const char* str, const RE& re) { - if (!re.is_valid_) return false; - - regmatch_t match; - return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; -} - -// Initializes an RE from its string representation. -void RE::Init(const char* regex) { - pattern_ = posix::StrDup(regex); - - // Reserves enough bytes to hold the regular expression used for a - // full match. - const size_t full_regex_len = strlen(regex) + 10; - char* const full_pattern = new char[full_regex_len]; - - snprintf(full_pattern, full_regex_len, "^(%s)$", regex); - is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; - // We want to call regcomp(&partial_regex_, ...) even if the - // previous expression returns false. Otherwise partial_regex_ may - // not be properly initialized can may cause trouble when it's - // freed. - // - // Some implementation of POSIX regex (e.g. on at least some - // versions of Cygwin) doesn't accept the empty string as a valid - // regex. We change it to an equivalent form "()" to be safe. - if (is_valid_) { - const char* const partial_regex = (*regex == '\0') ? "()" : regex; - is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; - } - EXPECT_TRUE(is_valid_) - << "Regular expression \"" << regex - << "\" is not a valid POSIX Extended regular expression."; - - delete[] full_pattern; -} - -#elif GTEST_USES_SIMPLE_RE - -// Returns true iff ch appears anywhere in str (excluding the -// terminating '\0' character). -bool IsInSet(char ch, const char* str) { - return ch != '\0' && strchr(str, ch) != NULL; -} - -// Returns true iff ch belongs to the given classification. Unlike -// similar functions in , these aren't affected by the -// current locale. -bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } -bool IsAsciiPunct(char ch) { - return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); -} -bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } -bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } -bool IsAsciiWordChar(char ch) { - return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || - ('0' <= ch && ch <= '9') || ch == '_'; -} - -// Returns true iff "\\c" is a supported escape sequence. -bool IsValidEscape(char c) { - return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); -} - -// Returns true iff the given atom (specified by escaped and pattern) -// matches ch. The result is undefined if the atom is invalid. -bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { - if (escaped) { // "\\p" where p is pattern_char. - switch (pattern_char) { - case 'd': return IsAsciiDigit(ch); - case 'D': return !IsAsciiDigit(ch); - case 'f': return ch == '\f'; - case 'n': return ch == '\n'; - case 'r': return ch == '\r'; - case 's': return IsAsciiWhiteSpace(ch); - case 'S': return !IsAsciiWhiteSpace(ch); - case 't': return ch == '\t'; - case 'v': return ch == '\v'; - case 'w': return IsAsciiWordChar(ch); - case 'W': return !IsAsciiWordChar(ch); - } - return IsAsciiPunct(pattern_char) && pattern_char == ch; - } - - return (pattern_char == '.' && ch != '\n') || pattern_char == ch; -} - -// Helper function used by ValidateRegex() to format error messages. -String FormatRegexSyntaxError(const char* regex, int index) { - return (Message() << "Syntax error at index " << index - << " in simple regular expression \"" << regex << "\": ").GetString(); -} - -// Generates non-fatal failures and returns false if regex is invalid; -// otherwise returns true. -bool ValidateRegex(const char* regex) { - if (regex == NULL) { - // TODO(wan@google.com): fix the source file location in the - // assertion failures to match where the regex is used in user - // code. - ADD_FAILURE() << "NULL is not a valid simple regular expression."; - return false; - } - - bool is_valid = true; - - // True iff ?, *, or + can follow the previous atom. - bool prev_repeatable = false; - for (int i = 0; regex[i]; i++) { - if (regex[i] == '\\') { // An escape sequence - i++; - if (regex[i] == '\0') { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) - << "'\\' cannot appear at the end."; - return false; - } - - if (!IsValidEscape(regex[i])) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) - << "invalid escape sequence \"\\" << regex[i] << "\"."; - is_valid = false; - } - prev_repeatable = true; - } else { // Not an escape sequence. - const char ch = regex[i]; - - if (ch == '^' && i > 0) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'^' can only appear at the beginning."; - is_valid = false; - } else if (ch == '$' && regex[i + 1] != '\0') { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'$' can only appear at the end."; - is_valid = false; - } else if (IsInSet(ch, "()[]{}|")) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'" << ch << "' is unsupported."; - is_valid = false; - } else if (IsRepeat(ch) && !prev_repeatable) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'" << ch << "' can only follow a repeatable token."; - is_valid = false; - } - - prev_repeatable = !IsInSet(ch, "^$?*+"); - } - } - - return is_valid; -} - -// Matches a repeated regex atom followed by a valid simple regular -// expression. The regex atom is defined as c if escaped is false, -// or \c otherwise. repeat is the repetition meta character (?, *, -// or +). The behavior is undefined if str contains too many -// characters to be indexable by size_t, in which case the test will -// probably time out anyway. We are fine with this limitation as -// std::string has it too. -bool MatchRepetitionAndRegexAtHead( - bool escaped, char c, char repeat, const char* regex, - const char* str) { - const size_t min_count = (repeat == '+') ? 1 : 0; - const size_t max_count = (repeat == '?') ? 1 : - static_cast(-1) - 1; - // We cannot call numeric_limits::max() as it conflicts with the - // max() macro on Windows. - - for (size_t i = 0; i <= max_count; ++i) { - // We know that the atom matches each of the first i characters in str. - if (i >= min_count && MatchRegexAtHead(regex, str + i)) { - // We have enough matches at the head, and the tail matches too. - // Since we only care about *whether* the pattern matches str - // (as opposed to *how* it matches), there is no need to find a - // greedy match. - return true; - } - if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) - return false; - } - return false; -} - -// Returns true iff regex matches a prefix of str. regex must be a -// valid simple regular expression and not start with "^", or the -// result is undefined. -bool MatchRegexAtHead(const char* regex, const char* str) { - if (*regex == '\0') // An empty regex matches a prefix of anything. - return true; - - // "$" only matches the end of a string. Note that regex being - // valid guarantees that there's nothing after "$" in it. - if (*regex == '$') - return *str == '\0'; - - // Is the first thing in regex an escape sequence? - const bool escaped = *regex == '\\'; - if (escaped) - ++regex; - if (IsRepeat(regex[1])) { - // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so - // here's an indirect recursion. It terminates as the regex gets - // shorter in each recursion. - return MatchRepetitionAndRegexAtHead( - escaped, regex[0], regex[1], regex + 2, str); - } else { - // regex isn't empty, isn't "$", and doesn't start with a - // repetition. We match the first atom of regex with the first - // character of str and recurse. - return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && - MatchRegexAtHead(regex + 1, str + 1); - } -} - -// Returns true iff regex matches any substring of str. regex must be -// a valid simple regular expression, or the result is undefined. -// -// The algorithm is recursive, but the recursion depth doesn't exceed -// the regex length, so we won't need to worry about running out of -// stack space normally. In rare cases the time complexity can be -// exponential with respect to the regex length + the string length, -// but usually it's must faster (often close to linear). -bool MatchRegexAnywhere(const char* regex, const char* str) { - if (regex == NULL || str == NULL) - return false; - - if (*regex == '^') - return MatchRegexAtHead(regex + 1, str); - - // A successful match can be anywhere in str. - do { - if (MatchRegexAtHead(regex, str)) - return true; - } while (*str++ != '\0'); - return false; -} - -// Implements the RE class. - -RE::~RE() { - free(const_cast(pattern_)); - free(const_cast(full_pattern_)); -} - -// Returns true iff regular expression re matches the entire str. -bool RE::FullMatch(const char* str, const RE& re) { - return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); -} - -// Returns true iff regular expression re matches a substring of str -// (including str itself). -bool RE::PartialMatch(const char* str, const RE& re) { - return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); -} - -// Initializes an RE from its string representation. -void RE::Init(const char* regex) { - pattern_ = full_pattern_ = NULL; - if (regex != NULL) { - pattern_ = posix::StrDup(regex); - } - - is_valid_ = ValidateRegex(regex); - if (!is_valid_) { - // No need to calculate the full pattern when the regex is invalid. - return; - } - - const size_t len = strlen(regex); - // Reserves enough bytes to hold the regular expression used for a - // full match: we need space to prepend a '^', append a '$', and - // terminate the string with '\0'. - char* buffer = static_cast(malloc(len + 3)); - full_pattern_ = buffer; - - if (*regex != '^') - *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. - - // We don't use snprintf or strncpy, as they trigger a warning when - // compiled with VC++ 8.0. - memcpy(buffer, regex, len); - buffer += len; - - if (len == 0 || regex[len - 1] != '$') - *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. - - *buffer = '\0'; -} - -#endif // GTEST_USES_POSIX_RE - -const char kUnknownFile[] = "unknown file"; - -// Formats a source file path and a line number as they would appear -// in an error message from the compiler used to compile this code. -GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { - const char* const file_name = file == NULL ? kUnknownFile : file; - - if (line < 0) { - return String::Format("%s:", file_name).c_str(); - } -#ifdef _MSC_VER - return String::Format("%s(%d):", file_name, line).c_str(); -#else - return String::Format("%s:%d:", file_name, line).c_str(); -#endif // _MSC_VER -} - -// Formats a file location for compiler-independent XML output. -// Although this function is not platform dependent, we put it next to -// FormatFileLocation in order to contrast the two functions. -// Note that FormatCompilerIndependentFileLocation() does NOT append colon -// to the file location it produces, unlike FormatFileLocation(). -GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( - const char* file, int line) { - const char* const file_name = file == NULL ? kUnknownFile : file; - - if (line < 0) - return file_name; - else - return String::Format("%s:%d", file_name, line).c_str(); -} - - -GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) - : severity_(severity) { - const char* const marker = - severity == GTEST_INFO ? "[ INFO ]" : - severity == GTEST_WARNING ? "[WARNING]" : - severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; - GetStream() << ::std::endl << marker << " " - << FormatFileLocation(file, line).c_str() << ": "; -} - -// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. -GTestLog::~GTestLog() { - GetStream() << ::std::endl; - if (severity_ == GTEST_FATAL) { - fflush(stderr); - posix::Abort(); - } -} -// Disable Microsoft deprecation warnings for POSIX functions called from -// this class (creat, dup, dup2, and close) -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable: 4996) -#endif // _MSC_VER - -#if GTEST_HAS_STREAM_REDIRECTION - -// Object that captures an output stream (stdout/stderr). -class CapturedStream { - public: - // The ctor redirects the stream to a temporary file. - CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { - -# if GTEST_OS_WINDOWS - char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT - char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT - - ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); - const UINT success = ::GetTempFileNameA(temp_dir_path, - "gtest_redir", - 0, // Generate unique file name. - temp_file_path); - GTEST_CHECK_(success != 0) - << "Unable to create a temporary file in " << temp_dir_path; - const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); - GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " - << temp_file_path; - filename_ = temp_file_path; -# else - // There's no guarantee that a test has write access to the - // current directory, so we create the temporary file in the /tmp - // directory instead. - char name_template[] = "/tmp/captured_stream.XXXXXX"; - const int captured_fd = mkstemp(name_template); - filename_ = name_template; -# endif // GTEST_OS_WINDOWS - fflush(NULL); - dup2(captured_fd, fd_); - close(captured_fd); - } - - ~CapturedStream() { - remove(filename_.c_str()); - } - - String GetCapturedString() { - if (uncaptured_fd_ != -1) { - // Restores the original stream. - fflush(NULL); - dup2(uncaptured_fd_, fd_); - close(uncaptured_fd_); - uncaptured_fd_ = -1; - } - - FILE* const file = posix::FOpen(filename_.c_str(), "r"); - const String content = ReadEntireFile(file); - posix::FClose(file); - return content; - } - - private: - // Reads the entire content of a file as a String. - static String ReadEntireFile(FILE* file); - - // Returns the size (in bytes) of a file. - static size_t GetFileSize(FILE* file); - - const int fd_; // A stream to capture. - int uncaptured_fd_; - // Name of the temporary file holding the stderr output. - ::std::string filename_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); -}; - -// Returns the size (in bytes) of a file. -size_t CapturedStream::GetFileSize(FILE* file) { - fseek(file, 0, SEEK_END); - return static_cast(ftell(file)); -} - -// Reads the entire content of a file as a string. -String CapturedStream::ReadEntireFile(FILE* file) { - const size_t file_size = GetFileSize(file); - char* const buffer = new char[file_size]; - - size_t bytes_last_read = 0; // # of bytes read in the last fread() - size_t bytes_read = 0; // # of bytes read so far - - fseek(file, 0, SEEK_SET); - - // Keeps reading the file until we cannot read further or the - // pre-determined file size is reached. - do { - bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); - bytes_read += bytes_last_read; - } while (bytes_last_read > 0 && bytes_read < file_size); - - const String content(buffer, bytes_read); - delete[] buffer; - - return content; -} - -# ifdef _MSC_VER -# pragma warning(pop) -# endif // _MSC_VER - -static CapturedStream* g_captured_stderr = NULL; -static CapturedStream* g_captured_stdout = NULL; - -// Starts capturing an output stream (stdout/stderr). -void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { - if (*stream != NULL) { - GTEST_LOG_(FATAL) << "Only one " << stream_name - << " capturer can exist at a time."; - } - *stream = new CapturedStream(fd); -} - -// Stops capturing the output stream and returns the captured string. -String GetCapturedStream(CapturedStream** captured_stream) { - const String content = (*captured_stream)->GetCapturedString(); - - delete *captured_stream; - *captured_stream = NULL; - - return content; -} - -// Starts capturing stdout. -void CaptureStdout() { - CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); -} - -// Starts capturing stderr. -void CaptureStderr() { - CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); -} - -// Stops capturing stdout and returns the captured string. -String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } - -// Stops capturing stderr and returns the captured string. -String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } - -#endif // GTEST_HAS_STREAM_REDIRECTION - -#if GTEST_HAS_DEATH_TEST - -// A copy of all command line arguments. Set by InitGoogleTest(). -::std::vector g_argvs; - -// Returns the command line as a vector of strings. -const ::std::vector& GetArgvs() { return g_argvs; } - -#endif // GTEST_HAS_DEATH_TEST - -#if GTEST_OS_WINDOWS_MOBILE -namespace posix { -void Abort() { - DebugBreak(); - TerminateProcess(GetCurrentProcess(), 1); -} -} // namespace posix -#endif // GTEST_OS_WINDOWS_MOBILE - -// Returns the name of the environment variable corresponding to the -// given flag. For example, FlagToEnvVar("foo") will return -// "GTEST_FOO" in the open-source version. -static String FlagToEnvVar(const char* flag) { - const String full_flag = - (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); - - Message env_var; - for (size_t i = 0; i != full_flag.length(); i++) { - env_var << ToUpper(full_flag.c_str()[i]); - } - - return env_var.GetString(); -} - -// Parses 'str' for a 32-bit signed integer. If successful, writes -// the result to *value and returns true; otherwise leaves *value -// unchanged and returns false. -bool ParseInt32(const Message& src_text, const char* str, Int32* value) { - // Parses the environment variable as a decimal integer. - char* end = NULL; - const long long_value = strtol(str, &end, 10); // NOLINT - - // Has strtol() consumed all characters in the string? - if (*end != '\0') { - // No - an invalid character was encountered. - Message msg; - msg << "WARNING: " << src_text - << " is expected to be a 32-bit integer, but actually" - << " has value \"" << str << "\".\n"; - printf("%s", msg.GetString().c_str()); - fflush(stdout); - return false; - } - - // Is the parsed value in the range of an Int32? - const Int32 result = static_cast(long_value); - if (long_value == LONG_MAX || long_value == LONG_MIN || - // The parsed value overflows as a long. (strtol() returns - // LONG_MAX or LONG_MIN when the input overflows.) - result != long_value - // The parsed value overflows as an Int32. - ) { - Message msg; - msg << "WARNING: " << src_text - << " is expected to be a 32-bit integer, but actually" - << " has value " << str << ", which overflows.\n"; - printf("%s", msg.GetString().c_str()); - fflush(stdout); - return false; - } - - *value = result; - return true; -} - -// Reads and returns the Boolean environment variable corresponding to -// the given flag; if it's not set, returns default_value. -// -// The value is considered true iff it's not "0". -bool BoolFromGTestEnv(const char* flag, bool default_value) { - const String env_var = FlagToEnvVar(flag); - const char* const string_value = posix::GetEnv(env_var.c_str()); - return string_value == NULL ? - default_value : strcmp(string_value, "0") != 0; -} - -// Reads and returns a 32-bit integer stored in the environment -// variable corresponding to the given flag; if it isn't set or -// doesn't represent a valid 32-bit integer, returns default_value. -Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { - const String env_var = FlagToEnvVar(flag); - const char* const string_value = posix::GetEnv(env_var.c_str()); - if (string_value == NULL) { - // The environment variable is not set. - return default_value; - } - - Int32 result = default_value; - if (!ParseInt32(Message() << "Environment variable " << env_var, - string_value, &result)) { - printf("The default value %s is used.\n", - (Message() << default_value).GetString().c_str()); - fflush(stdout); - return default_value; - } - - return result; -} - -// Reads and returns the string environment variable corresponding to -// the given flag; if it's not set, returns default_value. -const char* StringFromGTestEnv(const char* flag, const char* default_value) { - const String env_var = FlagToEnvVar(flag); - const char* const value = posix::GetEnv(env_var.c_str()); - return value == NULL ? default_value : value; -} - -} // namespace internal -} // namespace testing -// Copyright 2007, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) - -// Google Test - The Google C++ Testing Framework -// -// This file implements a universal value printer that can print a -// value of any type T: -// -// void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); -// -// It uses the << operator when possible, and prints the bytes in the -// object otherwise. A user can override its behavior for a class -// type Foo by defining either operator<<(::std::ostream&, const Foo&) -// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that -// defines Foo. - -#include -#include -#include // NOLINT -#include - -namespace testing { - -namespace { - -using ::std::ostream; - -#if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s. -# define snprintf _snprintf -#elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf. -# define snprintf _snprintf_s -#elif _MSC_VER -# define snprintf _snprintf -#endif // GTEST_OS_WINDOWS_MOBILE - -// Prints a segment of bytes in the given object. -void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, - size_t count, ostream* os) { - char text[5] = ""; - for (size_t i = 0; i != count; i++) { - const size_t j = start + i; - if (i != 0) { - // Organizes the bytes into groups of 2 for easy parsing by - // human. - if ((j % 2) == 0) - *os << ' '; - else - *os << '-'; - } - snprintf(text, sizeof(text), "%02X", obj_bytes[j]); - *os << text; - } -} - -// Prints the bytes in the given value to the given ostream. -void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, - ostream* os) { - // Tells the user how big the object is. - *os << count << "-byte object <"; - - const size_t kThreshold = 132; - const size_t kChunkSize = 64; - // If the object size is bigger than kThreshold, we'll have to omit - // some details by printing only the first and the last kChunkSize - // bytes. - // TODO(wan): let the user control the threshold using a flag. - if (count < kThreshold) { - PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); - } else { - PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); - *os << " ... "; - // Rounds up to 2-byte boundary. - const size_t resume_pos = (count - kChunkSize + 1)/2*2; - PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); - } - *os << ">"; -} - -} // namespace - -namespace internal2 { - -// Delegates to PrintBytesInObjectToImpl() to print the bytes in the -// given object. The delegation simplifies the implementation, which -// uses the << operator and thus is easier done outside of the -// ::testing::internal namespace, which contains a << operator that -// sometimes conflicts with the one in STL. -void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, - ostream* os) { - PrintBytesInObjectToImpl(obj_bytes, count, os); -} - -} // namespace internal2 - -namespace internal { - -// Depending on the value of a char (or wchar_t), we print it in one -// of three formats: -// - as is if it's a printable ASCII (e.g. 'a', '2', ' '), -// - as a hexidecimal escape sequence (e.g. '\x7F'), or -// - as a special escape sequence (e.g. '\r', '\n'). -enum CharFormat { - kAsIs, - kHexEscape, - kSpecialEscape -}; - -// Returns true if c is a printable ASCII character. We test the -// value of c directly instead of calling isprint(), which is buggy on -// Windows Mobile. -inline bool IsPrintableAscii(wchar_t c) { - return 0x20 <= c && c <= 0x7E; -} - -// Prints a wide or narrow char c as a character literal without the -// quotes, escaping it when necessary; returns how c was formatted. -// The template argument UnsignedChar is the unsigned version of Char, -// which is the type of c. -template -static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) { - switch (static_cast(c)) { - case L'\0': - *os << "\\0"; - break; - case L'\'': - *os << "\\'"; - break; - case L'\\': - *os << "\\\\"; - break; - case L'\a': - *os << "\\a"; - break; - case L'\b': - *os << "\\b"; - break; - case L'\f': - *os << "\\f"; - break; - case L'\n': - *os << "\\n"; - break; - case L'\r': - *os << "\\r"; - break; - case L'\t': - *os << "\\t"; - break; - case L'\v': - *os << "\\v"; - break; - default: - if (IsPrintableAscii(c)) { - *os << static_cast(c); - return kAsIs; - } else { - *os << String::Format("\\x%X", static_cast(c)); - return kHexEscape; - } - } - return kSpecialEscape; -} - -// Prints a char c as if it's part of a string literal, escaping it when -// necessary; returns how c was formatted. -static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) { - switch (c) { - case L'\'': - *os << "'"; - return kAsIs; - case L'"': - *os << "\\\""; - return kSpecialEscape; - default: - return PrintAsCharLiteralTo(c, os); - } -} - -// Prints a char c as if it's part of a string literal, escaping it when -// necessary; returns how c was formatted. -static CharFormat PrintAsNarrowStringLiteralTo(char c, ostream* os) { - return PrintAsWideStringLiteralTo(static_cast(c), os); -} - -// Prints a wide or narrow character c and its code. '\0' is printed -// as "'\\0'", other unprintable characters are also properly escaped -// using the standard C++ escape sequence. The template argument -// UnsignedChar is the unsigned version of Char, which is the type of c. -template -void PrintCharAndCodeTo(Char c, ostream* os) { - // First, print c as a literal in the most readable form we can find. - *os << ((sizeof(c) > 1) ? "L'" : "'"); - const CharFormat format = PrintAsCharLiteralTo(c, os); - *os << "'"; - - // To aid user debugging, we also print c's code in decimal, unless - // it's 0 (in which case c was printed as '\\0', making the code - // obvious). - if (c == 0) - return; - *os << " (" << String::Format("%d", c).c_str(); - - // For more convenience, we print c's code again in hexidecimal, - // unless c was already printed in the form '\x##' or the code is in - // [1, 9]. - if (format == kHexEscape || (1 <= c && c <= 9)) { - // Do nothing. - } else { - *os << String::Format(", 0x%X", - static_cast(c)).c_str(); - } - *os << ")"; -} - -void PrintTo(unsigned char c, ::std::ostream* os) { - PrintCharAndCodeTo(c, os); -} -void PrintTo(signed char c, ::std::ostream* os) { - PrintCharAndCodeTo(c, os); -} - -// Prints a wchar_t as a symbol if it is printable or as its internal -// code otherwise and also as its code. L'\0' is printed as "L'\\0'". -void PrintTo(wchar_t wc, ostream* os) { - PrintCharAndCodeTo(wc, os); -} - -// Prints the given array of characters to the ostream. -// The array starts at *begin, the length is len, it may include '\0' characters -// and may not be null-terminated. -static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) { - *os << "\""; - bool is_previous_hex = false; - for (size_t index = 0; index < len; ++index) { - const char cur = begin[index]; - if (is_previous_hex && IsXDigit(cur)) { - // Previous character is of '\x..' form and this character can be - // interpreted as another hexadecimal digit in its number. Break string to - // disambiguate. - *os << "\" \""; - } - is_previous_hex = PrintAsNarrowStringLiteralTo(cur, os) == kHexEscape; - } - *os << "\""; -} - -// Prints a (const) char array of 'len' elements, starting at address 'begin'. -void UniversalPrintArray(const char* begin, size_t len, ostream* os) { - PrintCharsAsStringTo(begin, len, os); -} - -// Prints the given array of wide characters to the ostream. -// The array starts at *begin, the length is len, it may include L'\0' -// characters and may not be null-terminated. -static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len, - ostream* os) { - *os << "L\""; - bool is_previous_hex = false; - for (size_t index = 0; index < len; ++index) { - const wchar_t cur = begin[index]; - if (is_previous_hex && isascii(cur) && IsXDigit(static_cast(cur))) { - // Previous character is of '\x..' form and this character can be - // interpreted as another hexadecimal digit in its number. Break string to - // disambiguate. - *os << "\" L\""; - } - is_previous_hex = PrintAsWideStringLiteralTo(cur, os) == kHexEscape; - } - *os << "\""; -} - -// Prints the given C string to the ostream. -void PrintTo(const char* s, ostream* os) { - if (s == NULL) { - *os << "NULL"; - } else { - *os << ImplicitCast_(s) << " pointing to "; - PrintCharsAsStringTo(s, strlen(s), os); - } -} - -// MSVC compiler can be configured to define whar_t as a typedef -// of unsigned short. Defining an overload for const wchar_t* in that case -// would cause pointers to unsigned shorts be printed as wide strings, -// possibly accessing more memory than intended and causing invalid -// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when -// wchar_t is implemented as a native type. -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) -// Prints the given wide C string to the ostream. -void PrintTo(const wchar_t* s, ostream* os) { - if (s == NULL) { - *os << "NULL"; - } else { - *os << ImplicitCast_(s) << " pointing to "; - PrintWideCharsAsStringTo(s, wcslen(s), os); - } -} -#endif // wchar_t is native - -// Prints a ::string object. -#if GTEST_HAS_GLOBAL_STRING -void PrintStringTo(const ::string& s, ostream* os) { - PrintCharsAsStringTo(s.data(), s.size(), os); -} -#endif // GTEST_HAS_GLOBAL_STRING - -void PrintStringTo(const ::std::string& s, ostream* os) { - PrintCharsAsStringTo(s.data(), s.size(), os); -} - -// Prints a ::wstring object. -#if GTEST_HAS_GLOBAL_WSTRING -void PrintWideStringTo(const ::wstring& s, ostream* os) { - PrintWideCharsAsStringTo(s.data(), s.size(), os); -} -#endif // GTEST_HAS_GLOBAL_WSTRING - -#if GTEST_HAS_STD_WSTRING -void PrintWideStringTo(const ::std::wstring& s, ostream* os) { - PrintWideCharsAsStringTo(s.data(), s.size(), os); -} -#endif // GTEST_HAS_STD_WSTRING - -} // namespace internal - -} // namespace testing -// Copyright 2008, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: mheule@google.com (Markus Heule) -// -// The Google C++ Testing Framework (Google Test) - - -// Indicates that this translation unit is part of Google Test's -// implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. -#define GTEST_IMPLEMENTATION_ 1 -#undef GTEST_IMPLEMENTATION_ - -namespace testing { - -using internal::GetUnitTestImpl; - -// Gets the summary of the failure message by omitting the stack trace -// in it. -internal::String TestPartResult::ExtractSummary(const char* message) { - const char* const stack_trace = strstr(message, internal::kStackTraceMarker); - return stack_trace == NULL ? internal::String(message) : - internal::String(message, stack_trace - message); -} - -// Prints a TestPartResult object. -std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { - return os - << result.file_name() << ":" << result.line_number() << ": " - << (result.type() == TestPartResult::kSuccess ? "Success" : - result.type() == TestPartResult::kFatalFailure ? "Fatal failure" : - "Non-fatal failure") << ":\n" - << result.message() << std::endl; -} - -// Appends a TestPartResult to the array. -void TestPartResultArray::Append(const TestPartResult& result) { - array_.push_back(result); -} - -// Returns the TestPartResult at the given index (0-based). -const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { - if (index < 0 || index >= size()) { - printf("\nInvalid index (%d) into TestPartResultArray.\n", index); - internal::posix::Abort(); - } - - return array_[index]; -} - -// Returns the number of TestPartResult objects in the array. -int TestPartResultArray::size() const { - return static_cast(array_.size()); -} - -namespace internal { - -HasNewFatalFailureHelper::HasNewFatalFailureHelper() - : has_new_fatal_failure_(false), - original_reporter_(GetUnitTestImpl()-> - GetTestPartResultReporterForCurrentThread()) { - GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); -} - -HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { - GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread( - original_reporter_); -} - -void HasNewFatalFailureHelper::ReportTestPartResult( - const TestPartResult& result) { - if (result.fatally_failed()) - has_new_fatal_failure_ = true; - original_reporter_->ReportTestPartResult(result); -} - -} // namespace internal - -} // namespace testing -// Copyright 2008 Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) - - -namespace testing { -namespace internal { - -#if GTEST_HAS_TYPED_TEST_P - -// Skips to the first non-space char in str. Returns an empty string if str -// contains only whitespace characters. -static const char* SkipSpaces(const char* str) { - while (IsSpace(*str)) - str++; - return str; -} - -// Verifies that registered_tests match the test names in -// defined_test_names_; returns registered_tests if successful, or -// aborts the program otherwise. -const char* TypedTestCasePState::VerifyRegisteredTestNames( - const char* file, int line, const char* registered_tests) { - typedef ::std::set::const_iterator DefinedTestIter; - registered_ = true; - - // Skip initial whitespace in registered_tests since some - // preprocessors prefix stringizied literals with whitespace. - registered_tests = SkipSpaces(registered_tests); - - Message errors; - ::std::set tests; - for (const char* names = registered_tests; names != NULL; - names = SkipComma(names)) { - const String name = GetPrefixUntilComma(names); - if (tests.count(name) != 0) { - errors << "Test " << name << " is listed more than once.\n"; - continue; - } - - bool found = false; - for (DefinedTestIter it = defined_test_names_.begin(); - it != defined_test_names_.end(); - ++it) { - if (name == *it) { - found = true; - break; - } - } - - if (found) { - tests.insert(name); - } else { - errors << "No test named " << name - << " can be found in this test case.\n"; - } - } - - for (DefinedTestIter it = defined_test_names_.begin(); - it != defined_test_names_.end(); - ++it) { - if (tests.count(*it) == 0) { - errors << "You forgot to list test " << *it << ".\n"; - } - } - - const String& errors_str = errors.GetString(); - if (errors_str != "") { - fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), - errors_str.c_str()); - fflush(stderr); - posix::Abort(); - } - - return registered_tests; -} - -#endif // GTEST_HAS_TYPED_TEST_P - -} // namespace internal -} // namespace testing diff --git a/Testing/Unit/GoogleTest/gtest/gtest.h b/Testing/Unit/GoogleTest/gtest/gtest.h deleted file mode 100644 index e8b816124..000000000 --- a/Testing/Unit/GoogleTest/gtest/gtest.h +++ /dev/null @@ -1,19550 +0,0 @@ -// Copyright 2005, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) -// -// The Google C++ Testing Framework (Google Test) -// -// This header file defines the public API for Google Test. It should be -// included by any test program that uses Google Test. -// -// IMPORTANT NOTE: Due to limitation of the C++ language, we have to -// leave some internal implementation details in this header file. -// They are clearly marked by comments like this: -// -// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -// -// Such code is NOT meant to be used by a user directly, and is subject -// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user -// program! -// -// Acknowledgment: Google Test borrowed the idea of automatic test -// registration from Barthelemy Dagenais' (barthelemy@prologique.com) -// easyUnit framework. - -#ifndef GTEST_INCLUDE_GTEST_GTEST_H_ -#define GTEST_INCLUDE_GTEST_GTEST_H_ - -#include -#include - -// Copyright 2005, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) -// -// The Google C++ Testing Framework (Google Test) -// -// This header file declares functions and macros used internally by -// Google Test. They are subject to change without notice. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ - -// Copyright 2005, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Authors: wan@google.com (Zhanyong Wan) -// -// Low-level types and utilities for porting Google Test to various -// platforms. They are subject to change without notice. DO NOT USE -// THEM IN USER CODE. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ - -// The user can define the following macros in the build script to -// control Google Test's behavior. If the user doesn't define a macro -// in this list, Google Test will define it. -// -// GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) -// is/isn't available. -// GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions -// are enabled. -// GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string -// is/isn't available (some systems define -// ::string, which is different to std::string). -// GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string -// is/isn't available (some systems define -// ::wstring, which is different to std::wstring). -// GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular -// expressions are/aren't available. -// GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that -// is/isn't available. -// GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't -// enabled. -// GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that -// std::wstring does/doesn't work (Google Test can -// be used where std::wstring is unavailable). -// GTEST_HAS_TR1_TUPLE - Define it to 1/0 to indicate tr1::tuple -// is/isn't available. -// GTEST_HAS_SEH - Define it to 1/0 to indicate whether the -// compiler supports Microsoft's "Structured -// Exception Handling". -// GTEST_HAS_STREAM_REDIRECTION -// - Define it to 1/0 to indicate whether the -// platform supports I/O stream redirection using -// dup() and dup2(). -// GTEST_USE_OWN_TR1_TUPLE - Define it to 1/0 to indicate whether Google -// Test's own tr1 tuple implementation should be -// used. Unused when the user sets -// GTEST_HAS_TR1_TUPLE to 0. -// GTEST_LINKED_AS_SHARED_LIBRARY -// - Define to 1 when compiling tests that use -// Google Test as a shared library (known as -// DLL on Windows). -// GTEST_CREATE_SHARED_LIBRARY -// - Define to 1 when compiling Google Test itself -// as a shared library. - -// This header defines the following utilities: -// -// Macros indicating the current platform (defined to 1 if compiled on -// the given platform; otherwise undefined): -// GTEST_OS_AIX - IBM AIX -// GTEST_OS_CYGWIN - Cygwin -// GTEST_OS_HPUX - HP-UX -// GTEST_OS_LINUX - Linux -// GTEST_OS_LINUX_ANDROID - Google Android -// GTEST_OS_MAC - Mac OS X -// GTEST_OS_NACL - Google Native Client (NaCl) -// GTEST_OS_SOLARIS - Sun Solaris -// GTEST_OS_SYMBIAN - Symbian -// GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) -// GTEST_OS_WINDOWS_DESKTOP - Windows Desktop -// GTEST_OS_WINDOWS_MINGW - MinGW -// GTEST_OS_WINDOWS_MOBILE - Windows Mobile -// GTEST_OS_ZOS - z/OS -// -// Among the platforms, Cygwin, Linux, Max OS X, and Windows have the -// most stable support. Since core members of the Google Test project -// don't have access to other platforms, support for them may be less -// stable. If you notice any problems on your platform, please notify -// googletestframework@googlegroups.com (patches for fixing them are -// even more welcome!). -// -// Note that it is possible that none of the GTEST_OS_* macros are defined. -// -// Macros indicating available Google Test features (defined to 1 if -// the corresponding feature is supported; otherwise undefined): -// GTEST_HAS_COMBINE - the Combine() function (for value-parameterized -// tests) -// GTEST_HAS_DEATH_TEST - death tests -// GTEST_HAS_PARAM_TEST - value-parameterized tests -// GTEST_HAS_TYPED_TEST - typed tests -// GTEST_HAS_TYPED_TEST_P - type-parameterized tests -// GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with -// GTEST_HAS_POSIX_RE (see above) which users can -// define themselves. -// GTEST_USES_SIMPLE_RE - our own simple regex is used; -// the above two are mutually exclusive. -// GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). -// -// Macros for basic C++ coding: -// GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. -// GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a -// variable don't have to be used. -// GTEST_DISALLOW_ASSIGN_ - disables operator=. -// GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. -// GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. -// -// Synchronization: -// Mutex, MutexLock, ThreadLocal, GetThreadCount() -// - synchronization primitives. -// GTEST_IS_THREADSAFE - defined to 1 to indicate that the above -// synchronization primitives have real implementations -// and Google Test is thread-safe; or 0 otherwise. -// -// Template meta programming: -// is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only. -// IteratorTraits - partial implementation of std::iterator_traits, which -// is not available in libCstd when compiled with Sun C++. -// -// Smart pointers: -// scoped_ptr - as in TR2. -// -// Regular expressions: -// RE - a simple regular expression class using the POSIX -// Extended Regular Expression syntax on UNIX-like -// platforms, or a reduced regular exception syntax on -// other platforms, including Windows. -// -// Logging: -// GTEST_LOG_() - logs messages at the specified severity level. -// LogToStderr() - directs all log messages to stderr. -// FlushInfoLog() - flushes informational log messages. -// -// Stdout and stderr capturing: -// CaptureStdout() - starts capturing stdout. -// GetCapturedStdout() - stops capturing stdout and returns the captured -// string. -// CaptureStderr() - starts capturing stderr. -// GetCapturedStderr() - stops capturing stderr and returns the captured -// string. -// -// Integer types: -// TypeWithSize - maps an integer to a int type. -// Int32, UInt32, Int64, UInt64, TimeInMillis -// - integers of known sizes. -// BiggestInt - the biggest signed integer type. -// -// Command-line utilities: -// GTEST_FLAG() - references a flag. -// GTEST_DECLARE_*() - declares a flag. -// GTEST_DEFINE_*() - defines a flag. -// GetArgvs() - returns the command line as a vector of strings. -// -// Environment variable utilities: -// GetEnv() - gets the value of an environment variable. -// BoolFromGTestEnv() - parses a bool environment variable. -// Int32FromGTestEnv() - parses an Int32 environment variable. -// StringFromGTestEnv() - parses a string environment variable. - -#include // for isspace, etc -#include // for ptrdiff_t -#include -#include -#include -#ifndef _WIN32_WCE -# include -# include -#endif // !_WIN32_WCE - -#include // NOLINT -#include // NOLINT -#include // NOLINT - -#define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" -#define GTEST_FLAG_PREFIX_ "gtest_" -#define GTEST_FLAG_PREFIX_DASH_ "gtest-" -#define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" -#define GTEST_NAME_ "Google Test" -#define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/" - -// Determines the version of gcc that is used to compile this. -#ifdef __GNUC__ -// 40302 means version 4.3.2. -# define GTEST_GCC_VER_ \ - (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) -#endif // __GNUC__ - -// Determines the platform on which Google Test is compiled. -#ifdef __CYGWIN__ -# define GTEST_OS_CYGWIN 1 -#elif defined __SYMBIAN32__ -# define GTEST_OS_SYMBIAN 1 -#elif defined _WIN32 -# define GTEST_OS_WINDOWS 1 -# ifdef _WIN32_WCE -# define GTEST_OS_WINDOWS_MOBILE 1 -# elif defined(__MINGW__) || defined(__MINGW32__) -# define GTEST_OS_WINDOWS_MINGW 1 -# else -# define GTEST_OS_WINDOWS_DESKTOP 1 -# endif // _WIN32_WCE -#elif defined __APPLE__ -# define GTEST_OS_MAC 1 -#elif defined __linux__ -# define GTEST_OS_LINUX 1 -# ifdef ANDROID -# define GTEST_OS_LINUX_ANDROID 1 -# endif // ANDROID -#elif defined __MVS__ -# define GTEST_OS_ZOS 1 -#elif defined(__sun) && defined(__SVR4) -# define GTEST_OS_SOLARIS 1 -#elif defined(_AIX) -# define GTEST_OS_AIX 1 -#elif defined(__hpux) -# define GTEST_OS_HPUX 1 -#elif defined __native_client__ -# define GTEST_OS_NACL 1 -#endif // __CYGWIN__ - -// Brings in definitions for functions used in the testing::internal::posix -// namespace (read, write, close, chdir, isatty, stat). We do not currently -// use them on Windows Mobile. -#if !GTEST_OS_WINDOWS -// This assumes that non-Windows OSes provide unistd.h. For OSes where this -// is not the case, we need to include headers that provide the functions -// mentioned above. -# include -# if !GTEST_OS_NACL -// TODO(vladl@google.com): Remove this condition when Native Client SDK adds -// strings.h (tracked in -// http://code.google.com/p/nativeclient/issues/detail?id=1175). -# include // Native Client doesn't provide strings.h. -# endif -#elif !GTEST_OS_WINDOWS_MOBILE -# include -# include -#endif - -// Defines this to true iff Google Test can use POSIX regular expressions. -#ifndef GTEST_HAS_POSIX_RE -# define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) -#endif - -#if GTEST_HAS_POSIX_RE - -// On some platforms, needs someone to define size_t, and -// won't compile otherwise. We can #include it here as we already -// included , which is guaranteed to define size_t through -// . -# include // NOLINT - -# define GTEST_USES_POSIX_RE 1 - -#elif GTEST_OS_WINDOWS - -// is not available on Windows. Use our own simple regex -// implementation instead. -# define GTEST_USES_SIMPLE_RE 1 - -#else - -// may not be available on this platform. Use our own -// simple regex implementation instead. -# define GTEST_USES_SIMPLE_RE 1 - -#endif // GTEST_HAS_POSIX_RE - -#ifndef GTEST_HAS_EXCEPTIONS -// The user didn't tell us whether exceptions are enabled, so we need -// to figure it out. -# if defined(_MSC_VER) || defined(__BORLANDC__) -// MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS -// macro to enable exceptions, so we'll do the same. -// Assumes that exceptions are enabled by default. -# ifndef _HAS_EXCEPTIONS -# define _HAS_EXCEPTIONS 1 -# endif // _HAS_EXCEPTIONS -# define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS -# elif defined(__GNUC__) && __EXCEPTIONS -// gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__SUNPRO_CC) -// Sun Pro CC supports exceptions. However, there is no compile-time way of -// detecting whether they are enabled or not. Therefore, we assume that -// they are enabled unless the user tells us otherwise. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__IBMCPP__) && __EXCEPTIONS -// xlC defines __EXCEPTIONS to 1 iff exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__HP_aCC) -// Exception handling is in effect by default in HP aCC compiler. It has to -// be turned of by +noeh compiler option if desired. -# define GTEST_HAS_EXCEPTIONS 1 -# else -// For other compilers, we assume exceptions are disabled to be -// conservative. -# define GTEST_HAS_EXCEPTIONS 0 -# endif // defined(_MSC_VER) || defined(__BORLANDC__) -#endif // GTEST_HAS_EXCEPTIONS - -#if !defined(GTEST_HAS_STD_STRING) -// Even though we don't use this macro any longer, we keep it in case -// some clients still depend on it. -# define GTEST_HAS_STD_STRING 1 -#elif !GTEST_HAS_STD_STRING -// The user told us that ::std::string isn't available. -# error "Google Test cannot be used where ::std::string isn't available." -#endif // !defined(GTEST_HAS_STD_STRING) - -#ifndef GTEST_HAS_GLOBAL_STRING -// The user didn't tell us whether ::string is available, so we need -// to figure it out. - -# define GTEST_HAS_GLOBAL_STRING 0 - -#endif // GTEST_HAS_GLOBAL_STRING - -#ifndef GTEST_HAS_STD_WSTRING -// The user didn't tell us whether ::std::wstring is available, so we need -// to figure it out. -// TODO(wan@google.com): uses autoconf to detect whether ::std::wstring -// is available. - -// Cygwin 1.7 and below doesn't support ::std::wstring. -// Solaris' libc++ doesn't support it either. Android has -// no support for it at least as recent as Froyo (2.2). -# define GTEST_HAS_STD_WSTRING \ - (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS)) - -#endif // GTEST_HAS_STD_WSTRING - -#ifndef GTEST_HAS_GLOBAL_WSTRING -// The user didn't tell us whether ::wstring is available, so we need -// to figure it out. -# define GTEST_HAS_GLOBAL_WSTRING \ - (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING) -#endif // GTEST_HAS_GLOBAL_WSTRING - -// Determines whether RTTI is available. -#ifndef GTEST_HAS_RTTI -// The user didn't tell us whether RTTI is enabled, so we need to -// figure it out. - -# ifdef _MSC_VER - -# ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled. -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif - -// Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. -# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) - -# ifdef __GXX_RTTI -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif // __GXX_RTTI - -// Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if -// both the typeid and dynamic_cast features are present. -# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) - -# ifdef __RTTI_ALL__ -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif - -# else - -// For all other compilers, we assume RTTI is enabled. -# define GTEST_HAS_RTTI 1 - -# endif // _MSC_VER - -#endif // GTEST_HAS_RTTI - -// It's this header's responsibility to #include when RTTI -// is enabled. -#if GTEST_HAS_RTTI -# include -#endif - -// Determines whether Google Test can use the pthreads library. -#ifndef GTEST_HAS_PTHREAD -// The user didn't tell us explicitly, so we assume pthreads support is -// available on Linux and Mac. -// -// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 -// to your compiler flags. -# define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX) -#endif // GTEST_HAS_PTHREAD - -#if GTEST_HAS_PTHREAD -// gtest-port.h guarantees to #include when GTEST_HAS_PTHREAD is -// true. -# include // NOLINT - -// For timespec and nanosleep, used below. -# include // NOLINT -#endif - - -// !!!HACK!!! -// Tuples are broken in VS11. The variadic templates are not deep enough. -// We are not currently using the GTest features which require tuple, -// so just disable them and hope that upstream premanetly addresses -// the problem, with out required more CMake core for compiler issues. -#define GTEST_HAS_TR1_TUPLE 0 - -// Determines whether Google Test can use tr1/tuple. You can define -// this macro to 0 to prevent Google Test from using tuple (any -// feature depending on tuple with be disabled in this mode). -#ifndef GTEST_HAS_TR1_TUPLE -// The user didn't tell us not to do it, so we assume it's OK. -# define GTEST_HAS_TR1_TUPLE 1 -#endif // GTEST_HAS_TR1_TUPLE - -// Determines whether Google Test's own tr1 tuple implementation -// should be used. -#ifndef GTEST_USE_OWN_TR1_TUPLE -// The user didn't tell us, so we need to figure it out. - -// We use our own TR1 tuple if we aren't sure the user has an -// implementation of it already. At this time, GCC 4.0.0+ and MSVC -// 2010 are the only mainstream compilers that come with a TR1 tuple -// implementation. NVIDIA's CUDA NVCC compiler pretends to be GCC by -// defining __GNUC__ and friends, but cannot compile GCC's tuple -// implementation. MSVC 2008 (9.0) provides TR1 tuple in a 323 MB -// Feature Pack download, which we cannot assume the user has. -# if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000)) \ - || _MSC_VER >= 1600 -# define GTEST_USE_OWN_TR1_TUPLE 0 -# else -# define GTEST_USE_OWN_TR1_TUPLE 1 -# endif - -#endif // GTEST_USE_OWN_TR1_TUPLE - -// To avoid conditional compilation everywhere, we make it -// gtest-port.h's responsibility to #include the header implementing -// tr1/tuple. -#if GTEST_HAS_TR1_TUPLE - -# if GTEST_USE_OWN_TR1_TUPLE -// This file was GENERATED by a script. DO NOT EDIT BY HAND!!! - -// Copyright 2009 Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) - -// Implements a subset of TR1 tuple needed by Google Test and Google Mock. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ - -#include // For ::std::pair. - -// The compiler used in Symbian has a bug that prevents us from declaring the -// tuple template as a friend (it complains that tuple is redefined). This -// hack bypasses the bug by declaring the members that should otherwise be -// private as public. -// Sun Studio versions < 12 also have the above bug. -#if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) -# define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: -#else -# define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ - template friend class tuple; \ - private: -#endif - -// GTEST_n_TUPLE_(T) is the type of an n-tuple. -#define GTEST_0_TUPLE_(T) tuple<> -#define GTEST_1_TUPLE_(T) tuple -#define GTEST_2_TUPLE_(T) tuple -#define GTEST_3_TUPLE_(T) tuple -#define GTEST_4_TUPLE_(T) tuple -#define GTEST_5_TUPLE_(T) tuple -#define GTEST_6_TUPLE_(T) tuple -#define GTEST_7_TUPLE_(T) tuple -#define GTEST_8_TUPLE_(T) tuple -#define GTEST_9_TUPLE_(T) tuple -#define GTEST_10_TUPLE_(T) tuple - -// GTEST_n_TYPENAMES_(T) declares a list of n typenames. -#define GTEST_0_TYPENAMES_(T) -#define GTEST_1_TYPENAMES_(T) typename T##0 -#define GTEST_2_TYPENAMES_(T) typename T##0, typename T##1 -#define GTEST_3_TYPENAMES_(T) typename T##0, typename T##1, typename T##2 -#define GTEST_4_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3 -#define GTEST_5_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4 -#define GTEST_6_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5 -#define GTEST_7_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5, typename T##6 -#define GTEST_8_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5, typename T##6, typename T##7 -#define GTEST_9_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5, typename T##6, \ - typename T##7, typename T##8 -#define GTEST_10_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5, typename T##6, \ - typename T##7, typename T##8, typename T##9 - -// In theory, defining stuff in the ::std namespace is undefined -// behavior. We can do this as we are playing the role of a standard -// library vendor. -namespace std { -namespace tr1 { - -template -class tuple; - -// Anything in namespace gtest_internal is Google Test's INTERNAL -// IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code. -namespace gtest_internal { - -// ByRef::type is T if T is a reference; otherwise it's const T&. -template -struct ByRef { typedef const T& type; }; // NOLINT -template -struct ByRef { typedef T& type; }; // NOLINT - -// A handy wrapper for ByRef. -#define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef::type - -// AddRef::type is T if T is a reference; otherwise it's T&. This -// is the same as tr1::add_reference::type. -template -struct AddRef { typedef T& type; }; // NOLINT -template -struct AddRef { typedef T& type; }; // NOLINT - -// A handy wrapper for AddRef. -#define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef::type - -// A helper for implementing get(). -template class Get; - -// A helper for implementing tuple_element. kIndexValid is true -// iff k < the number of fields in tuple type T. -template -struct TupleElement; - -template -struct TupleElement { typedef T0 type; }; - -template -struct TupleElement { typedef T1 type; }; - -template -struct TupleElement { typedef T2 type; }; - -template -struct TupleElement { typedef T3 type; }; - -template -struct TupleElement { typedef T4 type; }; - -template -struct TupleElement { typedef T5 type; }; - -template -struct TupleElement { typedef T6 type; }; - -template -struct TupleElement { typedef T7 type; }; - -template -struct TupleElement { typedef T8 type; }; - -template -struct TupleElement { typedef T9 type; }; - -} // namespace gtest_internal - -template <> -class tuple<> { - public: - tuple() {} - tuple(const tuple& /* t */) {} - tuple& operator=(const tuple& /* t */) { return *this; } -}; - -template -class GTEST_1_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0) : f0_(f0) {} - - tuple(const tuple& t) : f0_(t.f0_) {} - - template - tuple(const GTEST_1_TUPLE_(U)& t) : f0_(t.f0_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_1_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_1_TUPLE_(U)& t) { - f0_ = t.f0_; - return *this; - } - - T0 f0_; -}; - -template -class GTEST_2_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1) : f0_(f0), - f1_(f1) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_) {} - - template - tuple(const GTEST_2_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_) {} - template - tuple(const ::std::pair& p) : f0_(p.first), f1_(p.second) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_2_TUPLE_(U)& t) { - return CopyFrom(t); - } - template - tuple& operator=(const ::std::pair& p) { - f0_ = p.first; - f1_ = p.second; - return *this; - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_2_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - return *this; - } - - T0 f0_; - T1 f1_; -}; - -template -class GTEST_3_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2) : f0_(f0), f1_(f1), f2_(f2) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} - - template - tuple(const GTEST_3_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_3_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_3_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; -}; - -template -class GTEST_4_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3) : f0_(f0), f1_(f1), f2_(f2), - f3_(f3) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {} - - template - tuple(const GTEST_4_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_4_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_4_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; -}; - -template -class GTEST_5_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_(), f4_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, - GTEST_BY_REF_(T4) f4) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_) {} - - template - tuple(const GTEST_5_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_5_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_5_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - f4_ = t.f4_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; - T4 f4_; -}; - -template -class GTEST_6_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), - f5_(f5) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_) {} - - template - tuple(const GTEST_6_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_6_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_6_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - f4_ = t.f4_; - f5_ = t.f5_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; - T4 f4_; - T5 f5_; -}; - -template -class GTEST_7_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6) : f0_(f0), f1_(f1), f2_(f2), - f3_(f3), f4_(f4), f5_(f5), f6_(f6) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} - - template - tuple(const GTEST_7_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_7_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_7_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - f4_ = t.f4_; - f5_ = t.f5_; - f6_ = t.f6_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; - T4 f4_; - T5 f5_; - T6 f6_; -}; - -template -class GTEST_8_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, - GTEST_BY_REF_(T7) f7) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), - f5_(f5), f6_(f6), f7_(f7) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} - - template - tuple(const GTEST_8_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_8_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_8_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - f4_ = t.f4_; - f5_ = t.f5_; - f6_ = t.f6_; - f7_ = t.f7_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; - T4 f4_; - T5 f5_; - T6 f6_; - T7 f7_; -}; - -template -class GTEST_9_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, - GTEST_BY_REF_(T8) f8) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), - f5_(f5), f6_(f6), f7_(f7), f8_(f8) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} - - template - tuple(const GTEST_9_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_9_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_9_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - f4_ = t.f4_; - f5_ = t.f5_; - f6_ = t.f6_; - f7_ = t.f7_; - f8_ = t.f8_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; - T4 f4_; - T5 f5_; - T6 f6_; - T7 f7_; - T8 f8_; -}; - -template -class tuple { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_(), - f9_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, - GTEST_BY_REF_(T8) f8, GTEST_BY_REF_(T9) f9) : f0_(f0), f1_(f1), f2_(f2), - f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8), f9_(f9) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), f9_(t.f9_) {} - - template - tuple(const GTEST_10_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), - f9_(t.f9_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_10_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_10_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - f4_ = t.f4_; - f5_ = t.f5_; - f6_ = t.f6_; - f7_ = t.f7_; - f8_ = t.f8_; - f9_ = t.f9_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; - T4 f4_; - T5 f5_; - T6 f6_; - T7 f7_; - T8 f8_; - T9 f9_; -}; - -// 6.1.3.2 Tuple creation functions. - -// Known limitations: we don't support passing an -// std::tr1::reference_wrapper to make_tuple(). And we don't -// implement tie(). - -inline tuple<> make_tuple() { return tuple<>(); } - -template -inline GTEST_1_TUPLE_(T) make_tuple(const T0& f0) { - return GTEST_1_TUPLE_(T)(f0); -} - -template -inline GTEST_2_TUPLE_(T) make_tuple(const T0& f0, const T1& f1) { - return GTEST_2_TUPLE_(T)(f0, f1); -} - -template -inline GTEST_3_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2) { - return GTEST_3_TUPLE_(T)(f0, f1, f2); -} - -template -inline GTEST_4_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3) { - return GTEST_4_TUPLE_(T)(f0, f1, f2, f3); -} - -template -inline GTEST_5_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4) { - return GTEST_5_TUPLE_(T)(f0, f1, f2, f3, f4); -} - -template -inline GTEST_6_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5) { - return GTEST_6_TUPLE_(T)(f0, f1, f2, f3, f4, f5); -} - -template -inline GTEST_7_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5, const T6& f6) { - return GTEST_7_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6); -} - -template -inline GTEST_8_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7) { - return GTEST_8_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7); -} - -template -inline GTEST_9_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, - const T8& f8) { - return GTEST_9_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8); -} - -template -inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, - const T8& f8, const T9& f9) { - return GTEST_10_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9); -} - -// 6.1.3.3 Tuple helper classes. - -template struct tuple_size; - -template -struct tuple_size { static const int value = 0; }; - -template -struct tuple_size { static const int value = 1; }; - -template -struct tuple_size { static const int value = 2; }; - -template -struct tuple_size { static const int value = 3; }; - -template -struct tuple_size { static const int value = 4; }; - -template -struct tuple_size { static const int value = 5; }; - -template -struct tuple_size { static const int value = 6; }; - -template -struct tuple_size { static const int value = 7; }; - -template -struct tuple_size { static const int value = 8; }; - -template -struct tuple_size { static const int value = 9; }; - -template -struct tuple_size { static const int value = 10; }; - -template -struct tuple_element { - typedef typename gtest_internal::TupleElement< - k < (tuple_size::value), k, Tuple>::type type; -}; - -#define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element::type - -// 6.1.3.4 Element access. - -namespace gtest_internal { - -template <> -class Get<0> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) - Field(Tuple& t) { return t.f0_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) - ConstField(const Tuple& t) { return t.f0_; } -}; - -template <> -class Get<1> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) - Field(Tuple& t) { return t.f1_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) - ConstField(const Tuple& t) { return t.f1_; } -}; - -template <> -class Get<2> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) - Field(Tuple& t) { return t.f2_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) - ConstField(const Tuple& t) { return t.f2_; } -}; - -template <> -class Get<3> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) - Field(Tuple& t) { return t.f3_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) - ConstField(const Tuple& t) { return t.f3_; } -}; - -template <> -class Get<4> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) - Field(Tuple& t) { return t.f4_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) - ConstField(const Tuple& t) { return t.f4_; } -}; - -template <> -class Get<5> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) - Field(Tuple& t) { return t.f5_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) - ConstField(const Tuple& t) { return t.f5_; } -}; - -template <> -class Get<6> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) - Field(Tuple& t) { return t.f6_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) - ConstField(const Tuple& t) { return t.f6_; } -}; - -template <> -class Get<7> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) - Field(Tuple& t) { return t.f7_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) - ConstField(const Tuple& t) { return t.f7_; } -}; - -template <> -class Get<8> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) - Field(Tuple& t) { return t.f8_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) - ConstField(const Tuple& t) { return t.f8_; } -}; - -template <> -class Get<9> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) - Field(Tuple& t) { return t.f9_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) - ConstField(const Tuple& t) { return t.f9_; } -}; - -} // namespace gtest_internal - -template -GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) -get(GTEST_10_TUPLE_(T)& t) { - return gtest_internal::Get::Field(t); -} - -template -GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) -get(const GTEST_10_TUPLE_(T)& t) { - return gtest_internal::Get::ConstField(t); -} - -// 6.1.3.5 Relational operators - -// We only implement == and !=, as we don't have a need for the rest yet. - -namespace gtest_internal { - -// SameSizeTuplePrefixComparator::Eq(t1, t2) returns true if the -// first k fields of t1 equals the first k fields of t2. -// SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if -// k1 != k2. -template -struct SameSizeTuplePrefixComparator; - -template <> -struct SameSizeTuplePrefixComparator<0, 0> { - template - static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) { - return true; - } -}; - -template -struct SameSizeTuplePrefixComparator { - template - static bool Eq(const Tuple1& t1, const Tuple2& t2) { - return SameSizeTuplePrefixComparator::Eq(t1, t2) && - ::std::tr1::get(t1) == ::std::tr1::get(t2); - } -}; - -} // namespace gtest_internal - -template -inline bool operator==(const GTEST_10_TUPLE_(T)& t, - const GTEST_10_TUPLE_(U)& u) { - return gtest_internal::SameSizeTuplePrefixComparator< - tuple_size::value, - tuple_size::value>::Eq(t, u); -} - -template -inline bool operator!=(const GTEST_10_TUPLE_(T)& t, - const GTEST_10_TUPLE_(U)& u) { return !(t == u); } - -// 6.1.4 Pairs. -// Unimplemented. - -} // namespace tr1 -} // namespace std - -#undef GTEST_0_TUPLE_ -#undef GTEST_1_TUPLE_ -#undef GTEST_2_TUPLE_ -#undef GTEST_3_TUPLE_ -#undef GTEST_4_TUPLE_ -#undef GTEST_5_TUPLE_ -#undef GTEST_6_TUPLE_ -#undef GTEST_7_TUPLE_ -#undef GTEST_8_TUPLE_ -#undef GTEST_9_TUPLE_ -#undef GTEST_10_TUPLE_ - -#undef GTEST_0_TYPENAMES_ -#undef GTEST_1_TYPENAMES_ -#undef GTEST_2_TYPENAMES_ -#undef GTEST_3_TYPENAMES_ -#undef GTEST_4_TYPENAMES_ -#undef GTEST_5_TYPENAMES_ -#undef GTEST_6_TYPENAMES_ -#undef GTEST_7_TYPENAMES_ -#undef GTEST_8_TYPENAMES_ -#undef GTEST_9_TYPENAMES_ -#undef GTEST_10_TYPENAMES_ - -#undef GTEST_DECLARE_TUPLE_AS_FRIEND_ -#undef GTEST_BY_REF_ -#undef GTEST_ADD_REF_ -#undef GTEST_TUPLE_ELEMENT_ - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ -# elif GTEST_OS_SYMBIAN - -// On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to -// use STLport's tuple implementation, which unfortunately doesn't -// work as the copy of STLport distributed with Symbian is incomplete. -// By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to -// use its own tuple implementation. -# ifdef BOOST_HAS_TR1_TUPLE -# undef BOOST_HAS_TR1_TUPLE -# endif // BOOST_HAS_TR1_TUPLE - -// This prevents , which defines -// BOOST_HAS_TR1_TUPLE, from being #included by Boost's . -# define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED -# include - -# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) -// GCC 4.0+ implements tr1/tuple in the header. This does -// not conform to the TR1 spec, which requires the header to be . - -# if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 -// Until version 4.3.2, gcc has a bug that causes , -// which is #included by , to not compile when RTTI is -// disabled. _TR1_FUNCTIONAL is the header guard for -// . Hence the following #define is a hack to prevent -// from being included. -# define _TR1_FUNCTIONAL 1 -# include -# undef _TR1_FUNCTIONAL // Allows the user to #include - // if he chooses to. -# else -# include // NOLINT -# endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 - -# else -// If the compiler is not GCC 4.0+, we assume the user is using a -// spec-conforming TR1 implementation. -# include // NOLINT -# endif // GTEST_USE_OWN_TR1_TUPLE - -#endif // GTEST_HAS_TR1_TUPLE - -// Determines whether clone(2) is supported. -// Usually it will only be available on Linux, excluding -// Linux on the Itanium architecture. -// Also see http://linux.die.net/man/2/clone. -#ifndef GTEST_HAS_CLONE -// The user didn't tell us, so we need to figure it out. - -# if GTEST_OS_LINUX && !defined(__ia64__) -# define GTEST_HAS_CLONE 1 -# else -# define GTEST_HAS_CLONE 0 -# endif // GTEST_OS_LINUX && !defined(__ia64__) - -#endif // GTEST_HAS_CLONE - -// Determines whether to support stream redirection. This is used to test -// output correctness and to implement death tests. -#ifndef GTEST_HAS_STREAM_REDIRECTION -// By default, we assume that stream redirection is supported on all -// platforms except known mobile ones. -# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN -# define GTEST_HAS_STREAM_REDIRECTION 0 -# else -# define GTEST_HAS_STREAM_REDIRECTION 1 -# endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN -#endif // GTEST_HAS_STREAM_REDIRECTION - -// Determines whether to support death tests. -// Google Test does not support death tests for VC 7.1 and earlier as -// abort() in a VC 7.1 application compiled as GUI in debug config -// pops up a dialog window that cannot be suppressed programmatically. -#if (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ - (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ - GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX) -# define GTEST_HAS_DEATH_TEST 1 -# include // NOLINT -#endif - -// We don't support MSVC 7.1 with exceptions disabled now. Therefore -// all the compilers we care about are adequate for supporting -// value-parameterized tests. -#define GTEST_HAS_PARAM_TEST 1 - -// Determines whether to support type-driven tests. - -// Typed tests need and variadic macros, which GCC, VC++ 8.0, -// Sun Pro CC, IBM Visual Age, and HP aCC support. -#if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \ - defined(__IBMCPP__) || defined(__HP_aCC) -# define GTEST_HAS_TYPED_TEST 1 -# define GTEST_HAS_TYPED_TEST_P 1 -#endif - -// Determines whether to support Combine(). This only makes sense when -// value-parameterized tests are enabled. The implementation doesn't -// work on Sun Studio since it doesn't understand templated conversion -// operators. -#if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC) -# define GTEST_HAS_COMBINE 1 -#endif - -// Determines whether the system compiler uses UTF-16 for encoding wide strings. -#define GTEST_WIDE_STRING_USES_UTF16_ \ - (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) - -// Determines whether test results can be streamed to a socket. -#if GTEST_OS_LINUX -# define GTEST_CAN_STREAM_RESULTS_ 1 -#endif - -// Defines some utility macros. - -// The GNU compiler emits a warning if nested "if" statements are followed by -// an "else" statement and braces are not used to explicitly disambiguate the -// "else" binding. This leads to problems with code like: -// -// if (gate) -// ASSERT_*(condition) << "Some message"; -// -// The "switch (0) case 0:" idiom is used to suppress this. -#ifdef __INTEL_COMPILER -# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ -#else -# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT -#endif - -// Use this annotation at the end of a struct/class definition to -// prevent the compiler from optimizing away instances that are never -// used. This is useful when all interesting logic happens inside the -// c'tor and / or d'tor. Example: -// -// struct Foo { -// Foo() { ... } -// } GTEST_ATTRIBUTE_UNUSED_; -// -// Also use it after a variable or parameter declaration to tell the -// compiler the variable/parameter does not have to be used. -#if defined(__GNUC__) && !defined(COMPILER_ICC) -# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) -#else -# define GTEST_ATTRIBUTE_UNUSED_ -#endif - -// A macro to disallow operator= -// This should be used in the private: declarations for a class. -#define GTEST_DISALLOW_ASSIGN_(type)\ - void operator=(type const &) - -// A macro to disallow copy constructor and operator= -// This should be used in the private: declarations for a class. -#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\ - type(type const &);\ - GTEST_DISALLOW_ASSIGN_(type) - -// Tell the compiler to warn about unused return values for functions declared -// with this macro. The macro should be used on function declarations -// following the argument list: -// -// Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; -#if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC) -# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) -#else -# define GTEST_MUST_USE_RESULT_ -#endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC - -// Determine whether the compiler supports Microsoft's Structured Exception -// Handling. This is supported by several Windows compilers but generally -// does not exist on any other system. -#ifndef GTEST_HAS_SEH -// The user didn't tell us, so we need to figure it out. - -# if defined(_MSC_VER) || defined(__BORLANDC__) -// These two compilers are known to support SEH. -# define GTEST_HAS_SEH 1 -# else -// Assume no SEH. -# define GTEST_HAS_SEH 0 -# endif - -#endif // GTEST_HAS_SEH - -#ifdef _MSC_VER - -# if GTEST_LINKED_AS_SHARED_LIBRARY -# define GTEST_API_ __declspec(dllimport) -# elif GTEST_CREATE_SHARED_LIBRARY -# define GTEST_API_ __declspec(dllexport) -# endif - -#endif // _MSC_VER - -#ifndef GTEST_API_ -# define GTEST_API_ -#endif - -#ifdef __GNUC__ -// Ask the compiler to never inline a given function. -# define GTEST_NO_INLINE_ __attribute__((noinline)) -#else -# define GTEST_NO_INLINE_ -#endif - -namespace testing { - -class Message; - -namespace internal { - -class String; - -// The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time -// expression is true. For example, you could use it to verify the -// size of a static array: -// -// GTEST_COMPILE_ASSERT_(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES, -// content_type_names_incorrect_size); -// -// or to make sure a struct is smaller than a certain size: -// -// GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large); -// -// The second argument to the macro is the name of the variable. If -// the expression is false, most compilers will issue a warning/error -// containing the name of the variable. - -template -struct CompileAssert { -}; - -#define GTEST_COMPILE_ASSERT_(expr, msg) \ - typedef ::testing::internal::CompileAssert<(bool(expr))> \ - msg[bool(expr) ? 1 : -1] - -// Implementation details of GTEST_COMPILE_ASSERT_: -// -// - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1 -// elements (and thus is invalid) when the expression is false. -// -// - The simpler definition -// -// #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1] -// -// does not work, as gcc supports variable-length arrays whose sizes -// are determined at run-time (this is gcc's extension and not part -// of the C++ standard). As a result, gcc fails to reject the -// following code with the simple definition: -// -// int foo; -// GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is -// // not a compile-time constant. -// -// - By using the type CompileAssert<(bool(expr))>, we ensures that -// expr is a compile-time constant. (Template arguments must be -// determined at compile-time.) -// -// - The outter parentheses in CompileAssert<(bool(expr))> are necessary -// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written -// -// CompileAssert -// -// instead, these compilers will refuse to compile -// -// GTEST_COMPILE_ASSERT_(5 > 0, some_message); -// -// (They seem to think the ">" in "5 > 0" marks the end of the -// template argument list.) -// -// - The array size is (bool(expr) ? 1 : -1), instead of simply -// -// ((expr) ? 1 : -1). -// -// This is to avoid running into a bug in MS VC 7.1, which -// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. - -// StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h. -// -// This template is declared, but intentionally undefined. -template -struct StaticAssertTypeEqHelper; - -template -struct StaticAssertTypeEqHelper {}; - -#if GTEST_HAS_GLOBAL_STRING -typedef ::string string; -#else -typedef ::std::string string; -#endif // GTEST_HAS_GLOBAL_STRING - -#if GTEST_HAS_GLOBAL_WSTRING -typedef ::wstring wstring; -#elif GTEST_HAS_STD_WSTRING -typedef ::std::wstring wstring; -#endif // GTEST_HAS_GLOBAL_WSTRING - -// A helper for suppressing warnings on constant condition. It just -// returns 'condition'. -GTEST_API_ bool IsTrue(bool condition); - -// Defines scoped_ptr. - -// This implementation of scoped_ptr is PARTIAL - it only contains -// enough stuff to satisfy Google Test's need. -template -class scoped_ptr { - public: - typedef T element_type; - - explicit scoped_ptr(T* p = NULL) : ptr_(p) {} - ~scoped_ptr() { reset(); } - - T& operator*() const { return *ptr_; } - T* operator->() const { return ptr_; } - T* get() const { return ptr_; } - - T* release() { - T* const ptr = ptr_; - ptr_ = NULL; - return ptr; - } - - void reset(T* p = NULL) { - if (p != ptr_) { - if (IsTrue(sizeof(T) > 0)) { // Makes sure T is a complete type. - delete ptr_; - } - ptr_ = p; - } - } - private: - T* ptr_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr); -}; - -// Defines RE. - -// A simple C++ wrapper for . It uses the POSIX Extended -// Regular Expression syntax. -class GTEST_API_ RE { - public: - // A copy constructor is required by the Standard to initialize object - // references from r-values. - RE(const RE& other) { Init(other.pattern()); } - - // Constructs an RE from a string. - RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT - -#if GTEST_HAS_GLOBAL_STRING - - RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT - -#endif // GTEST_HAS_GLOBAL_STRING - - RE(const char* regex) { Init(regex); } // NOLINT - ~RE(); - - // Returns the string representation of the regex. - const char* pattern() const { return pattern_; } - - // FullMatch(str, re) returns true iff regular expression re matches - // the entire str. - // PartialMatch(str, re) returns true iff regular expression re - // matches a substring of str (including str itself). - // - // TODO(wan@google.com): make FullMatch() and PartialMatch() work - // when str contains NUL characters. - static bool FullMatch(const ::std::string& str, const RE& re) { - return FullMatch(str.c_str(), re); - } - static bool PartialMatch(const ::std::string& str, const RE& re) { - return PartialMatch(str.c_str(), re); - } - -#if GTEST_HAS_GLOBAL_STRING - - static bool FullMatch(const ::string& str, const RE& re) { - return FullMatch(str.c_str(), re); - } - static bool PartialMatch(const ::string& str, const RE& re) { - return PartialMatch(str.c_str(), re); - } - -#endif // GTEST_HAS_GLOBAL_STRING - - static bool FullMatch(const char* str, const RE& re); - static bool PartialMatch(const char* str, const RE& re); - - private: - void Init(const char* regex); - - // We use a const char* instead of a string, as Google Test may be used - // where string is not available. We also do not use Google Test's own - // String type here, in order to simplify dependencies between the - // files. - const char* pattern_; - bool is_valid_; - -#if GTEST_USES_POSIX_RE - - regex_t full_regex_; // For FullMatch(). - regex_t partial_regex_; // For PartialMatch(). - -#else // GTEST_USES_SIMPLE_RE - - const char* full_pattern_; // For FullMatch(); - -#endif - - GTEST_DISALLOW_ASSIGN_(RE); -}; - -// Formats a source file path and a line number as they would appear -// in an error message from the compiler used to compile this code. -GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); - -// Formats a file location for compiler-independent XML output. -// Although this function is not platform dependent, we put it next to -// FormatFileLocation in order to contrast the two functions. -GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, - int line); - -// Defines logging utilities: -// GTEST_LOG_(severity) - logs messages at the specified severity level. The -// message itself is streamed into the macro. -// LogToStderr() - directs all log messages to stderr. -// FlushInfoLog() - flushes informational log messages. - -enum GTestLogSeverity { - GTEST_INFO, - GTEST_WARNING, - GTEST_ERROR, - GTEST_FATAL -}; - -// Formats log entry severity, provides a stream object for streaming the -// log message, and terminates the message with a newline when going out of -// scope. -class GTEST_API_ GTestLog { - public: - GTestLog(GTestLogSeverity severity, const char* file, int line); - - // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. - ~GTestLog(); - - ::std::ostream& GetStream() { return ::std::cerr; } - - private: - const GTestLogSeverity severity_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog); -}; - -#define GTEST_LOG_(severity) \ - ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ - __FILE__, __LINE__).GetStream() - -inline void LogToStderr() {} -inline void FlushInfoLog() { fflush(NULL); } - -// INTERNAL IMPLEMENTATION - DO NOT USE. -// -// GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition -// is not satisfied. -// Synopsys: -// GTEST_CHECK_(boolean_condition); -// or -// GTEST_CHECK_(boolean_condition) << "Additional message"; -// -// This checks the condition and if the condition is not satisfied -// it prints message about the condition violation, including the -// condition itself, plus additional message streamed into it, if any, -// and then it aborts the program. It aborts the program irrespective of -// whether it is built in the debug mode or not. -#define GTEST_CHECK_(condition) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::IsTrue(condition)) \ - ; \ - else \ - GTEST_LOG_(FATAL) << "Condition " #condition " failed. " - -// An all-mode assert to verify that the given POSIX-style function -// call returns 0 (indicating success). Known limitation: this -// doesn't expand to a balanced 'if' statement, so enclose the macro -// in {} if you need to use it as the only statement in an 'if' -// branch. -#define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ - if (const int gtest_error = (posix_call)) \ - GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ - << gtest_error - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Use ImplicitCast_ as a safe version of static_cast for upcasting in -// the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a -// const Foo*). When you use ImplicitCast_, the compiler checks that -// the cast is safe. Such explicit ImplicitCast_s are necessary in -// surprisingly many situations where C++ demands an exact type match -// instead of an argument type convertable to a target type. -// -// The syntax for using ImplicitCast_ is the same as for static_cast: -// -// ImplicitCast_(expr) -// -// ImplicitCast_ would have been part of the C++ standard library, -// but the proposal was submitted too late. It will probably make -// its way into the language in the future. -// -// This relatively ugly name is intentional. It prevents clashes with -// similar functions users may have (e.g., implicit_cast). The internal -// namespace alone is not enough because the function can be found by ADL. -template -inline To ImplicitCast_(To x) { return x; } - -// When you upcast (that is, cast a pointer from type Foo to type -// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts -// always succeed. When you downcast (that is, cast a pointer from -// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because -// how do you know the pointer is really of type SubclassOfFoo? It -// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, -// when you downcast, you should use this macro. In debug mode, we -// use dynamic_cast<> to double-check the downcast is legal (we die -// if it's not). In normal mode, we do the efficient static_cast<> -// instead. Thus, it's important to test in debug mode to make sure -// the cast is legal! -// This is the only place in the code we should use dynamic_cast<>. -// In particular, you SHOULDN'T be using dynamic_cast<> in order to -// do RTTI (eg code like this: -// if (dynamic_cast(foo)) HandleASubclass1Object(foo); -// if (dynamic_cast(foo)) HandleASubclass2Object(foo); -// You should design the code some other way not to need this. -// -// This relatively ugly name is intentional. It prevents clashes with -// similar functions users may have (e.g., down_cast). The internal -// namespace alone is not enough because the function can be found by ADL. -template // use like this: DownCast_(foo); -inline To DownCast_(From* f) { // so we only accept pointers - // Ensures that To is a sub-type of From *. This test is here only - // for compile-time type checking, and has no overhead in an - // optimized build at run-time, as it will be optimized away - // completely. - if (false) { - const To to = NULL; - ::testing::internal::ImplicitCast_(to); - } - -#if GTEST_HAS_RTTI - // RTTI: debug mode only! - GTEST_CHECK_(f == NULL || dynamic_cast(f) != NULL); -#endif - return static_cast(f); -} - -// Downcasts the pointer of type Base to Derived. -// Derived must be a subclass of Base. The parameter MUST -// point to a class of type Derived, not any subclass of it. -// When RTTI is available, the function performs a runtime -// check to enforce this. -template -Derived* CheckedDowncastToActualType(Base* base) { -#if GTEST_HAS_RTTI - GTEST_CHECK_(typeid(*base) == typeid(Derived)); - return dynamic_cast(base); // NOLINT -#else - return static_cast(base); // Poor man's downcast. -#endif -} - -#if GTEST_HAS_STREAM_REDIRECTION - -// Defines the stderr capturer: -// CaptureStdout - starts capturing stdout. -// GetCapturedStdout - stops capturing stdout and returns the captured string. -// CaptureStderr - starts capturing stderr. -// GetCapturedStderr - stops capturing stderr and returns the captured string. -// -GTEST_API_ void CaptureStdout(); -GTEST_API_ String GetCapturedStdout(); -GTEST_API_ void CaptureStderr(); -GTEST_API_ String GetCapturedStderr(); - -#endif // GTEST_HAS_STREAM_REDIRECTION - - -#if GTEST_HAS_DEATH_TEST - -// A copy of all command line arguments. Set by InitGoogleTest(). -extern ::std::vector g_argvs; - -// GTEST_HAS_DEATH_TEST implies we have ::std::string. -const ::std::vector& GetArgvs(); - -#endif // GTEST_HAS_DEATH_TEST - -// Defines synchronization primitives. - -#if GTEST_HAS_PTHREAD - -// Sleeps for (roughly) n milli-seconds. This function is only for -// testing Google Test's own constructs. Don't use it in user tests, -// either directly or indirectly. -inline void SleepMilliseconds(int n) { - const timespec time = { - 0, // 0 seconds. - n * 1000L * 1000L, // And n ms. - }; - nanosleep(&time, NULL); -} - -// Allows a controller thread to pause execution of newly created -// threads until notified. Instances of this class must be created -// and destroyed in the controller thread. -// -// This class is only for testing Google Test's own constructs. Do not -// use it in user tests, either directly or indirectly. -class Notification { - public: - Notification() : notified_(false) {} - - // Notifies all threads created with this notification to start. Must - // be called from the controller thread. - void Notify() { notified_ = true; } - - // Blocks until the controller thread notifies. Must be called from a test - // thread. - void WaitForNotification() { - while(!notified_) { - SleepMilliseconds(10); - } - } - - private: - volatile bool notified_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); -}; - -// As a C-function, ThreadFuncWithCLinkage cannot be templated itself. -// Consequently, it cannot select a correct instantiation of ThreadWithParam -// in order to call its Run(). Introducing ThreadWithParamBase as a -// non-templated base class for ThreadWithParam allows us to bypass this -// problem. -class ThreadWithParamBase { - public: - virtual ~ThreadWithParamBase() {} - virtual void Run() = 0; -}; - -// pthread_create() accepts a pointer to a function type with the C linkage. -// According to the Standard (7.5/1), function types with different linkages -// are different even if they are otherwise identical. Some compilers (for -// example, SunStudio) treat them as different types. Since class methods -// cannot be defined with C-linkage we need to define a free C-function to -// pass into pthread_create(). -extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { - static_cast(thread)->Run(); - return NULL; -} - -// Helper class for testing Google Test's multi-threading constructs. -// To use it, write: -// -// void ThreadFunc(int param) { /* Do things with param */ } -// Notification thread_can_start; -// ... -// // The thread_can_start parameter is optional; you can supply NULL. -// ThreadWithParam thread(&ThreadFunc, 5, &thread_can_start); -// thread_can_start.Notify(); -// -// These classes are only for testing Google Test's own constructs. Do -// not use them in user tests, either directly or indirectly. -template -class ThreadWithParam : public ThreadWithParamBase { - public: - typedef void (*UserThreadFunc)(T); - - ThreadWithParam( - UserThreadFunc func, T param, Notification* thread_can_start) - : func_(func), - param_(param), - thread_can_start_(thread_can_start), - finished_(false) { - ThreadWithParamBase* const base = this; - // The thread can be created only after all fields except thread_ - // have been initialized. - GTEST_CHECK_POSIX_SUCCESS_( - pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); - } - ~ThreadWithParam() { Join(); } - - void Join() { - if (!finished_) { - GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0)); - finished_ = true; - } - } - - virtual void Run() { - if (thread_can_start_ != NULL) - thread_can_start_->WaitForNotification(); - func_(param_); - } - - private: - const UserThreadFunc func_; // User-supplied thread function. - const T param_; // User-supplied parameter to the thread function. - // When non-NULL, used to block execution until the controller thread - // notifies. - Notification* const thread_can_start_; - bool finished_; // true iff we know that the thread function has finished. - pthread_t thread_; // The native thread object. - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); -}; - -// MutexBase and Mutex implement mutex on pthreads-based platforms. They -// are used in conjunction with class MutexLock: -// -// Mutex mutex; -// ... -// MutexLock lock(&mutex); // Acquires the mutex and releases it at the end -// // of the current scope. -// -// MutexBase implements behavior for both statically and dynamically -// allocated mutexes. Do not use MutexBase directly. Instead, write -// the following to define a static mutex: -// -// GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); -// -// You can forward declare a static mutex like this: -// -// GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); -// -// To create a dynamic mutex, just define an object of type Mutex. -class MutexBase { - public: - // Acquires this mutex. - void Lock() { - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); - owner_ = pthread_self(); - } - - // Releases this mutex. - void Unlock() { - // We don't protect writing to owner_ here, as it's the caller's - // responsibility to ensure that the current thread holds the - // mutex when this is called. - owner_ = 0; - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); - } - - // Does nothing if the current thread holds the mutex. Otherwise, crashes - // with high probability. - void AssertHeld() const { - GTEST_CHECK_(owner_ == pthread_self()) - << "The current thread is not holding the mutex @" << this; - } - - // A static mutex may be used before main() is entered. It may even - // be used before the dynamic initialization stage. Therefore we - // must be able to initialize a static mutex object at link time. - // This means MutexBase has to be a POD and its member variables - // have to be public. - public: - pthread_mutex_t mutex_; // The underlying pthread mutex. - pthread_t owner_; // The thread holding the mutex; 0 means no one holds it. -}; - -// Forward-declares a static mutex. -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ - extern ::testing::internal::MutexBase mutex - -// Defines and statically (i.e. at link time) initializes a static mutex. -# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ - ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, 0 } - -// The Mutex class can only be used for mutexes created at runtime. It -// shares its API with MutexBase otherwise. -class Mutex : public MutexBase { - public: - Mutex() { - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); - owner_ = 0; - } - ~Mutex() { - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); - } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); -}; - -// We cannot name this class MutexLock as the ctor declaration would -// conflict with a macro named MutexLock, which is defined on some -// platforms. Hence the typedef trick below. -class GTestMutexLock { - public: - explicit GTestMutexLock(MutexBase* mutex) - : mutex_(mutex) { mutex_->Lock(); } - - ~GTestMutexLock() { mutex_->Unlock(); } - - private: - MutexBase* const mutex_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); -}; - -typedef GTestMutexLock MutexLock; - -// Helpers for ThreadLocal. - -// pthread_key_create() requires DeleteThreadLocalValue() to have -// C-linkage. Therefore it cannot be templatized to access -// ThreadLocal. Hence the need for class -// ThreadLocalValueHolderBase. -class ThreadLocalValueHolderBase { - public: - virtual ~ThreadLocalValueHolderBase() {} -}; - -// Called by pthread to delete thread-local data stored by -// pthread_setspecific(). -extern "C" inline void DeleteThreadLocalValue(void* value_holder) { - delete static_cast(value_holder); -} - -// Implements thread-local storage on pthreads-based systems. -// -// // Thread 1 -// ThreadLocal tl(100); // 100 is the default value for each thread. -// -// // Thread 2 -// tl.set(150); // Changes the value for thread 2 only. -// EXPECT_EQ(150, tl.get()); -// -// // Thread 1 -// EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. -// tl.set(200); -// EXPECT_EQ(200, tl.get()); -// -// The template type argument T must have a public copy constructor. -// In addition, the default ThreadLocal constructor requires T to have -// a public default constructor. -// -// An object managed for a thread by a ThreadLocal instance is deleted -// when the thread exits. Or, if the ThreadLocal instance dies in -// that thread, when the ThreadLocal dies. It's the user's -// responsibility to ensure that all other threads using a ThreadLocal -// have exited when it dies, or the per-thread objects for those -// threads will not be deleted. -// -// Google Test only uses global ThreadLocal objects. That means they -// will die after main() has returned. Therefore, no per-thread -// object managed by Google Test will be leaked as long as all threads -// using Google Test have exited when main() returns. -template -class ThreadLocal { - public: - ThreadLocal() : key_(CreateKey()), - default_() {} - explicit ThreadLocal(const T& value) : key_(CreateKey()), - default_(value) {} - - ~ThreadLocal() { - // Destroys the managed object for the current thread, if any. - DeleteThreadLocalValue(pthread_getspecific(key_)); - - // Releases resources associated with the key. This will *not* - // delete managed objects for other threads. - GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_)); - } - - T* pointer() { return GetOrCreateValue(); } - const T* pointer() const { return GetOrCreateValue(); } - const T& get() const { return *pointer(); } - void set(const T& value) { *pointer() = value; } - - private: - // Holds a value of type T. - class ValueHolder : public ThreadLocalValueHolderBase { - public: - explicit ValueHolder(const T& value) : value_(value) {} - - T* pointer() { return &value_; } - - private: - T value_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); - }; - - static pthread_key_t CreateKey() { - pthread_key_t key; - // When a thread exits, DeleteThreadLocalValue() will be called on - // the object managed for that thread. - GTEST_CHECK_POSIX_SUCCESS_( - pthread_key_create(&key, &DeleteThreadLocalValue)); - return key; - } - - T* GetOrCreateValue() const { - ThreadLocalValueHolderBase* const holder = - static_cast(pthread_getspecific(key_)); - if (holder != NULL) { - return CheckedDowncastToActualType(holder)->pointer(); - } - - ValueHolder* const new_holder = new ValueHolder(default_); - ThreadLocalValueHolderBase* const holder_base = new_holder; - GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); - return new_holder->pointer(); - } - - // A key pthreads uses for looking up per-thread values. - const pthread_key_t key_; - const T default_; // The default value for each thread. - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); -}; - -# define GTEST_IS_THREADSAFE 1 - -#else // GTEST_HAS_PTHREAD - -// A dummy implementation of synchronization primitives (mutex, lock, -// and thread-local variable). Necessary for compiling Google Test where -// mutex is not supported - using Google Test in multiple threads is not -// supported on such platforms. - -class Mutex { - public: - Mutex() {} - void AssertHeld() const {} -}; - -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ - extern ::testing::internal::Mutex mutex - -# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex - -class GTestMutexLock { - public: - explicit GTestMutexLock(Mutex*) {} // NOLINT -}; - -typedef GTestMutexLock MutexLock; - -template -class ThreadLocal { - public: - ThreadLocal() : value_() {} - explicit ThreadLocal(const T& value) : value_(value) {} - T* pointer() { return &value_; } - const T* pointer() const { return &value_; } - const T& get() const { return value_; } - void set(const T& value) { value_ = value; } - private: - T value_; -}; - -// The above synchronization primitives have dummy implementations. -// Therefore Google Test is not thread-safe. -# define GTEST_IS_THREADSAFE 0 - -#endif // GTEST_HAS_PTHREAD - -// Returns the number of threads running in the process, or 0 to indicate that -// we cannot detect it. -GTEST_API_ size_t GetThreadCount(); - -// Passing non-POD classes through ellipsis (...) crashes the ARM -// compiler and generates a warning in Sun Studio. The Nokia Symbian -// and the IBM XL C/C++ compiler try to instantiate a copy constructor -// for objects passed through ellipsis (...), failing for uncopyable -// objects. We define this to ensure that only POD is passed through -// ellipsis on these systems. -#if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC) -// We lose support for NULL detection where the compiler doesn't like -// passing non-POD classes through ellipsis (...). -# define GTEST_ELLIPSIS_NEEDS_POD_ 1 -#else -# define GTEST_CAN_COMPARE_NULL 1 -#endif - -// The Nokia Symbian and IBM XL C/C++ compilers cannot decide between -// const T& and const T* in a function template. These compilers -// _can_ decide between class template specializations for T and T*, -// so a tr1::type_traits-like is_pointer works. -#if defined(__SYMBIAN32__) || defined(__IBMCPP__) -# define GTEST_NEEDS_IS_POINTER_ 1 -#endif - -template -struct bool_constant { - typedef bool_constant type; - static const bool value = bool_value; -}; -template const bool bool_constant::value; - -typedef bool_constant false_type; -typedef bool_constant true_type; - -template -struct is_pointer : public false_type {}; - -template -struct is_pointer : public true_type {}; - -template -struct IteratorTraits { - typedef typename Iterator::value_type value_type; -}; - -template -struct IteratorTraits { - typedef T value_type; -}; - -template -struct IteratorTraits { - typedef T value_type; -}; - -#if GTEST_OS_WINDOWS -# define GTEST_PATH_SEP_ "\\" -# define GTEST_HAS_ALT_PATH_SEP_ 1 -// The biggest signed integer type the compiler supports. -typedef __int64 BiggestInt; -#else -# define GTEST_PATH_SEP_ "/" -# define GTEST_HAS_ALT_PATH_SEP_ 0 -typedef long long BiggestInt; // NOLINT -#endif // GTEST_OS_WINDOWS - -// Utilities for char. - -// isspace(int ch) and friends accept an unsigned char or EOF. char -// may be signed, depending on the compiler (or compiler flags). -// Therefore we need to cast a char to unsigned char before calling -// isspace(), etc. - -inline bool IsAlpha(char ch) { - return isalpha(static_cast(ch)) != 0; -} -inline bool IsAlNum(char ch) { - return isalnum(static_cast(ch)) != 0; -} -inline bool IsDigit(char ch) { - return isdigit(static_cast(ch)) != 0; -} -inline bool IsLower(char ch) { - return islower(static_cast(ch)) != 0; -} -inline bool IsSpace(char ch) { - return isspace(static_cast(ch)) != 0; -} -inline bool IsUpper(char ch) { - return isupper(static_cast(ch)) != 0; -} -inline bool IsXDigit(char ch) { - return isxdigit(static_cast(ch)) != 0; -} - -inline char ToLower(char ch) { - return static_cast(tolower(static_cast(ch))); -} -inline char ToUpper(char ch) { - return static_cast(toupper(static_cast(ch))); -} - -// The testing::internal::posix namespace holds wrappers for common -// POSIX functions. These wrappers hide the differences between -// Windows/MSVC and POSIX systems. Since some compilers define these -// standard functions as macros, the wrapper cannot have the same name -// as the wrapped function. - -namespace posix { - -// Functions with a different name on Windows. - -#if GTEST_OS_WINDOWS - -typedef struct _stat StatStruct; - -# ifdef __BORLANDC__ -inline int IsATTY(int fd) { return isatty(fd); } -inline int StrCaseCmp(const char* s1, const char* s2) { - return stricmp(s1, s2); -} -inline char* StrDup(const char* src) { return strdup(src); } -# else // !__BORLANDC__ -# if GTEST_OS_WINDOWS_MOBILE -inline int IsATTY(int /* fd */) { return 0; } -# else -inline int IsATTY(int fd) { return _isatty(fd); } -# endif // GTEST_OS_WINDOWS_MOBILE -inline int StrCaseCmp(const char* s1, const char* s2) { - return _stricmp(s1, s2); -} -inline char* StrDup(const char* src) { return _strdup(src); } -# endif // __BORLANDC__ - -# if GTEST_OS_WINDOWS_MOBILE -inline int FileNo(FILE* file) { return reinterpret_cast(_fileno(file)); } -// Stat(), RmDir(), and IsDir() are not needed on Windows CE at this -// time and thus not defined there. -# else -inline int FileNo(FILE* file) { return _fileno(file); } -inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } -inline int RmDir(const char* dir) { return _rmdir(dir); } -inline bool IsDir(const StatStruct& st) { - return (_S_IFDIR & st.st_mode) != 0; -} -# endif // GTEST_OS_WINDOWS_MOBILE - -#else - -typedef struct stat StatStruct; - -inline int FileNo(FILE* file) { return fileno(file); } -inline int IsATTY(int fd) { return isatty(fd); } -inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } -inline int StrCaseCmp(const char* s1, const char* s2) { - return strcasecmp(s1, s2); -} -inline char* StrDup(const char* src) { return strdup(src); } -inline int RmDir(const char* dir) { return rmdir(dir); } -inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } - -#endif // GTEST_OS_WINDOWS - -// Functions deprecated by MSVC 8.0. - -#ifdef _MSC_VER -// Temporarily disable warning 4996 (deprecated function). -# pragma warning(push) -# pragma warning(disable:4996) -#endif - -inline const char* StrNCpy(char* dest, const char* src, size_t n) { - return strncpy(dest, src, n); -} - -// ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and -// StrError() aren't needed on Windows CE at this time and thus not -// defined there. - -#if !GTEST_OS_WINDOWS_MOBILE -inline int ChDir(const char* dir) { return chdir(dir); } -#endif -inline FILE* FOpen(const char* path, const char* mode) { - return fopen(path, mode); -} -#if !GTEST_OS_WINDOWS_MOBILE -inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { - return freopen(path, mode, stream); -} -inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } -#endif -inline int FClose(FILE* fp) { return fclose(fp); } -#if !GTEST_OS_WINDOWS_MOBILE -inline int Read(int fd, void* buf, unsigned int count) { - return static_cast(read(fd, buf, count)); -} -inline int Write(int fd, const void* buf, unsigned int count) { - return static_cast(write(fd, buf, count)); -} -inline int Close(int fd) { return close(fd); } -inline const char* StrError(int errnum) { return strerror(errnum); } -#endif -inline const char* GetEnv(const char* name) { -#if GTEST_OS_WINDOWS_MOBILE - // We are on Windows CE, which has no environment variables. - return NULL; -#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) - // Environment variables which we programmatically clear will be set to the - // empty string rather than unset (NULL). Handle that case. - const char* const env = getenv(name); - return (env != NULL && env[0] != '\0') ? env : NULL; -#else - return getenv(name); -#endif -} - -#ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif - -#if GTEST_OS_WINDOWS_MOBILE -// Windows CE has no C library. The abort() function is used in -// several places in Google Test. This implementation provides a reasonable -// imitation of standard behaviour. -void Abort(); -#else -inline void Abort() { abort(); } -#endif // GTEST_OS_WINDOWS_MOBILE - -} // namespace posix - -// The maximum number a BiggestInt can represent. This definition -// works no matter BiggestInt is represented in one's complement or -// two's complement. -// -// We cannot rely on numeric_limits in STL, as __int64 and long long -// are not part of standard C++ and numeric_limits doesn't need to be -// defined for them. -const BiggestInt kMaxBiggestInt = - ~(static_cast(1) << (8*sizeof(BiggestInt) - 1)); - -// This template class serves as a compile-time function from size to -// type. It maps a size in bytes to a primitive type with that -// size. e.g. -// -// TypeWithSize<4>::UInt -// -// is typedef-ed to be unsigned int (unsigned integer made up of 4 -// bytes). -// -// Such functionality should belong to STL, but I cannot find it -// there. -// -// Google Test uses this class in the implementation of floating-point -// comparison. -// -// For now it only handles UInt (unsigned int) as that's all Google Test -// needs. Other types can be easily added in the future if need -// arises. -template -class TypeWithSize { - public: - // This prevents the user from using TypeWithSize with incorrect - // values of N. - typedef void UInt; -}; - -// The specialization for size 4. -template <> -class TypeWithSize<4> { - public: - // unsigned int has size 4 in both gcc and MSVC. - // - // As base/basictypes.h doesn't compile on Windows, we cannot use - // uint32, uint64, and etc here. - typedef int Int; - typedef unsigned int UInt; -}; - -// The specialization for size 8. -template <> -class TypeWithSize<8> { - public: - -#if GTEST_OS_WINDOWS - typedef __int64 Int; - typedef unsigned __int64 UInt; -#else - typedef long long Int; // NOLINT - typedef unsigned long long UInt; // NOLINT -#endif // GTEST_OS_WINDOWS -}; - -// Integer types of known sizes. -typedef TypeWithSize<4>::Int Int32; -typedef TypeWithSize<4>::UInt UInt32; -typedef TypeWithSize<8>::Int Int64; -typedef TypeWithSize<8>::UInt UInt64; -typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. - -// Utilities for command line flags and environment variables. - -// Macro for referencing flags. -#define GTEST_FLAG(name) FLAGS_gtest_##name - -// Macros for declaring flags. -#define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) -#define GTEST_DECLARE_int32_(name) \ - GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) -#define GTEST_DECLARE_string_(name) \ - GTEST_API_ extern ::testing::internal::String GTEST_FLAG(name) - -// Macros for defining flags. -#define GTEST_DEFINE_bool_(name, default_val, doc) \ - GTEST_API_ bool GTEST_FLAG(name) = (default_val) -#define GTEST_DEFINE_int32_(name, default_val, doc) \ - GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) -#define GTEST_DEFINE_string_(name, default_val, doc) \ - GTEST_API_ ::testing::internal::String GTEST_FLAG(name) = (default_val) - -// Parses 'str' for a 32-bit signed integer. If successful, writes the result -// to *value and returns true; otherwise leaves *value unchanged and returns -// false. -// TODO(chandlerc): Find a better way to refactor flag and environment parsing -// out of both gtest-port.cc and gtest.cc to avoid exporting this utility -// function. -bool ParseInt32(const Message& src_text, const char* str, Int32* value); - -// Parses a bool/Int32/string from the environment variable -// corresponding to the given Google Test flag. -bool BoolFromGTestEnv(const char* flag, bool default_val); -GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); -const char* StringFromGTestEnv(const char* flag, const char* default_val); - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ - -#if GTEST_OS_LINUX -# include -# include -# include -# include -#endif // GTEST_OS_LINUX - -#include -#include -#include -#include -#include - -// Copyright 2005, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) -// -// The Google C++ Testing Framework (Google Test) -// -// This header file declares the String class and functions used internally by -// Google Test. They are subject to change without notice. They should not used -// by code external to Google Test. -// -// This header file is #included by . -// It should not be #included by other files. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ - -#ifdef __BORLANDC__ -// string.h is not guaranteed to provide strcpy on C++ Builder. -# include -#endif - -#include - -#include - -namespace testing { -namespace internal { - -// String - a UTF-8 string class. -// -// For historic reasons, we don't use std::string. -// -// TODO(wan@google.com): replace this class with std::string or -// implement it in terms of the latter. -// -// Note that String can represent both NULL and the empty string, -// while std::string cannot represent NULL. -// -// NULL and the empty string are considered different. NULL is less -// than anything (including the empty string) except itself. -// -// This class only provides minimum functionality necessary for -// implementing Google Test. We do not intend to implement a full-fledged -// string class here. -// -// Since the purpose of this class is to provide a substitute for -// std::string on platforms where it cannot be used, we define a copy -// constructor and assignment operators such that we don't need -// conditional compilation in a lot of places. -// -// In order to make the representation efficient, the d'tor of String -// is not virtual. Therefore DO NOT INHERIT FROM String. -class GTEST_API_ String { - public: - // Static utility methods - - // Returns the input enclosed in double quotes if it's not NULL; - // otherwise returns "(null)". For example, "\"Hello\"" is returned - // for input "Hello". - // - // This is useful for printing a C string in the syntax of a literal. - // - // Known issue: escape sequences are not handled yet. - static String ShowCStringQuoted(const char* c_str); - - // Clones a 0-terminated C string, allocating memory using new. The - // caller is responsible for deleting the return value using - // delete[]. Returns the cloned string, or NULL if the input is - // NULL. - // - // This is different from strdup() in string.h, which allocates - // memory using malloc(). - static const char* CloneCString(const char* c_str); - -#if GTEST_OS_WINDOWS_MOBILE - // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be - // able to pass strings to Win32 APIs on CE we need to convert them - // to 'Unicode', UTF-16. - - // Creates a UTF-16 wide string from the given ANSI string, allocating - // memory using new. The caller is responsible for deleting the return - // value using delete[]. Returns the wide string, or NULL if the - // input is NULL. - // - // The wide string is created using the ANSI codepage (CP_ACP) to - // match the behaviour of the ANSI versions of Win32 calls and the - // C runtime. - static LPCWSTR AnsiToUtf16(const char* c_str); - - // Creates an ANSI string from the given wide string, allocating - // memory using new. The caller is responsible for deleting the return - // value using delete[]. Returns the ANSI string, or NULL if the - // input is NULL. - // - // The returned string is created using the ANSI codepage (CP_ACP) to - // match the behaviour of the ANSI versions of Win32 calls and the - // C runtime. - static const char* Utf16ToAnsi(LPCWSTR utf16_str); -#endif - - // Compares two C strings. Returns true iff they have the same content. - // - // Unlike strcmp(), this function can handle NULL argument(s). A - // NULL C string is considered different to any non-NULL C string, - // including the empty string. - static bool CStringEquals(const char* lhs, const char* rhs); - - // Converts a wide C string to a String using the UTF-8 encoding. - // NULL will be converted to "(null)". If an error occurred during - // the conversion, "(failed to convert from wide string)" is - // returned. - static String ShowWideCString(const wchar_t* wide_c_str); - - // Similar to ShowWideCString(), except that this function encloses - // the converted string in double quotes. - static String ShowWideCStringQuoted(const wchar_t* wide_c_str); - - // Compares two wide C strings. Returns true iff they have the same - // content. - // - // Unlike wcscmp(), this function can handle NULL argument(s). A - // NULL C string is considered different to any non-NULL C string, - // including the empty string. - static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); - - // Compares two C strings, ignoring case. Returns true iff they - // have the same content. - // - // Unlike strcasecmp(), this function can handle NULL argument(s). - // A NULL C string is considered different to any non-NULL C string, - // including the empty string. - static bool CaseInsensitiveCStringEquals(const char* lhs, - const char* rhs); - - // Compares two wide C strings, ignoring case. Returns true iff they - // have the same content. - // - // Unlike wcscasecmp(), this function can handle NULL argument(s). - // A NULL C string is considered different to any non-NULL wide C string, - // including the empty string. - // NB: The implementations on different platforms slightly differ. - // On windows, this method uses _wcsicmp which compares according to LC_CTYPE - // environment variable. On GNU platform this method uses wcscasecmp - // which compares according to LC_CTYPE category of the current locale. - // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the - // current locale. - static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, - const wchar_t* rhs); - - // Formats a list of arguments to a String, using the same format - // spec string as for printf. - // - // We do not use the StringPrintf class as it is not universally - // available. - // - // The result is limited to 4096 characters (including the tailing - // 0). If 4096 characters are not enough to format the input, - // "" is returned. - static String Format(const char* format, ...); - - // C'tors - - // The default c'tor constructs a NULL string. - String() : c_str_(NULL), length_(0) {} - - // Constructs a String by cloning a 0-terminated C string. - String(const char* a_c_str) { // NOLINT - if (a_c_str == NULL) { - c_str_ = NULL; - length_ = 0; - } else { - ConstructNonNull(a_c_str, strlen(a_c_str)); - } - } - - // Constructs a String by copying a given number of chars from a - // buffer. E.g. String("hello", 3) creates the string "hel", - // String("a\0bcd", 4) creates "a\0bc", String(NULL, 0) creates "", - // and String(NULL, 1) results in access violation. - String(const char* buffer, size_t a_length) { - ConstructNonNull(buffer, a_length); - } - - // The copy c'tor creates a new copy of the string. The two - // String objects do not share content. - String(const String& str) : c_str_(NULL), length_(0) { *this = str; } - - // D'tor. String is intended to be a final class, so the d'tor - // doesn't need to be virtual. - ~String() { delete[] c_str_; } - - // Allows a String to be implicitly converted to an ::std::string or - // ::string, and vice versa. Converting a String containing a NULL - // pointer to ::std::string or ::string is undefined behavior. - // Converting a ::std::string or ::string containing an embedded NUL - // character to a String will result in the prefix up to the first - // NUL character. - String(const ::std::string& str) { - ConstructNonNull(str.c_str(), str.length()); - } - - operator ::std::string() const { return ::std::string(c_str(), length()); } - -#if GTEST_HAS_GLOBAL_STRING - String(const ::string& str) { - ConstructNonNull(str.c_str(), str.length()); - } - - operator ::string() const { return ::string(c_str(), length()); } -#endif // GTEST_HAS_GLOBAL_STRING - - // Returns true iff this is an empty string (i.e. ""). - bool empty() const { return (c_str() != NULL) && (length() == 0); } - - // Compares this with another String. - // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0 - // if this is greater than rhs. - int Compare(const String& rhs) const; - - // Returns true iff this String equals the given C string. A NULL - // string and a non-NULL string are considered not equal. - bool operator==(const char* a_c_str) const { return Compare(a_c_str) == 0; } - - // Returns true iff this String is less than the given String. A - // NULL string is considered less than "". - bool operator<(const String& rhs) const { return Compare(rhs) < 0; } - - // Returns true iff this String doesn't equal the given C string. A NULL - // string and a non-NULL string are considered not equal. - bool operator!=(const char* a_c_str) const { return !(*this == a_c_str); } - - // Returns true iff this String ends with the given suffix. *Any* - // String is considered to end with a NULL or empty suffix. - bool EndsWith(const char* suffix) const; - - // Returns true iff this String ends with the given suffix, not considering - // case. Any String is considered to end with a NULL or empty suffix. - bool EndsWithCaseInsensitive(const char* suffix) const; - - // Returns the length of the encapsulated string, or 0 if the - // string is NULL. - size_t length() const { return length_; } - - // Gets the 0-terminated C string this String object represents. - // The String object still owns the string. Therefore the caller - // should NOT delete the return value. - const char* c_str() const { return c_str_; } - - // Assigns a C string to this object. Self-assignment works. - const String& operator=(const char* a_c_str) { - return *this = String(a_c_str); - } - - // Assigns a String object to this object. Self-assignment works. - const String& operator=(const String& rhs) { - if (this != &rhs) { - delete[] c_str_; - if (rhs.c_str() == NULL) { - c_str_ = NULL; - length_ = 0; - } else { - ConstructNonNull(rhs.c_str(), rhs.length()); - } - } - - return *this; - } - - private: - // Constructs a non-NULL String from the given content. This - // function can only be called when c_str_ has not been allocated. - // ConstructNonNull(NULL, 0) results in an empty string (""). - // ConstructNonNull(NULL, non_zero) is undefined behavior. - void ConstructNonNull(const char* buffer, size_t a_length) { - char* const str = new char[a_length + 1]; - memcpy(str, buffer, a_length); - str[a_length] = '\0'; - c_str_ = str; - length_ = a_length; - } - - const char* c_str_; - size_t length_; -}; // class String - -// Streams a String to an ostream. Each '\0' character in the String -// is replaced with "\\0". -inline ::std::ostream& operator<<(::std::ostream& os, const String& str) { - if (str.c_str() == NULL) { - os << "(null)"; - } else { - const char* const c_str = str.c_str(); - for (size_t i = 0; i != str.length(); i++) { - if (c_str[i] == '\0') { - os << "\\0"; - } else { - os << c_str[i]; - } - } - } - return os; -} - -// Gets the content of the stringstream's buffer as a String. Each '\0' -// character in the buffer is replaced with "\\0". -GTEST_API_ String StringStreamToString(::std::stringstream* stream); - -// Converts a streamable value to a String. A NULL pointer is -// converted to "(null)". When the input value is a ::string, -// ::std::string, ::wstring, or ::std::wstring object, each NUL -// character in it is replaced with "\\0". - -// Declared here but defined in gtest.h, so that it has access -// to the definition of the Message class, required by the ARM -// compiler. -template -String StreamableToString(const T& streamable); - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ -// Copyright 2008, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: keith.ray@gmail.com (Keith Ray) -// -// Google Test filepath utilities -// -// This header file declares classes and functions used internally by -// Google Test. They are subject to change without notice. -// -// This file is #included in . -// Do not include this header file separately! - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ - - -namespace testing { -namespace internal { - -// FilePath - a class for file and directory pathname manipulation which -// handles platform-specific conventions (like the pathname separator). -// Used for helper functions for naming files in a directory for xml output. -// Except for Set methods, all methods are const or static, which provides an -// "immutable value object" -- useful for peace of mind. -// A FilePath with a value ending in a path separator ("like/this/") represents -// a directory, otherwise it is assumed to represent a file. In either case, -// it may or may not represent an actual file or directory in the file system. -// Names are NOT checked for syntax correctness -- no checking for illegal -// characters, malformed paths, etc. - -class GTEST_API_ FilePath { - public: - FilePath() : pathname_("") { } - FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } - - explicit FilePath(const char* pathname) : pathname_(pathname) { - Normalize(); - } - - explicit FilePath(const String& pathname) : pathname_(pathname) { - Normalize(); - } - - FilePath& operator=(const FilePath& rhs) { - Set(rhs); - return *this; - } - - void Set(const FilePath& rhs) { - pathname_ = rhs.pathname_; - } - - String ToString() const { return pathname_; } - const char* c_str() const { return pathname_.c_str(); } - - // Returns the current working directory, or "" if unsuccessful. - static FilePath GetCurrentDir(); - - // Given directory = "dir", base_name = "test", number = 0, - // extension = "xml", returns "dir/test.xml". If number is greater - // than zero (e.g., 12), returns "dir/test_12.xml". - // On Windows platform, uses \ as the separator rather than /. - static FilePath MakeFileName(const FilePath& directory, - const FilePath& base_name, - int number, - const char* extension); - - // Given directory = "dir", relative_path = "test.xml", - // returns "dir/test.xml". - // On Windows, uses \ as the separator rather than /. - static FilePath ConcatPaths(const FilePath& directory, - const FilePath& relative_path); - - // Returns a pathname for a file that does not currently exist. The pathname - // will be directory/base_name.extension or - // directory/base_name_.extension if directory/base_name.extension - // already exists. The number will be incremented until a pathname is found - // that does not already exist. - // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. - // There could be a race condition if two or more processes are calling this - // function at the same time -- they could both pick the same filename. - static FilePath GenerateUniqueFileName(const FilePath& directory, - const FilePath& base_name, - const char* extension); - - // Returns true iff the path is NULL or "". - bool IsEmpty() const { return c_str() == NULL || *c_str() == '\0'; } - - // If input name has a trailing separator character, removes it and returns - // the name, otherwise return the name string unmodified. - // On Windows platform, uses \ as the separator, other platforms use /. - FilePath RemoveTrailingPathSeparator() const; - - // Returns a copy of the FilePath with the directory part removed. - // Example: FilePath("path/to/file").RemoveDirectoryName() returns - // FilePath("file"). If there is no directory part ("just_a_file"), it returns - // the FilePath unmodified. If there is no file part ("just_a_dir/") it - // returns an empty FilePath (""). - // On Windows platform, '\' is the path separator, otherwise it is '/'. - FilePath RemoveDirectoryName() const; - - // RemoveFileName returns the directory path with the filename removed. - // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". - // If the FilePath is "a_file" or "/a_file", RemoveFileName returns - // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does - // not have a file, like "just/a/dir/", it returns the FilePath unmodified. - // On Windows platform, '\' is the path separator, otherwise it is '/'. - FilePath RemoveFileName() const; - - // Returns a copy of the FilePath with the case-insensitive extension removed. - // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns - // FilePath("dir/file"). If a case-insensitive extension is not - // found, returns a copy of the original FilePath. - FilePath RemoveExtension(const char* extension) const; - - // Creates directories so that path exists. Returns true if successful or if - // the directories already exist; returns false if unable to create - // directories for any reason. Will also return false if the FilePath does - // not represent a directory (that is, it doesn't end with a path separator). - bool CreateDirectoriesRecursively() const; - - // Create the directory so that path exists. Returns true if successful or - // if the directory already exists; returns false if unable to create the - // directory for any reason, including if the parent directory does not - // exist. Not named "CreateDirectory" because that's a macro on Windows. - bool CreateFolder() const; - - // Returns true if FilePath describes something in the file-system, - // either a file, directory, or whatever, and that something exists. - bool FileOrDirectoryExists() const; - - // Returns true if pathname describes a directory in the file-system - // that exists. - bool DirectoryExists() const; - - // Returns true if FilePath ends with a path separator, which indicates that - // it is intended to represent a directory. Returns false otherwise. - // This does NOT check that a directory (or file) actually exists. - bool IsDirectory() const; - - // Returns true if pathname describes a root directory. (Windows has one - // root directory per disk drive.) - bool IsRootDirectory() const; - - // Returns true if pathname describes an absolute path. - bool IsAbsolutePath() const; - - private: - // Replaces multiple consecutive separators with a single separator. - // For example, "bar///foo" becomes "bar/foo". Does not eliminate other - // redundancies that might be in a pathname involving "." or "..". - // - // A pathname with multiple consecutive separators may occur either through - // user error or as a result of some scripts or APIs that generate a pathname - // with a trailing separator. On other platforms the same API or script - // may NOT generate a pathname with a trailing "/". Then elsewhere that - // pathname may have another "/" and pathname components added to it, - // without checking for the separator already being there. - // The script language and operating system may allow paths like "foo//bar" - // but some of the functions in FilePath will not handle that correctly. In - // particular, RemoveTrailingPathSeparator() only removes one separator, and - // it is called in CreateDirectoriesRecursively() assuming that it will change - // a pathname from directory syntax (trailing separator) to filename syntax. - // - // On Windows this method also replaces the alternate path separator '/' with - // the primary path separator '\\', so that for example "bar\\/\\foo" becomes - // "bar\\foo". - - void Normalize(); - - // Returns a pointer to the last occurence of a valid path separator in - // the FilePath. On Windows, for example, both '/' and '\' are valid path - // separators. Returns NULL if no path separator was found. - const char* FindLastPathSeparator() const; - - String pathname_; -}; // class FilePath - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ -// This file was GENERATED by command: -// pump.py gtest-type-util.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2008 Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) - -// Type utilities needed for implementing typed and type-parameterized -// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! -// -// Currently we support at most 50 types in a list, and at most 50 -// type-parameterized tests in one type-parameterized test case. -// Please contact googletestframework@googlegroups.com if you need -// more. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ - - -// #ifdef __GNUC__ is too general here. It is possible to use gcc without using -// libstdc++ (which is where cxxabi.h comes from). -# ifdef __GLIBCXX__ -# include -# elif defined(__HP_aCC) -# include -# endif // __GLIBCXX__ - -namespace testing { -namespace internal { - -// GetTypeName() returns a human-readable name of type T. -// NB: This function is also used in Google Mock, so don't move it inside of -// the typed-test-only section below. -template -String GetTypeName() { -# if GTEST_HAS_RTTI - - const char* const name = typeid(T).name(); -# if defined(__GLIBCXX__) || defined(__HP_aCC) - int status = 0; - // gcc's implementation of typeid(T).name() mangles the type name, - // so we have to demangle it. -# ifdef __GLIBCXX__ - using abi::__cxa_demangle; -# endif // __GLIBCXX__ - char* const readable_name = __cxa_demangle(name, 0, 0, &status); - const String name_str(status == 0 ? readable_name : name); - free(readable_name); - return name_str; -# else - return name; -# endif // __GLIBCXX__ || __HP_aCC - -# else - - return ""; - -# endif // GTEST_HAS_RTTI -} - -#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -// AssertyTypeEq::type is defined iff T1 and T2 are the same -// type. This can be used as a compile-time assertion to ensure that -// two types are equal. - -template -struct AssertTypeEq; - -template -struct AssertTypeEq { - typedef bool type; -}; - -// A unique type used as the default value for the arguments of class -// template Types. This allows us to simulate variadic templates -// (e.g. Types, Type, and etc), which C++ doesn't -// support directly. -struct None {}; - -// The following family of struct and struct templates are used to -// represent type lists. In particular, TypesN -// represents a type list with N types (T1, T2, ..., and TN) in it. -// Except for Types0, every struct in the family has two member types: -// Head for the first type in the list, and Tail for the rest of the -// list. - -// The empty type list. -struct Types0 {}; - -// Type lists of length 1, 2, 3, and so on. - -template -struct Types1 { - typedef T1 Head; - typedef Types0 Tail; -}; -template -struct Types2 { - typedef T1 Head; - typedef Types1 Tail; -}; - -template -struct Types3 { - typedef T1 Head; - typedef Types2 Tail; -}; - -template -struct Types4 { - typedef T1 Head; - typedef Types3 Tail; -}; - -template -struct Types5 { - typedef T1 Head; - typedef Types4 Tail; -}; - -template -struct Types6 { - typedef T1 Head; - typedef Types5 Tail; -}; - -template -struct Types7 { - typedef T1 Head; - typedef Types6 Tail; -}; - -template -struct Types8 { - typedef T1 Head; - typedef Types7 Tail; -}; - -template -struct Types9 { - typedef T1 Head; - typedef Types8 Tail; -}; - -template -struct Types10 { - typedef T1 Head; - typedef Types9 Tail; -}; - -template -struct Types11 { - typedef T1 Head; - typedef Types10 Tail; -}; - -template -struct Types12 { - typedef T1 Head; - typedef Types11 Tail; -}; - -template -struct Types13 { - typedef T1 Head; - typedef Types12 Tail; -}; - -template -struct Types14 { - typedef T1 Head; - typedef Types13 Tail; -}; - -template -struct Types15 { - typedef T1 Head; - typedef Types14 Tail; -}; - -template -struct Types16 { - typedef T1 Head; - typedef Types15 Tail; -}; - -template -struct Types17 { - typedef T1 Head; - typedef Types16 Tail; -}; - -template -struct Types18 { - typedef T1 Head; - typedef Types17 Tail; -}; - -template -struct Types19 { - typedef T1 Head; - typedef Types18 Tail; -}; - -template -struct Types20 { - typedef T1 Head; - typedef Types19 Tail; -}; - -template -struct Types21 { - typedef T1 Head; - typedef Types20 Tail; -}; - -template -struct Types22 { - typedef T1 Head; - typedef Types21 Tail; -}; - -template -struct Types23 { - typedef T1 Head; - typedef Types22 Tail; -}; - -template -struct Types24 { - typedef T1 Head; - typedef Types23 Tail; -}; - -template -struct Types25 { - typedef T1 Head; - typedef Types24 Tail; -}; - -template -struct Types26 { - typedef T1 Head; - typedef Types25 Tail; -}; - -template -struct Types27 { - typedef T1 Head; - typedef Types26 Tail; -}; - -template -struct Types28 { - typedef T1 Head; - typedef Types27 Tail; -}; - -template -struct Types29 { - typedef T1 Head; - typedef Types28 Tail; -}; - -template -struct Types30 { - typedef T1 Head; - typedef Types29 Tail; -}; - -template -struct Types31 { - typedef T1 Head; - typedef Types30 Tail; -}; - -template -struct Types32 { - typedef T1 Head; - typedef Types31 Tail; -}; - -template -struct Types33 { - typedef T1 Head; - typedef Types32 Tail; -}; - -template -struct Types34 { - typedef T1 Head; - typedef Types33 Tail; -}; - -template -struct Types35 { - typedef T1 Head; - typedef Types34 Tail; -}; - -template -struct Types36 { - typedef T1 Head; - typedef Types35 Tail; -}; - -template -struct Types37 { - typedef T1 Head; - typedef Types36 Tail; -}; - -template -struct Types38 { - typedef T1 Head; - typedef Types37 Tail; -}; - -template -struct Types39 { - typedef T1 Head; - typedef Types38 Tail; -}; - -template -struct Types40 { - typedef T1 Head; - typedef Types39 Tail; -}; - -template -struct Types41 { - typedef T1 Head; - typedef Types40 Tail; -}; - -template -struct Types42 { - typedef T1 Head; - typedef Types41 Tail; -}; - -template -struct Types43 { - typedef T1 Head; - typedef Types42 Tail; -}; - -template -struct Types44 { - typedef T1 Head; - typedef Types43 Tail; -}; - -template -struct Types45 { - typedef T1 Head; - typedef Types44 Tail; -}; - -template -struct Types46 { - typedef T1 Head; - typedef Types45 Tail; -}; - -template -struct Types47 { - typedef T1 Head; - typedef Types46 Tail; -}; - -template -struct Types48 { - typedef T1 Head; - typedef Types47 Tail; -}; - -template -struct Types49 { - typedef T1 Head; - typedef Types48 Tail; -}; - -template -struct Types50 { - typedef T1 Head; - typedef Types49 Tail; -}; - - -} // namespace internal - -// We don't want to require the users to write TypesN<...> directly, -// as that would require them to count the length. Types<...> is much -// easier to write, but generates horrible messages when there is a -// compiler error, as gcc insists on printing out each template -// argument, even if it has the default value (this means Types -// will appear as Types in the compiler -// errors). -// -// Our solution is to combine the best part of the two approaches: a -// user would write Types, and Google Test will translate -// that to TypesN internally to make error messages -// readable. The translation is done by the 'type' member of the -// Types template. -template -struct Types { - typedef internal::Types50 type; -}; - -template <> -struct Types { - typedef internal::Types0 type; -}; -template -struct Types { - typedef internal::Types1 type; -}; -template -struct Types { - typedef internal::Types2 type; -}; -template -struct Types { - typedef internal::Types3 type; -}; -template -struct Types { - typedef internal::Types4 type; -}; -template -struct Types { - typedef internal::Types5 type; -}; -template -struct Types { - typedef internal::Types6 type; -}; -template -struct Types { - typedef internal::Types7 type; -}; -template -struct Types { - typedef internal::Types8 type; -}; -template -struct Types { - typedef internal::Types9 type; -}; -template -struct Types { - typedef internal::Types10 type; -}; -template -struct Types { - typedef internal::Types11 type; -}; -template -struct Types { - typedef internal::Types12 type; -}; -template -struct Types { - typedef internal::Types13 type; -}; -template -struct Types { - typedef internal::Types14 type; -}; -template -struct Types { - typedef internal::Types15 type; -}; -template -struct Types { - typedef internal::Types16 type; -}; -template -struct Types { - typedef internal::Types17 type; -}; -template -struct Types { - typedef internal::Types18 type; -}; -template -struct Types { - typedef internal::Types19 type; -}; -template -struct Types { - typedef internal::Types20 type; -}; -template -struct Types { - typedef internal::Types21 type; -}; -template -struct Types { - typedef internal::Types22 type; -}; -template -struct Types { - typedef internal::Types23 type; -}; -template -struct Types { - typedef internal::Types24 type; -}; -template -struct Types { - typedef internal::Types25 type; -}; -template -struct Types { - typedef internal::Types26 type; -}; -template -struct Types { - typedef internal::Types27 type; -}; -template -struct Types { - typedef internal::Types28 type; -}; -template -struct Types { - typedef internal::Types29 type; -}; -template -struct Types { - typedef internal::Types30 type; -}; -template -struct Types { - typedef internal::Types31 type; -}; -template -struct Types { - typedef internal::Types32 type; -}; -template -struct Types { - typedef internal::Types33 type; -}; -template -struct Types { - typedef internal::Types34 type; -}; -template -struct Types { - typedef internal::Types35 type; -}; -template -struct Types { - typedef internal::Types36 type; -}; -template -struct Types { - typedef internal::Types37 type; -}; -template -struct Types { - typedef internal::Types38 type; -}; -template -struct Types { - typedef internal::Types39 type; -}; -template -struct Types { - typedef internal::Types40 type; -}; -template -struct Types { - typedef internal::Types41 type; -}; -template -struct Types { - typedef internal::Types42 type; -}; -template -struct Types { - typedef internal::Types43 type; -}; -template -struct Types { - typedef internal::Types44 type; -}; -template -struct Types { - typedef internal::Types45 type; -}; -template -struct Types { - typedef internal::Types46 type; -}; -template -struct Types { - typedef internal::Types47 type; -}; -template -struct Types { - typedef internal::Types48 type; -}; -template -struct Types { - typedef internal::Types49 type; -}; - -namespace internal { - -# define GTEST_TEMPLATE_ template class - -// The template "selector" struct TemplateSel is used to -// represent Tmpl, which must be a class template with one type -// parameter, as a type. TemplateSel::Bind::type is defined -// as the type Tmpl. This allows us to actually instantiate the -// template "selected" by TemplateSel. -// -// This trick is necessary for simulating typedef for class templates, -// which C++ doesn't support directly. -template -struct TemplateSel { - template - struct Bind { - typedef Tmpl type; - }; -}; - -# define GTEST_BIND_(TmplSel, T) \ - TmplSel::template Bind::type - -// A unique struct template used as the default value for the -// arguments of class template Templates. This allows us to simulate -// variadic templates (e.g. Templates, Templates, -// and etc), which C++ doesn't support directly. -template -struct NoneT {}; - -// The following family of struct and struct templates are used to -// represent template lists. In particular, TemplatesN represents a list of N templates (T1, T2, ..., and TN). Except -// for Templates0, every struct in the family has two member types: -// Head for the selector of the first template in the list, and Tail -// for the rest of the list. - -// The empty template list. -struct Templates0 {}; - -// Template lists of length 1, 2, 3, and so on. - -template -struct Templates1 { - typedef TemplateSel Head; - typedef Templates0 Tail; -}; -template -struct Templates2 { - typedef TemplateSel Head; - typedef Templates1 Tail; -}; - -template -struct Templates3 { - typedef TemplateSel Head; - typedef Templates2 Tail; -}; - -template -struct Templates4 { - typedef TemplateSel Head; - typedef Templates3 Tail; -}; - -template -struct Templates5 { - typedef TemplateSel Head; - typedef Templates4 Tail; -}; - -template -struct Templates6 { - typedef TemplateSel Head; - typedef Templates5 Tail; -}; - -template -struct Templates7 { - typedef TemplateSel Head; - typedef Templates6 Tail; -}; - -template -struct Templates8 { - typedef TemplateSel Head; - typedef Templates7 Tail; -}; - -template -struct Templates9 { - typedef TemplateSel Head; - typedef Templates8 Tail; -}; - -template -struct Templates10 { - typedef TemplateSel Head; - typedef Templates9 Tail; -}; - -template -struct Templates11 { - typedef TemplateSel Head; - typedef Templates10 Tail; -}; - -template -struct Templates12 { - typedef TemplateSel Head; - typedef Templates11 Tail; -}; - -template -struct Templates13 { - typedef TemplateSel Head; - typedef Templates12 Tail; -}; - -template -struct Templates14 { - typedef TemplateSel Head; - typedef Templates13 Tail; -}; - -template -struct Templates15 { - typedef TemplateSel Head; - typedef Templates14 Tail; -}; - -template -struct Templates16 { - typedef TemplateSel Head; - typedef Templates15 Tail; -}; - -template -struct Templates17 { - typedef TemplateSel Head; - typedef Templates16 Tail; -}; - -template -struct Templates18 { - typedef TemplateSel Head; - typedef Templates17 Tail; -}; - -template -struct Templates19 { - typedef TemplateSel Head; - typedef Templates18 Tail; -}; - -template -struct Templates20 { - typedef TemplateSel Head; - typedef Templates19 Tail; -}; - -template -struct Templates21 { - typedef TemplateSel Head; - typedef Templates20 Tail; -}; - -template -struct Templates22 { - typedef TemplateSel Head; - typedef Templates21 Tail; -}; - -template -struct Templates23 { - typedef TemplateSel Head; - typedef Templates22 Tail; -}; - -template -struct Templates24 { - typedef TemplateSel Head; - typedef Templates23 Tail; -}; - -template -struct Templates25 { - typedef TemplateSel Head; - typedef Templates24 Tail; -}; - -template -struct Templates26 { - typedef TemplateSel Head; - typedef Templates25 Tail; -}; - -template -struct Templates27 { - typedef TemplateSel Head; - typedef Templates26 Tail; -}; - -template -struct Templates28 { - typedef TemplateSel Head; - typedef Templates27 Tail; -}; - -template -struct Templates29 { - typedef TemplateSel Head; - typedef Templates28 Tail; -}; - -template -struct Templates30 { - typedef TemplateSel Head; - typedef Templates29 Tail; -}; - -template -struct Templates31 { - typedef TemplateSel Head; - typedef Templates30 Tail; -}; - -template -struct Templates32 { - typedef TemplateSel Head; - typedef Templates31 Tail; -}; - -template -struct Templates33 { - typedef TemplateSel Head; - typedef Templates32 Tail; -}; - -template -struct Templates34 { - typedef TemplateSel Head; - typedef Templates33 Tail; -}; - -template -struct Templates35 { - typedef TemplateSel Head; - typedef Templates34 Tail; -}; - -template -struct Templates36 { - typedef TemplateSel Head; - typedef Templates35 Tail; -}; - -template -struct Templates37 { - typedef TemplateSel Head; - typedef Templates36 Tail; -}; - -template -struct Templates38 { - typedef TemplateSel Head; - typedef Templates37 Tail; -}; - -template -struct Templates39 { - typedef TemplateSel Head; - typedef Templates38 Tail; -}; - -template -struct Templates40 { - typedef TemplateSel Head; - typedef Templates39 Tail; -}; - -template -struct Templates41 { - typedef TemplateSel Head; - typedef Templates40 Tail; -}; - -template -struct Templates42 { - typedef TemplateSel Head; - typedef Templates41 Tail; -}; - -template -struct Templates43 { - typedef TemplateSel Head; - typedef Templates42 Tail; -}; - -template -struct Templates44 { - typedef TemplateSel Head; - typedef Templates43 Tail; -}; - -template -struct Templates45 { - typedef TemplateSel Head; - typedef Templates44 Tail; -}; - -template -struct Templates46 { - typedef TemplateSel Head; - typedef Templates45 Tail; -}; - -template -struct Templates47 { - typedef TemplateSel Head; - typedef Templates46 Tail; -}; - -template -struct Templates48 { - typedef TemplateSel Head; - typedef Templates47 Tail; -}; - -template -struct Templates49 { - typedef TemplateSel Head; - typedef Templates48 Tail; -}; - -template -struct Templates50 { - typedef TemplateSel Head; - typedef Templates49 Tail; -}; - - -// We don't want to require the users to write TemplatesN<...> directly, -// as that would require them to count the length. Templates<...> is much -// easier to write, but generates horrible messages when there is a -// compiler error, as gcc insists on printing out each template -// argument, even if it has the default value (this means Templates -// will appear as Templates in the compiler -// errors). -// -// Our solution is to combine the best part of the two approaches: a -// user would write Templates, and Google Test will translate -// that to TemplatesN internally to make error messages -// readable. The translation is done by the 'type' member of the -// Templates template. -template -struct Templates { - typedef Templates50 type; -}; - -template <> -struct Templates { - typedef Templates0 type; -}; -template -struct Templates { - typedef Templates1 type; -}; -template -struct Templates { - typedef Templates2 type; -}; -template -struct Templates { - typedef Templates3 type; -}; -template -struct Templates { - typedef Templates4 type; -}; -template -struct Templates { - typedef Templates5 type; -}; -template -struct Templates { - typedef Templates6 type; -}; -template -struct Templates { - typedef Templates7 type; -}; -template -struct Templates { - typedef Templates8 type; -}; -template -struct Templates { - typedef Templates9 type; -}; -template -struct Templates { - typedef Templates10 type; -}; -template -struct Templates { - typedef Templates11 type; -}; -template -struct Templates { - typedef Templates12 type; -}; -template -struct Templates { - typedef Templates13 type; -}; -template -struct Templates { - typedef Templates14 type; -}; -template -struct Templates { - typedef Templates15 type; -}; -template -struct Templates { - typedef Templates16 type; -}; -template -struct Templates { - typedef Templates17 type; -}; -template -struct Templates { - typedef Templates18 type; -}; -template -struct Templates { - typedef Templates19 type; -}; -template -struct Templates { - typedef Templates20 type; -}; -template -struct Templates { - typedef Templates21 type; -}; -template -struct Templates { - typedef Templates22 type; -}; -template -struct Templates { - typedef Templates23 type; -}; -template -struct Templates { - typedef Templates24 type; -}; -template -struct Templates { - typedef Templates25 type; -}; -template -struct Templates { - typedef Templates26 type; -}; -template -struct Templates { - typedef Templates27 type; -}; -template -struct Templates { - typedef Templates28 type; -}; -template -struct Templates { - typedef Templates29 type; -}; -template -struct Templates { - typedef Templates30 type; -}; -template -struct Templates { - typedef Templates31 type; -}; -template -struct Templates { - typedef Templates32 type; -}; -template -struct Templates { - typedef Templates33 type; -}; -template -struct Templates { - typedef Templates34 type; -}; -template -struct Templates { - typedef Templates35 type; -}; -template -struct Templates { - typedef Templates36 type; -}; -template -struct Templates { - typedef Templates37 type; -}; -template -struct Templates { - typedef Templates38 type; -}; -template -struct Templates { - typedef Templates39 type; -}; -template -struct Templates { - typedef Templates40 type; -}; -template -struct Templates { - typedef Templates41 type; -}; -template -struct Templates { - typedef Templates42 type; -}; -template -struct Templates { - typedef Templates43 type; -}; -template -struct Templates { - typedef Templates44 type; -}; -template -struct Templates { - typedef Templates45 type; -}; -template -struct Templates { - typedef Templates46 type; -}; -template -struct Templates { - typedef Templates47 type; -}; -template -struct Templates { - typedef Templates48 type; -}; -template -struct Templates { - typedef Templates49 type; -}; - -// The TypeList template makes it possible to use either a single type -// or a Types<...> list in TYPED_TEST_CASE() and -// INSTANTIATE_TYPED_TEST_CASE_P(). - -template -struct TypeList { typedef Types1 type; }; - -template -struct TypeList > { - typedef typename Types::type type; -}; - -#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ - -// Due to C++ preprocessor weirdness, we need double indirection to -// concatenate two tokens when one of them is __LINE__. Writing -// -// foo ## __LINE__ -// -// will result in the token foo__LINE__, instead of foo followed by -// the current line number. For more details, see -// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 -#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) -#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar - -// Google Test defines the testing::Message class to allow construction of -// test messages via the << operator. The idea is that anything -// streamable to std::ostream can be streamed to a testing::Message. -// This allows a user to use his own types in Google Test assertions by -// overloading the << operator. -// -// util/gtl/stl_logging-inl.h overloads << for STL containers. These -// overloads cannot be defined in the std namespace, as that will be -// undefined behavior. Therefore, they are defined in the global -// namespace instead. -// -// C++'s symbol lookup rule (i.e. Koenig lookup) says that these -// overloads are visible in either the std namespace or the global -// namespace, but not other namespaces, including the testing -// namespace which Google Test's Message class is in. -// -// To allow STL containers (and other types that has a << operator -// defined in the global namespace) to be used in Google Test assertions, -// testing::Message must access the custom << operator from the global -// namespace. Hence this helper function. -// -// Note: Jeffrey Yasskin suggested an alternative fix by "using -// ::operator<<;" in the definition of Message's operator<<. That fix -// doesn't require a helper function, but unfortunately doesn't -// compile with MSVC. -template -inline void GTestStreamToHelper(std::ostream* os, const T& val) { - *os << val; -} - -class ProtocolMessage; -namespace proto2 { class Message; } - -namespace testing { - -// Forward declarations. - -class AssertionResult; // Result of an assertion. -class Message; // Represents a failure message. -class Test; // Represents a test. -class TestInfo; // Information about a test. -class TestPartResult; // Result of a test part. -class UnitTest; // A collection of test cases. - -template -::std::string PrintToString(const T& value); - -namespace internal { - -struct TraceInfo; // Information about a trace point. -class ScopedTrace; // Implements scoped trace. -class TestInfoImpl; // Opaque implementation of TestInfo -class UnitTestImpl; // Opaque implementation of UnitTest - -// How many times InitGoogleTest() has been called. -extern int g_init_gtest_count; - -// The text used in failure messages to indicate the start of the -// stack trace. -GTEST_API_ extern const char kStackTraceMarker[]; - -// A secret type that Google Test users don't know about. It has no -// definition on purpose. Therefore it's impossible to create a -// Secret object, which is what we want. -class Secret; - -// Two overloaded helpers for checking at compile time whether an -// expression is a null pointer literal (i.e. NULL or any 0-valued -// compile-time integral constant). Their return values have -// different sizes, so we can use sizeof() to test which version is -// picked by the compiler. These helpers have no implementations, as -// we only need their signatures. -// -// Given IsNullLiteralHelper(x), the compiler will pick the first -// version if x can be implicitly converted to Secret*, and pick the -// second version otherwise. Since Secret is a secret and incomplete -// type, the only expression a user can write that has type Secret* is -// a null pointer literal. Therefore, we know that x is a null -// pointer literal if and only if the first version is picked by the -// compiler. -char IsNullLiteralHelper(Secret* p); -char (&IsNullLiteralHelper(...))[2]; // NOLINT - -// A compile-time bool constant that is true if and only if x is a -// null pointer literal (i.e. NULL or any 0-valued compile-time -// integral constant). -#ifdef GTEST_ELLIPSIS_NEEDS_POD_ -// We lose support for NULL detection where the compiler doesn't like -// passing non-POD classes through ellipsis (...). -# define GTEST_IS_NULL_LITERAL_(x) false -#else -# define GTEST_IS_NULL_LITERAL_(x) \ - (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1) -#endif // GTEST_ELLIPSIS_NEEDS_POD_ - -// Appends the user-supplied message to the Google-Test-generated message. -GTEST_API_ String AppendUserMessage(const String& gtest_msg, - const Message& user_msg); - -// A helper class for creating scoped traces in user programs. -class GTEST_API_ ScopedTrace { - public: - // The c'tor pushes the given source file location and message onto - // a trace stack maintained by Google Test. - ScopedTrace(const char* file, int line, const Message& message); - - // The d'tor pops the info pushed by the c'tor. - // - // Note that the d'tor is not virtual in order to be efficient. - // Don't inherit from ScopedTrace! - ~ScopedTrace(); - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace); -} GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its - // c'tor and d'tor. Therefore it doesn't - // need to be used otherwise. - -// Converts a streamable value to a String. A NULL pointer is -// converted to "(null)". When the input value is a ::string, -// ::std::string, ::wstring, or ::std::wstring object, each NUL -// character in it is replaced with "\\0". -// Declared here but defined in gtest.h, so that it has access -// to the definition of the Message class, required by the ARM -// compiler. -template -String StreamableToString(const T& streamable); - -// The Symbian compiler has a bug that prevents it from selecting the -// correct overload of FormatForComparisonFailureMessage (see below) -// unless we pass the first argument by reference. If we do that, -// however, Visual Age C++ 10.1 generates a compiler error. Therefore -// we only apply the work-around for Symbian. -#if defined(__SYMBIAN32__) -# define GTEST_CREF_WORKAROUND_ const& -#else -# define GTEST_CREF_WORKAROUND_ -#endif - -// When this operand is a const char* or char*, if the other operand -// is a ::std::string or ::string, we print this operand as a C string -// rather than a pointer (we do the same for wide strings); otherwise -// we print it as a pointer to be safe. - -// This internal macro is used to avoid duplicated code. -#define GTEST_FORMAT_IMPL_(operand2_type, operand1_printer)\ -inline String FormatForComparisonFailureMessage(\ - operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \ - const operand2_type& /*operand2*/) {\ - return operand1_printer(str);\ -}\ -inline String FormatForComparisonFailureMessage(\ - const operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \ - const operand2_type& /*operand2*/) {\ - return operand1_printer(str);\ -} - -GTEST_FORMAT_IMPL_(::std::string, String::ShowCStringQuoted) -#if GTEST_HAS_STD_WSTRING -GTEST_FORMAT_IMPL_(::std::wstring, String::ShowWideCStringQuoted) -#endif // GTEST_HAS_STD_WSTRING - -#if GTEST_HAS_GLOBAL_STRING -GTEST_FORMAT_IMPL_(::string, String::ShowCStringQuoted) -#endif // GTEST_HAS_GLOBAL_STRING -#if GTEST_HAS_GLOBAL_WSTRING -GTEST_FORMAT_IMPL_(::wstring, String::ShowWideCStringQuoted) -#endif // GTEST_HAS_GLOBAL_WSTRING - -#undef GTEST_FORMAT_IMPL_ - -// The next four overloads handle the case where the operand being -// printed is a char/wchar_t pointer and the other operand is not a -// string/wstring object. In such cases, we just print the operand as -// a pointer to be safe. -#define GTEST_FORMAT_CHAR_PTR_IMPL_(CharType) \ - template \ - String FormatForComparisonFailureMessage(CharType* GTEST_CREF_WORKAROUND_ p, \ - const T&) { \ - return PrintToString(static_cast(p)); \ - } - -GTEST_FORMAT_CHAR_PTR_IMPL_(char) -GTEST_FORMAT_CHAR_PTR_IMPL_(const char) -GTEST_FORMAT_CHAR_PTR_IMPL_(wchar_t) -GTEST_FORMAT_CHAR_PTR_IMPL_(const wchar_t) - -#undef GTEST_FORMAT_CHAR_PTR_IMPL_ - -// Constructs and returns the message for an equality assertion -// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. -// -// The first four parameters are the expressions used in the assertion -// and their values, as strings. For example, for ASSERT_EQ(foo, bar) -// where foo is 5 and bar is 6, we have: -// -// expected_expression: "foo" -// actual_expression: "bar" -// expected_value: "5" -// actual_value: "6" -// -// The ignoring_case parameter is true iff the assertion is a -// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will -// be inserted into the message. -GTEST_API_ AssertionResult EqFailure(const char* expected_expression, - const char* actual_expression, - const String& expected_value, - const String& actual_value, - bool ignoring_case); - -// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. -GTEST_API_ String GetBoolAssertionFailureMessage( - const AssertionResult& assertion_result, - const char* expression_text, - const char* actual_predicate_value, - const char* expected_predicate_value); - -// This template class represents an IEEE floating-point number -// (either single-precision or double-precision, depending on the -// template parameters). -// -// The purpose of this class is to do more sophisticated number -// comparison. (Due to round-off error, etc, it's very unlikely that -// two floating-points will be equal exactly. Hence a naive -// comparison by the == operation often doesn't work.) -// -// Format of IEEE floating-point: -// -// The most-significant bit being the leftmost, an IEEE -// floating-point looks like -// -// sign_bit exponent_bits fraction_bits -// -// Here, sign_bit is a single bit that designates the sign of the -// number. -// -// For float, there are 8 exponent bits and 23 fraction bits. -// -// For double, there are 11 exponent bits and 52 fraction bits. -// -// More details can be found at -// http://en.wikipedia.org/wiki/IEEE_floating-point_standard. -// -// Template parameter: -// -// RawType: the raw floating-point type (either float or double) -template -class FloatingPoint { - public: - // Defines the unsigned integer type that has the same size as the - // floating point number. - typedef typename TypeWithSize::UInt Bits; - - // Constants. - - // # of bits in a number. - static const size_t kBitCount = 8*sizeof(RawType); - - // # of fraction bits in a number. - static const size_t kFractionBitCount = - std::numeric_limits::digits - 1; - - // # of exponent bits in a number. - static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; - - // The mask for the sign bit. - static const Bits kSignBitMask = static_cast(1) << (kBitCount - 1); - - // The mask for the fraction bits. - static const Bits kFractionBitMask = - ~static_cast(0) >> (kExponentBitCount + 1); - - // The mask for the exponent bits. - static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); - - // How many ULP's (Units in the Last Place) we want to tolerate when - // comparing two numbers. The larger the value, the more error we - // allow. A 0 value means that two numbers must be exactly the same - // to be considered equal. - // - // The maximum error of a single floating-point operation is 0.5 - // units in the last place. On Intel CPU's, all floating-point - // calculations are done with 80-bit precision, while double has 64 - // bits. Therefore, 4 should be enough for ordinary use. - // - // See the following article for more details on ULP: - // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm. - static const size_t kMaxUlps = 4; - - // Constructs a FloatingPoint from a raw floating-point number. - // - // On an Intel CPU, passing a non-normalized NAN (Not a Number) - // around may change its bits, although the new value is guaranteed - // to be also a NAN. Therefore, don't expect this constructor to - // preserve the bits in x when x is a NAN. - explicit FloatingPoint(const RawType& x) { u_.value_ = x; } - - // Static methods - - // Reinterprets a bit pattern as a floating-point number. - // - // This function is needed to test the AlmostEquals() method. - static RawType ReinterpretBits(const Bits bits) { - FloatingPoint fp(0); - fp.u_.bits_ = bits; - return fp.u_.value_; - } - - // Returns the floating-point number that represent positive infinity. - static RawType Infinity() { - return ReinterpretBits(kExponentBitMask); - } - - // Non-static methods - - // Returns the bits that represents this number. - const Bits &bits() const { return u_.bits_; } - - // Returns the exponent bits of this number. - Bits exponent_bits() const { return kExponentBitMask & u_.bits_; } - - // Returns the fraction bits of this number. - Bits fraction_bits() const { return kFractionBitMask & u_.bits_; } - - // Returns the sign bit of this number. - Bits sign_bit() const { return kSignBitMask & u_.bits_; } - - // Returns true iff this is NAN (not a number). - bool is_nan() const { - // It's a NAN if the exponent bits are all ones and the fraction - // bits are not entirely zeros. - return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0); - } - - // Returns true iff this number is at most kMaxUlps ULP's away from - // rhs. In particular, this function: - // - // - returns false if either number is (or both are) NAN. - // - treats really large numbers as almost equal to infinity. - // - thinks +0.0 and -0.0 are 0 DLP's apart. - bool AlmostEquals(const FloatingPoint& rhs) const { - // The IEEE standard says that any comparison operation involving - // a NAN must return false. - if (is_nan() || rhs.is_nan()) return false; - - return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) - <= kMaxUlps; - } - - private: - // The data type used to store the actual floating-point number. - union FloatingPointUnion { - RawType value_; // The raw floating-point number. - Bits bits_; // The bits that represent the number. - }; - - // Converts an integer from the sign-and-magnitude representation to - // the biased representation. More precisely, let N be 2 to the - // power of (kBitCount - 1), an integer x is represented by the - // unsigned number x + N. - // - // For instance, - // - // -N + 1 (the most negative number representable using - // sign-and-magnitude) is represented by 1; - // 0 is represented by N; and - // N - 1 (the biggest number representable using - // sign-and-magnitude) is represented by 2N - 1. - // - // Read http://en.wikipedia.org/wiki/Signed_number_representations - // for more details on signed number representations. - static Bits SignAndMagnitudeToBiased(const Bits &sam) { - if (kSignBitMask & sam) { - // sam represents a negative number. - return ~sam + 1; - } else { - // sam represents a positive number. - return kSignBitMask | sam; - } - } - - // Given two numbers in the sign-and-magnitude representation, - // returns the distance between them as an unsigned number. - static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, - const Bits &sam2) { - const Bits biased1 = SignAndMagnitudeToBiased(sam1); - const Bits biased2 = SignAndMagnitudeToBiased(sam2); - return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); - } - - FloatingPointUnion u_; -}; - -// Typedefs the instances of the FloatingPoint template class that we -// care to use. -typedef FloatingPoint Float; -typedef FloatingPoint Double; - -// In order to catch the mistake of putting tests that use different -// test fixture classes in the same test case, we need to assign -// unique IDs to fixture classes and compare them. The TypeId type is -// used to hold such IDs. The user should treat TypeId as an opaque -// type: the only operation allowed on TypeId values is to compare -// them for equality using the == operator. -typedef const void* TypeId; - -template -class TypeIdHelper { - public: - // dummy_ must not have a const type. Otherwise an overly eager - // compiler (e.g. MSVC 7.1 & 8.0) may try to merge - // TypeIdHelper::dummy_ for different Ts as an "optimization". - static bool dummy_; -}; - -template -bool TypeIdHelper::dummy_ = false; - -// GetTypeId() returns the ID of type T. Different values will be -// returned for different types. Calling the function twice with the -// same type argument is guaranteed to return the same ID. -template -TypeId GetTypeId() { - // The compiler is required to allocate a different - // TypeIdHelper::dummy_ variable for each T used to instantiate - // the template. Therefore, the address of dummy_ is guaranteed to - // be unique. - return &(TypeIdHelper::dummy_); -} - -// Returns the type ID of ::testing::Test. Always call this instead -// of GetTypeId< ::testing::Test>() to get the type ID of -// ::testing::Test, as the latter may give the wrong result due to a -// suspected linker bug when compiling Google Test as a Mac OS X -// framework. -GTEST_API_ TypeId GetTestTypeId(); - -// Defines the abstract factory interface that creates instances -// of a Test object. -class TestFactoryBase { - public: - virtual ~TestFactoryBase() {} - - // Creates a test instance to run. The instance is both created and destroyed - // within TestInfoImpl::Run() - virtual Test* CreateTest() = 0; - - protected: - TestFactoryBase() {} - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase); -}; - -// This class provides implementation of TeastFactoryBase interface. -// It is used in TEST and TEST_F macros. -template -class TestFactoryImpl : public TestFactoryBase { - public: - virtual Test* CreateTest() { return new TestClass; } -}; - -#if GTEST_OS_WINDOWS - -// Predicate-formatters for implementing the HRESULT checking macros -// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED} -// We pass a long instead of HRESULT to avoid causing an -// include dependency for the HRESULT type. -GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr, - long hr); // NOLINT -GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, - long hr); // NOLINT - -#endif // GTEST_OS_WINDOWS - -// Types of SetUpTestCase() and TearDownTestCase() functions. -typedef void (*SetUpTestCaseFunc)(); -typedef void (*TearDownTestCaseFunc)(); - -// Creates a new TestInfo object and registers it with Google Test; -// returns the created object. -// -// Arguments: -// -// test_case_name: name of the test case -// name: name of the test -// type_param the name of the test's type parameter, or NULL if -// this is not a typed or a type-parameterized test. -// value_param text representation of the test's value parameter, -// or NULL if this is not a type-parameterized test. -// fixture_class_id: ID of the test fixture class -// set_up_tc: pointer to the function that sets up the test case -// tear_down_tc: pointer to the function that tears down the test case -// factory: pointer to the factory that creates a test object. -// The newly created TestInfo instance will assume -// ownership of the factory object. -GTEST_API_ TestInfo* MakeAndRegisterTestInfo( - const char* test_case_name, const char* name, - const char* type_param, - const char* value_param, - TypeId fixture_class_id, - SetUpTestCaseFunc set_up_tc, - TearDownTestCaseFunc tear_down_tc, - TestFactoryBase* factory); - -// If *pstr starts with the given prefix, modifies *pstr to be right -// past the prefix and returns true; otherwise leaves *pstr unchanged -// and returns false. None of pstr, *pstr, and prefix can be NULL. -GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr); - -#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -// State of the definition of a type-parameterized test case. -class GTEST_API_ TypedTestCasePState { - public: - TypedTestCasePState() : registered_(false) {} - - // Adds the given test name to defined_test_names_ and return true - // if the test case hasn't been registered; otherwise aborts the - // program. - bool AddTestName(const char* file, int line, const char* case_name, - const char* test_name) { - if (registered_) { - fprintf(stderr, "%s Test %s must be defined before " - "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n", - FormatFileLocation(file, line).c_str(), test_name, case_name); - fflush(stderr); - posix::Abort(); - } - defined_test_names_.insert(test_name); - return true; - } - - // Verifies that registered_tests match the test names in - // defined_test_names_; returns registered_tests if successful, or - // aborts the program otherwise. - const char* VerifyRegisteredTestNames( - const char* file, int line, const char* registered_tests); - - private: - bool registered_; - ::std::set defined_test_names_; -}; - -// Skips to the first non-space char after the first comma in 'str'; -// returns NULL if no comma is found in 'str'. -inline const char* SkipComma(const char* str) { - const char* comma = strchr(str, ','); - if (comma == NULL) { - return NULL; - } - while (IsSpace(*(++comma))) {} - return comma; -} - -// Returns the prefix of 'str' before the first comma in it; returns -// the entire string if it contains no comma. -inline String GetPrefixUntilComma(const char* str) { - const char* comma = strchr(str, ','); - return comma == NULL ? String(str) : String(str, comma - str); -} - -// TypeParameterizedTest::Register() -// registers a list of type-parameterized tests with Google Test. The -// return value is insignificant - we just need to return something -// such that we can call this function in a namespace scope. -// -// Implementation note: The GTEST_TEMPLATE_ macro declares a template -// template parameter. It's defined in gtest-type-util.h. -template -class TypeParameterizedTest { - public: - // 'index' is the index of the test in the type list 'Types' - // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase, - // Types). Valid values for 'index' are [0, N - 1] where N is the - // length of Types. - static bool Register(const char* prefix, const char* case_name, - const char* test_names, int index) { - typedef typename Types::Head Type; - typedef Fixture FixtureClass; - typedef typename GTEST_BIND_(TestSel, Type) TestClass; - - // First, registers the first type-parameterized test in the type - // list. - MakeAndRegisterTestInfo( - String::Format("%s%s%s/%d", prefix, prefix[0] == '\0' ? "" : "/", - case_name, index).c_str(), - GetPrefixUntilComma(test_names).c_str(), - GetTypeName().c_str(), - NULL, // No value parameter. - GetTypeId(), - TestClass::SetUpTestCase, - TestClass::TearDownTestCase, - new TestFactoryImpl); - - // Next, recurses (at compile time) with the tail of the type list. - return TypeParameterizedTest - ::Register(prefix, case_name, test_names, index + 1); - } -}; - -// The base case for the compile time recursion. -template -class TypeParameterizedTest { - public: - static bool Register(const char* /*prefix*/, const char* /*case_name*/, - const char* /*test_names*/, int /*index*/) { - return true; - } -}; - -// TypeParameterizedTestCase::Register() -// registers *all combinations* of 'Tests' and 'Types' with Google -// Test. The return value is insignificant - we just need to return -// something such that we can call this function in a namespace scope. -template -class TypeParameterizedTestCase { - public: - static bool Register(const char* prefix, const char* case_name, - const char* test_names) { - typedef typename Tests::Head Head; - - // First, register the first test in 'Test' for each type in 'Types'. - TypeParameterizedTest::Register( - prefix, case_name, test_names, 0); - - // Next, recurses (at compile time) with the tail of the test list. - return TypeParameterizedTestCase - ::Register(prefix, case_name, SkipComma(test_names)); - } -}; - -// The base case for the compile time recursion. -template -class TypeParameterizedTestCase { - public: - static bool Register(const char* /*prefix*/, const char* /*case_name*/, - const char* /*test_names*/) { - return true; - } -}; - -#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -// Returns the current OS stack trace as a String. -// -// The maximum number of stack frames to be included is specified by -// the gtest_stack_trace_depth flag. The skip_count parameter -// specifies the number of top frames to be skipped, which doesn't -// count against the number of frames to be included. -// -// For example, if Foo() calls Bar(), which in turn calls -// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in -// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. -GTEST_API_ String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, - int skip_count); - -// Helpers for suppressing warnings on unreachable code or constant -// condition. - -// Always returns true. -GTEST_API_ bool AlwaysTrue(); - -// Always returns false. -inline bool AlwaysFalse() { return !AlwaysTrue(); } - -// Helper for suppressing false warning from Clang on a const char* -// variable declared in a conditional expression always being NULL in -// the else branch. -struct GTEST_API_ ConstCharPtr { - ConstCharPtr(const char* str) : value(str) {} - operator bool() const { return true; } - const char* value; -}; - -// A simple Linear Congruential Generator for generating random -// numbers with a uniform distribution. Unlike rand() and srand(), it -// doesn't use global state (and therefore can't interfere with user -// code). Unlike rand_r(), it's portable. An LCG isn't very random, -// but it's good enough for our purposes. -class GTEST_API_ Random { - public: - static const UInt32 kMaxRange = 1u << 31; - - explicit Random(UInt32 seed) : state_(seed) {} - - void Reseed(UInt32 seed) { state_ = seed; } - - // Generates a random number from [0, range). Crashes if 'range' is - // 0 or greater than kMaxRange. - UInt32 Generate(UInt32 range); - - private: - UInt32 state_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); -}; - -// Defining a variable of type CompileAssertTypesEqual will cause a -// compiler error iff T1 and T2 are different types. -template -struct CompileAssertTypesEqual; - -template -struct CompileAssertTypesEqual { -}; - -// Removes the reference from a type if it is a reference type, -// otherwise leaves it unchanged. This is the same as -// tr1::remove_reference, which is not widely available yet. -template -struct RemoveReference { typedef T type; }; // NOLINT -template -struct RemoveReference { typedef T type; }; // NOLINT - -// A handy wrapper around RemoveReference that works when the argument -// T depends on template parameters. -#define GTEST_REMOVE_REFERENCE_(T) \ - typename ::testing::internal::RemoveReference::type - -// Removes const from a type if it is a const type, otherwise leaves -// it unchanged. This is the same as tr1::remove_const, which is not -// widely available yet. -template -struct RemoveConst { typedef T type; }; // NOLINT -template -struct RemoveConst { typedef T type; }; // NOLINT - -// MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above -// definition to fail to remove the const in 'const int[3]' and 'const -// char[3][4]'. The following specialization works around the bug. -// However, it causes trouble with GCC and thus needs to be -// conditionally compiled. -#if defined(_MSC_VER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) -template -struct RemoveConst { - typedef typename RemoveConst::type type[N]; -}; -#endif - -// A handy wrapper around RemoveConst that works when the argument -// T depends on template parameters. -#define GTEST_REMOVE_CONST_(T) \ - typename ::testing::internal::RemoveConst::type - -// Turns const U&, U&, const U, and U all into U. -#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ - GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) - -// Adds reference to a type if it is not a reference type, -// otherwise leaves it unchanged. This is the same as -// tr1::add_reference, which is not widely available yet. -template -struct AddReference { typedef T& type; }; // NOLINT -template -struct AddReference { typedef T& type; }; // NOLINT - -// A handy wrapper around AddReference that works when the argument T -// depends on template parameters. -#define GTEST_ADD_REFERENCE_(T) \ - typename ::testing::internal::AddReference::type - -// Adds a reference to const on top of T as necessary. For example, -// it transforms -// -// char ==> const char& -// const char ==> const char& -// char& ==> const char& -// const char& ==> const char& -// -// The argument T must depend on some template parameters. -#define GTEST_REFERENCE_TO_CONST_(T) \ - GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T)) - -// ImplicitlyConvertible::value is a compile-time bool -// constant that's true iff type From can be implicitly converted to -// type To. -template -class ImplicitlyConvertible { - private: - // We need the following helper functions only for their types. - // They have no implementations. - - // MakeFrom() is an expression whose type is From. We cannot simply - // use From(), as the type From may not have a public default - // constructor. - static From MakeFrom(); - - // These two functions are overloaded. Given an expression - // Helper(x), the compiler will pick the first version if x can be - // implicitly converted to type To; otherwise it will pick the - // second version. - // - // The first version returns a value of size 1, and the second - // version returns a value of size 2. Therefore, by checking the - // size of Helper(x), which can be done at compile time, we can tell - // which version of Helper() is used, and hence whether x can be - // implicitly converted to type To. - static char Helper(To); - static char (&Helper(...))[2]; // NOLINT - - // We have to put the 'public' section after the 'private' section, - // or MSVC refuses to compile the code. - public: - // MSVC warns about implicitly converting from double to int for - // possible loss of data, so we need to temporarily disable the - // warning. -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4244) // Temporarily disables warning 4244. - - static const bool value = - sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; -# pragma warning(pop) // Restores the warning state. -#elif defined(__BORLANDC__) - // C++Builder cannot use member overload resolution during template - // instantiation. The simplest workaround is to use its C++0x type traits - // functions (C++Builder 2009 and above only). - static const bool value = __is_convertible(From, To); -#else - static const bool value = - sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; -#endif // _MSV_VER -}; -template -const bool ImplicitlyConvertible::value; - -// IsAProtocolMessage::value is a compile-time bool constant that's -// true iff T is type ProtocolMessage, proto2::Message, or a subclass -// of those. -template -struct IsAProtocolMessage - : public bool_constant< - ImplicitlyConvertible::value || - ImplicitlyConvertible::value> { -}; - -// When the compiler sees expression IsContainerTest(0), if C is an -// STL-style container class, the first overload of IsContainerTest -// will be viable (since both C::iterator* and C::const_iterator* are -// valid types and NULL can be implicitly converted to them). It will -// be picked over the second overload as 'int' is a perfect match for -// the type of argument 0. If C::iterator or C::const_iterator is not -// a valid type, the first overload is not viable, and the second -// overload will be picked. Therefore, we can determine whether C is -// a container class by checking the type of IsContainerTest(0). -// The value of the expression is insignificant. -// -// Note that we look for both C::iterator and C::const_iterator. The -// reason is that C++ injects the name of a class as a member of the -// class itself (e.g. you can refer to class iterator as either -// 'iterator' or 'iterator::iterator'). If we look for C::iterator -// only, for example, we would mistakenly think that a class named -// iterator is an STL container. -// -// Also note that the simpler approach of overloading -// IsContainerTest(typename C::const_iterator*) and -// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++. -typedef int IsContainer; -template -IsContainer IsContainerTest(int /* dummy */, - typename C::iterator* /* it */ = NULL, - typename C::const_iterator* /* const_it */ = NULL) { - return 0; -} - -typedef char IsNotContainer; -template -IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; } - -// EnableIf::type is void when 'Cond' is true, and -// undefined when 'Cond' is false. To use SFINAE to make a function -// overload only apply when a particular expression is true, add -// "typename EnableIf::type* = 0" as the last parameter. -template struct EnableIf; -template<> struct EnableIf { typedef void type; }; // NOLINT - -// Utilities for native arrays. - -// ArrayEq() compares two k-dimensional native arrays using the -// elements' operator==, where k can be any integer >= 0. When k is -// 0, ArrayEq() degenerates into comparing a single pair of values. - -template -bool ArrayEq(const T* lhs, size_t size, const U* rhs); - -// This generic version is used when k is 0. -template -inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } - -// This overload is used when k >= 1. -template -inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { - return internal::ArrayEq(lhs, N, rhs); -} - -// This helper reduces code bloat. If we instead put its logic inside -// the previous ArrayEq() function, arrays with different sizes would -// lead to different copies of the template code. -template -bool ArrayEq(const T* lhs, size_t size, const U* rhs) { - for (size_t i = 0; i != size; i++) { - if (!internal::ArrayEq(lhs[i], rhs[i])) - return false; - } - return true; -} - -// Finds the first element in the iterator range [begin, end) that -// equals elem. Element may be a native array type itself. -template -Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { - for (Iter it = begin; it != end; ++it) { - if (internal::ArrayEq(*it, elem)) - return it; - } - return end; -} - -// CopyArray() copies a k-dimensional native array using the elements' -// operator=, where k can be any integer >= 0. When k is 0, -// CopyArray() degenerates into copying a single value. - -template -void CopyArray(const T* from, size_t size, U* to); - -// This generic version is used when k is 0. -template -inline void CopyArray(const T& from, U* to) { *to = from; } - -// This overload is used when k >= 1. -template -inline void CopyArray(const T(&from)[N], U(*to)[N]) { - internal::CopyArray(from, N, *to); -} - -// This helper reduces code bloat. If we instead put its logic inside -// the previous CopyArray() function, arrays with different sizes -// would lead to different copies of the template code. -template -void CopyArray(const T* from, size_t size, U* to) { - for (size_t i = 0; i != size; i++) { - internal::CopyArray(from[i], to + i); - } -} - -// The relation between an NativeArray object (see below) and the -// native array it represents. -enum RelationToSource { - kReference, // The NativeArray references the native array. - kCopy // The NativeArray makes a copy of the native array and - // owns the copy. -}; - -// Adapts a native array to a read-only STL-style container. Instead -// of the complete STL container concept, this adaptor only implements -// members useful for Google Mock's container matchers. New members -// should be added as needed. To simplify the implementation, we only -// support Element being a raw type (i.e. having no top-level const or -// reference modifier). It's the client's responsibility to satisfy -// this requirement. Element can be an array type itself (hence -// multi-dimensional arrays are supported). -template -class NativeArray { - public: - // STL-style container typedefs. - typedef Element value_type; - typedef Element* iterator; - typedef const Element* const_iterator; - - // Constructs from a native array. - NativeArray(const Element* array, size_t count, RelationToSource relation) { - Init(array, count, relation); - } - - // Copy constructor. - NativeArray(const NativeArray& rhs) { - Init(rhs.array_, rhs.size_, rhs.relation_to_source_); - } - - ~NativeArray() { - // Ensures that the user doesn't instantiate NativeArray with a - // const or reference type. - static_cast(StaticAssertTypeEqHelper()); - if (relation_to_source_ == kCopy) - delete[] array_; - } - - // STL-style container methods. - size_t size() const { return size_; } - const_iterator begin() const { return array_; } - const_iterator end() const { return array_ + size_; } - bool operator==(const NativeArray& rhs) const { - return size() == rhs.size() && - ArrayEq(begin(), size(), rhs.begin()); - } - - private: - // Initializes this object; makes a copy of the input array if - // 'relation' is kCopy. - void Init(const Element* array, size_t a_size, RelationToSource relation) { - if (relation == kReference) { - array_ = array; - } else { - Element* const copy = new Element[a_size]; - CopyArray(array, a_size, copy); - array_ = copy; - } - size_ = a_size; - relation_to_source_ = relation; - } - - const Element* array_; - size_t size_; - RelationToSource relation_to_source_; - - GTEST_DISALLOW_ASSIGN_(NativeArray); -}; - -} // namespace internal -} // namespace testing - -#define GTEST_MESSAGE_AT_(file, line, message, result_type) \ - ::testing::internal::AssertHelper(result_type, file, line, message) \ - = ::testing::Message() - -#define GTEST_MESSAGE_(message, result_type) \ - GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) - -#define GTEST_FATAL_FAILURE_(message) \ - return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure) - -#define GTEST_NONFATAL_FAILURE_(message) \ - GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure) - -#define GTEST_SUCCESS_(message) \ - GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess) - -// Suppresses MSVC warnings 4072 (unreachable code) for the code following -// statement if it returns or throws (or doesn't return or throw in some -// situations). -#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \ - if (::testing::internal::AlwaysTrue()) { statement; } - -#define GTEST_TEST_THROW_(statement, expected_exception, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::ConstCharPtr gtest_msg = "") { \ - bool gtest_caught_expected = false; \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch (expected_exception const&) { \ - gtest_caught_expected = true; \ - } \ - catch (...) { \ - gtest_msg.value = \ - "Expected: " #statement " throws an exception of type " \ - #expected_exception ".\n Actual: it throws a different type."; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ - } \ - if (!gtest_caught_expected) { \ - gtest_msg.value = \ - "Expected: " #statement " throws an exception of type " \ - #expected_exception ".\n Actual: it throws nothing."; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ - fail(gtest_msg.value) - -#define GTEST_TEST_NO_THROW_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch ( std::exception &e ) { \ - GTEST_LOG_(INFO) \ - << "Unexpected exception: what: \"" << e.what() << "\".\n"; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ - } \ - catch (...) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ - fail("Expected: " #statement " doesn't throw an exception.\n" \ - " Actual: it throws.") - -#define GTEST_TEST_ANY_THROW_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - bool gtest_caught_any = false; \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch (...) { \ - gtest_caught_any = true; \ - } \ - if (!gtest_caught_any) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ - fail("Expected: " #statement " throws an exception.\n" \ - " Actual: it doesn't.") - - -// Implements Boolean test assertions such as EXPECT_TRUE. expression can be -// either a boolean expression or an AssertionResult. text is a textual -// represenation of expression as it was passed into the EXPECT_TRUE. -#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (const ::testing::AssertionResult gtest_ar_ = \ - ::testing::AssertionResult(expression)) \ - ; \ - else \ - fail(::testing::internal::GetBoolAssertionFailureMessage(\ - gtest_ar_, text, #actual, #expected).c_str()) - -#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ - fail("Expected: " #statement " doesn't generate new fatal " \ - "failures in the current thread.\n" \ - " Actual: it does.") - -// Expands to the name of the class that implements the given test. -#define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ - test_case_name##_##test_name##_Test - -// Helper macro for defining tests. -#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\ -class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\ - public:\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\ - private:\ - virtual void TestBody();\ - static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\ - GTEST_DISALLOW_COPY_AND_ASSIGN_(\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\ -};\ -\ -::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\ - ::test_info_ =\ - ::testing::internal::MakeAndRegisterTestInfo(\ - #test_case_name, #test_name, NULL, NULL, \ - (parent_id), \ - parent_class::SetUpTestCase, \ - parent_class::TearDownTestCase, \ - new ::testing::internal::TestFactoryImpl<\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\ -void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ -// Copyright 2005, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) -// -// The Google C++ Testing Framework (Google Test) -// -// This header file defines the public API for death tests. It is -// #included by gtest.h so a user doesn't need to include this -// directly. - -#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ -#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ - -// Copyright 2005, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) -// -// The Google C++ Testing Framework (Google Test) -// -// This header file defines internal utilities needed for implementing -// death tests. They are subject to change without notice. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ - - -#include - -namespace testing { -namespace internal { - -GTEST_DECLARE_string_(internal_run_death_test); - -// Names of the flags (needed for parsing Google Test flags). -const char kDeathTestStyleFlag[] = "death_test_style"; -const char kDeathTestUseFork[] = "death_test_use_fork"; -const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; - -#if GTEST_HAS_DEATH_TEST - -// DeathTest is a class that hides much of the complexity of the -// GTEST_DEATH_TEST_ macro. It is abstract; its static Create method -// returns a concrete class that depends on the prevailing death test -// style, as defined by the --gtest_death_test_style and/or -// --gtest_internal_run_death_test flags. - -// In describing the results of death tests, these terms are used with -// the corresponding definitions: -// -// exit status: The integer exit information in the format specified -// by wait(2) -// exit code: The integer code passed to exit(3), _exit(2), or -// returned from main() -class GTEST_API_ DeathTest { - public: - // Create returns false if there was an error determining the - // appropriate action to take for the current death test; for example, - // if the gtest_death_test_style flag is set to an invalid value. - // The LastMessage method will return a more detailed message in that - // case. Otherwise, the DeathTest pointer pointed to by the "test" - // argument is set. If the death test should be skipped, the pointer - // is set to NULL; otherwise, it is set to the address of a new concrete - // DeathTest object that controls the execution of the current test. - static bool Create(const char* statement, const RE* regex, - const char* file, int line, DeathTest** test); - DeathTest(); - virtual ~DeathTest() { } - - // A helper class that aborts a death test when it's deleted. - class ReturnSentinel { - public: - explicit ReturnSentinel(DeathTest* test) : test_(test) { } - ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } - private: - DeathTest* const test_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); - } GTEST_ATTRIBUTE_UNUSED_; - - // An enumeration of possible roles that may be taken when a death - // test is encountered. EXECUTE means that the death test logic should - // be executed immediately. OVERSEE means that the program should prepare - // the appropriate environment for a child process to execute the death - // test, then wait for it to complete. - enum TestRole { OVERSEE_TEST, EXECUTE_TEST }; - - // An enumeration of the three reasons that a test might be aborted. - enum AbortReason { - TEST_ENCOUNTERED_RETURN_STATEMENT, - TEST_THREW_EXCEPTION, - TEST_DID_NOT_DIE - }; - - // Assumes one of the above roles. - virtual TestRole AssumeRole() = 0; - - // Waits for the death test to finish and returns its status. - virtual int Wait() = 0; - - // Returns true if the death test passed; that is, the test process - // exited during the test, its exit status matches a user-supplied - // predicate, and its stderr output matches a user-supplied regular - // expression. - // The user-supplied predicate may be a macro expression rather - // than a function pointer or functor, or else Wait and Passed could - // be combined. - virtual bool Passed(bool exit_status_ok) = 0; - - // Signals that the death test did not die as expected. - virtual void Abort(AbortReason reason) = 0; - - // Returns a human-readable outcome message regarding the outcome of - // the last death test. - static const char* LastMessage(); - - static void set_last_death_test_message(const String& message); - - private: - // A string containing a description of the outcome of the last death test. - static String last_death_test_message_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); -}; - -// Factory interface for death tests. May be mocked out for testing. -class DeathTestFactory { - public: - virtual ~DeathTestFactory() { } - virtual bool Create(const char* statement, const RE* regex, - const char* file, int line, DeathTest** test) = 0; -}; - -// A concrete DeathTestFactory implementation for normal use. -class DefaultDeathTestFactory : public DeathTestFactory { - public: - virtual bool Create(const char* statement, const RE* regex, - const char* file, int line, DeathTest** test); -}; - -// Returns true if exit_status describes a process that was terminated -// by a signal, or exited normally with a nonzero exit code. -GTEST_API_ bool ExitedUnsuccessfully(int exit_status); - -// Traps C++ exceptions escaping statement and reports them as test -// failures. Note that trapping SEH exceptions is not implemented here. -# if GTEST_HAS_EXCEPTIONS -# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } catch (const ::std::exception& gtest_exception) { \ - fprintf(\ - stderr, \ - "\n%s: Caught std::exception-derived exception escaping the " \ - "death test statement. Exception message: %s\n", \ - ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ - gtest_exception.what()); \ - fflush(stderr); \ - death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ - } catch (...) { \ - death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ - } - -# else -# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) - -# endif - -// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, -// ASSERT_EXIT*, and EXPECT_EXIT*. -# define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - const ::testing::internal::RE& gtest_regex = (regex); \ - ::testing::internal::DeathTest* gtest_dt; \ - if (!::testing::internal::DeathTest::Create(#statement, >est_regex, \ - __FILE__, __LINE__, >est_dt)) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ - } \ - if (gtest_dt != NULL) { \ - ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \ - gtest_dt_ptr(gtest_dt); \ - switch (gtest_dt->AssumeRole()) { \ - case ::testing::internal::DeathTest::OVERSEE_TEST: \ - if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ - } \ - break; \ - case ::testing::internal::DeathTest::EXECUTE_TEST: { \ - ::testing::internal::DeathTest::ReturnSentinel \ - gtest_sentinel(gtest_dt); \ - GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ - gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ - break; \ - } \ - default: \ - break; \ - } \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \ - fail(::testing::internal::DeathTest::LastMessage()) -// The symbol "fail" here expands to something into which a message -// can be streamed. - -// A class representing the parsed contents of the -// --gtest_internal_run_death_test flag, as it existed when -// RUN_ALL_TESTS was called. -class InternalRunDeathTestFlag { - public: - InternalRunDeathTestFlag(const String& a_file, - int a_line, - int an_index, - int a_write_fd) - : file_(a_file), line_(a_line), index_(an_index), - write_fd_(a_write_fd) {} - - ~InternalRunDeathTestFlag() { - if (write_fd_ >= 0) - posix::Close(write_fd_); - } - - String file() const { return file_; } - int line() const { return line_; } - int index() const { return index_; } - int write_fd() const { return write_fd_; } - - private: - String file_; - int line_; - int index_; - int write_fd_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag); -}; - -// Returns a newly created InternalRunDeathTestFlag object with fields -// initialized from the GTEST_FLAG(internal_run_death_test) flag if -// the flag is specified; otherwise returns NULL. -InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag(); - -#else // GTEST_HAS_DEATH_TEST - -// This macro is used for implementing macros such as -// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where -// death tests are not supported. Those macros must compile on such systems -// iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on -// systems that support death tests. This allows one to write such a macro -// on a system that does not support death tests and be sure that it will -// compile on a death-test supporting system. -// -// Parameters: -// statement - A statement that a macro such as EXPECT_DEATH would test -// for program termination. This macro has to make sure this -// statement is compiled but not executed, to ensure that -// EXPECT_DEATH_IF_SUPPORTED compiles with a certain -// parameter iff EXPECT_DEATH compiles with it. -// regex - A regex that a macro such as EXPECT_DEATH would use to test -// the output of statement. This parameter has to be -// compiled but not evaluated by this macro, to ensure that -// this macro only accepts expressions that a macro such as -// EXPECT_DEATH would accept. -// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED -// and a return statement for ASSERT_DEATH_IF_SUPPORTED. -// This ensures that ASSERT_DEATH_IF_SUPPORTED will not -// compile inside functions where ASSERT_DEATH doesn't -// compile. -// -// The branch that has an always false condition is used to ensure that -// statement and regex are compiled (and thus syntactically correct) but -// never executed. The unreachable code macro protects the terminator -// statement from generating an 'unreachable code' warning in case -// statement unconditionally returns or throws. The Message constructor at -// the end allows the syntax of streaming additional messages into the -// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. -# define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - GTEST_LOG_(WARNING) \ - << "Death tests are not supported on this platform.\n" \ - << "Statement '" #statement "' cannot be verified."; \ - } else if (::testing::internal::AlwaysFalse()) { \ - ::testing::internal::RE::PartialMatch(".*", (regex)); \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - terminator; \ - } else \ - ::testing::Message() - -#endif // GTEST_HAS_DEATH_TEST - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ - -namespace testing { - -// This flag controls the style of death tests. Valid values are "threadsafe", -// meaning that the death test child process will re-execute the test binary -// from the start, running only a single death test, or "fast", -// meaning that the child process will execute the test logic immediately -// after forking. -GTEST_DECLARE_string_(death_test_style); - -#if GTEST_HAS_DEATH_TEST - -// The following macros are useful for writing death tests. - -// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is -// executed: -// -// 1. It generates a warning if there is more than one active -// thread. This is because it's safe to fork() or clone() only -// when there is a single thread. -// -// 2. The parent process clone()s a sub-process and runs the death -// test in it; the sub-process exits with code 0 at the end of the -// death test, if it hasn't exited already. -// -// 3. The parent process waits for the sub-process to terminate. -// -// 4. The parent process checks the exit code and error message of -// the sub-process. -// -// Examples: -// -// ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number"); -// for (int i = 0; i < 5; i++) { -// EXPECT_DEATH(server.ProcessRequest(i), -// "Invalid request .* in ProcessRequest()") -// << "Failed to die on request " << i); -// } -// -// ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting"); -// -// bool KilledBySIGHUP(int exit_code) { -// return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP; -// } -// -// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!"); -// -// On the regular expressions used in death tests: -// -// On POSIX-compliant systems (*nix), we use the library, -// which uses the POSIX extended regex syntax. -// -// On other platforms (e.g. Windows), we only support a simple regex -// syntax implemented as part of Google Test. This limited -// implementation should be enough most of the time when writing -// death tests; though it lacks many features you can find in PCRE -// or POSIX extended regex syntax. For example, we don't support -// union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and -// repetition count ("x{5,7}"), among others. -// -// Below is the syntax that we do support. We chose it to be a -// subset of both PCRE and POSIX extended regex, so it's easy to -// learn wherever you come from. In the following: 'A' denotes a -// literal character, period (.), or a single \\ escape sequence; -// 'x' and 'y' denote regular expressions; 'm' and 'n' are for -// natural numbers. -// -// c matches any literal character c -// \\d matches any decimal digit -// \\D matches any character that's not a decimal digit -// \\f matches \f -// \\n matches \n -// \\r matches \r -// \\s matches any ASCII whitespace, including \n -// \\S matches any character that's not a whitespace -// \\t matches \t -// \\v matches \v -// \\w matches any letter, _, or decimal digit -// \\W matches any character that \\w doesn't match -// \\c matches any literal character c, which must be a punctuation -// . matches any single character except \n -// A? matches 0 or 1 occurrences of A -// A* matches 0 or many occurrences of A -// A+ matches 1 or many occurrences of A -// ^ matches the beginning of a string (not that of each line) -// $ matches the end of a string (not that of each line) -// xy matches x followed by y -// -// If you accidentally use PCRE or POSIX extended regex features -// not implemented by us, you will get a run-time failure. In that -// case, please try to rewrite your regular expression within the -// above syntax. -// -// This implementation is *not* meant to be as highly tuned or robust -// as a compiled regex library, but should perform well enough for a -// death test, which already incurs significant overhead by launching -// a child process. -// -// Known caveats: -// -// A "threadsafe" style death test obtains the path to the test -// program from argv[0] and re-executes it in the sub-process. For -// simplicity, the current implementation doesn't search the PATH -// when launching the sub-process. This means that the user must -// invoke the test program via a path that contains at least one -// path separator (e.g. path/to/foo_test and -// /absolute/path/to/bar_test are fine, but foo_test is not). This -// is rarely a problem as people usually don't put the test binary -// directory in PATH. -// -// TODO(wan@google.com): make thread-safe death tests search the PATH. - -// Asserts that a given statement causes the program to exit, with an -// integer exit status that satisfies predicate, and emitting error output -// that matches regex. -# define ASSERT_EXIT(statement, predicate, regex) \ - GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) - -// Like ASSERT_EXIT, but continues on to successive tests in the -// test case, if any: -# define EXPECT_EXIT(statement, predicate, regex) \ - GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_) - -// Asserts that a given statement causes the program to exit, either by -// explicitly exiting with a nonzero exit code or being killed by a -// signal, and emitting error output that matches regex. -# define ASSERT_DEATH(statement, regex) \ - ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) - -// Like ASSERT_DEATH, but continues on to successive tests in the -// test case, if any: -# define EXPECT_DEATH(statement, regex) \ - EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) - -// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: - -// Tests that an exit code describes a normal exit with a given exit code. -class GTEST_API_ ExitedWithCode { - public: - explicit ExitedWithCode(int exit_code); - bool operator()(int exit_status) const; - private: - // No implementation - assignment is unsupported. - void operator=(const ExitedWithCode& other); - - const int exit_code_; -}; - -# if !GTEST_OS_WINDOWS -// Tests that an exit code describes an exit due to termination by a -// given signal. -class GTEST_API_ KilledBySignal { - public: - explicit KilledBySignal(int signum); - bool operator()(int exit_status) const; - private: - const int signum_; -}; -# endif // !GTEST_OS_WINDOWS - -// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. -// The death testing framework causes this to have interesting semantics, -// since the sideeffects of the call are only visible in opt mode, and not -// in debug mode. -// -// In practice, this can be used to test functions that utilize the -// LOG(DFATAL) macro using the following style: -// -// int DieInDebugOr12(int* sideeffect) { -// if (sideeffect) { -// *sideeffect = 12; -// } -// LOG(DFATAL) << "death"; -// return 12; -// } -// -// TEST(TestCase, TestDieOr12WorksInDgbAndOpt) { -// int sideeffect = 0; -// // Only asserts in dbg. -// EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death"); -// -// #ifdef NDEBUG -// // opt-mode has sideeffect visible. -// EXPECT_EQ(12, sideeffect); -// #else -// // dbg-mode no visible sideeffect. -// EXPECT_EQ(0, sideeffect); -// #endif -// } -// -// This will assert that DieInDebugReturn12InOpt() crashes in debug -// mode, usually due to a DCHECK or LOG(DFATAL), but returns the -// appropriate fallback value (12 in this case) in opt mode. If you -// need to test that a function has appropriate side-effects in opt -// mode, include assertions against the side-effects. A general -// pattern for this is: -// -// EXPECT_DEBUG_DEATH({ -// // Side-effects here will have an effect after this statement in -// // opt mode, but none in debug mode. -// EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); -// }, "death"); -// -# ifdef NDEBUG - -# define EXPECT_DEBUG_DEATH(statement, regex) \ - do { statement; } while (::testing::internal::AlwaysFalse()) - -# define ASSERT_DEBUG_DEATH(statement, regex) \ - do { statement; } while (::testing::internal::AlwaysFalse()) - -# else - -# define EXPECT_DEBUG_DEATH(statement, regex) \ - EXPECT_DEATH(statement, regex) - -# define ASSERT_DEBUG_DEATH(statement, regex) \ - ASSERT_DEATH(statement, regex) - -# endif // NDEBUG for EXPECT_DEBUG_DEATH -#endif // GTEST_HAS_DEATH_TEST - -// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and -// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if -// death tests are supported; otherwise they just issue a warning. This is -// useful when you are combining death test assertions with normal test -// assertions in one test. -#if GTEST_HAS_DEATH_TEST -# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ - EXPECT_DEATH(statement, regex) -# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ - ASSERT_DEATH(statement, regex) -#else -# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ - GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, ) -# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ - GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return) -#endif - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ -// Copyright 2005, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) -// -// The Google C++ Testing Framework (Google Test) -// -// This header file defines the Message class. -// -// IMPORTANT NOTE: Due to limitation of the C++ language, we have to -// leave some internal implementation details in this header file. -// They are clearly marked by comments like this: -// -// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -// -// Such code is NOT meant to be used by a user directly, and is subject -// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user -// program! - -#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ -#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ - -#include - - -namespace testing { - -// The Message class works like an ostream repeater. -// -// Typical usage: -// -// 1. You stream a bunch of values to a Message object. -// It will remember the text in a stringstream. -// 2. Then you stream the Message object to an ostream. -// This causes the text in the Message to be streamed -// to the ostream. -// -// For example; -// -// testing::Message foo; -// foo << 1 << " != " << 2; -// std::cout << foo; -// -// will print "1 != 2". -// -// Message is not intended to be inherited from. In particular, its -// destructor is not virtual. -// -// Note that stringstream behaves differently in gcc and in MSVC. You -// can stream a NULL char pointer to it in the former, but not in the -// latter (it causes an access violation if you do). The Message -// class hides this difference by treating a NULL char pointer as -// "(null)". -class GTEST_API_ Message { - private: - // The type of basic IO manipulators (endl, ends, and flush) for - // narrow streams. - typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&); - - public: - // Constructs an empty Message. - // We allocate the stringstream separately because otherwise each use of - // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's - // stack frame leading to huge stack frames in some cases; gcc does not reuse - // the stack space. - Message() : ss_(new ::std::stringstream) { - // By default, we want there to be enough precision when printing - // a double to a Message. - *ss_ << std::setprecision(std::numeric_limits::digits10 + 2); - } - - // Copy constructor. - Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT - *ss_ << msg.GetString(); - } - - // Constructs a Message from a C-string. - explicit Message(const char* str) : ss_(new ::std::stringstream) { - *ss_ << str; - } - -#if GTEST_OS_SYMBIAN - // Streams a value (either a pointer or not) to this object. - template - inline Message& operator <<(const T& value) { - StreamHelper(typename internal::is_pointer::type(), value); - return *this; - } -#else - // Streams a non-pointer value to this object. - template - inline Message& operator <<(const T& val) { - ::GTestStreamToHelper(ss_.get(), val); - return *this; - } - - // Streams a pointer value to this object. - // - // This function is an overload of the previous one. When you - // stream a pointer to a Message, this definition will be used as it - // is more specialized. (The C++ Standard, section - // [temp.func.order].) If you stream a non-pointer, then the - // previous definition will be used. - // - // The reason for this overload is that streaming a NULL pointer to - // ostream is undefined behavior. Depending on the compiler, you - // may get "0", "(nil)", "(null)", or an access violation. To - // ensure consistent result across compilers, we always treat NULL - // as "(null)". - template - inline Message& operator <<(T* const& pointer) { // NOLINT - if (pointer == NULL) { - *ss_ << "(null)"; - } else { - ::GTestStreamToHelper(ss_.get(), pointer); - } - return *this; - } -#endif // GTEST_OS_SYMBIAN - - // Since the basic IO manipulators are overloaded for both narrow - // and wide streams, we have to provide this specialized definition - // of operator <<, even though its body is the same as the - // templatized version above. Without this definition, streaming - // endl or other basic IO manipulators to Message will confuse the - // compiler. - Message& operator <<(BasicNarrowIoManip val) { - *ss_ << val; - return *this; - } - - // Instead of 1/0, we want to see true/false for bool values. - Message& operator <<(bool b) { - return *this << (b ? "true" : "false"); - } - - // These two overloads allow streaming a wide C string to a Message - // using the UTF-8 encoding. - Message& operator <<(const wchar_t* wide_c_str) { - return *this << internal::String::ShowWideCString(wide_c_str); - } - Message& operator <<(wchar_t* wide_c_str) { - return *this << internal::String::ShowWideCString(wide_c_str); - } - -#if GTEST_HAS_STD_WSTRING - // Converts the given wide string to a narrow string using the UTF-8 - // encoding, and streams the result to this Message object. - Message& operator <<(const ::std::wstring& wstr); -#endif // GTEST_HAS_STD_WSTRING - -#if GTEST_HAS_GLOBAL_WSTRING - // Converts the given wide string to a narrow string using the UTF-8 - // encoding, and streams the result to this Message object. - Message& operator <<(const ::wstring& wstr); -#endif // GTEST_HAS_GLOBAL_WSTRING - - // Gets the text streamed to this object so far as a String. - // Each '\0' character in the buffer is replaced with "\\0". - // - // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - internal::String GetString() const { - return internal::StringStreamToString(ss_.get()); - } - - private: - -#if GTEST_OS_SYMBIAN - // These are needed as the Nokia Symbian Compiler cannot decide between - // const T& and const T* in a function template. The Nokia compiler _can_ - // decide between class template specializations for T and T*, so a - // tr1::type_traits-like is_pointer works, and we can overload on that. - template - inline void StreamHelper(internal::true_type /*dummy*/, T* pointer) { - if (pointer == NULL) { - *ss_ << "(null)"; - } else { - ::GTestStreamToHelper(ss_.get(), pointer); - } - } - template - inline void StreamHelper(internal::false_type /*dummy*/, const T& value) { - ::GTestStreamToHelper(ss_.get(), value); - } -#endif // GTEST_OS_SYMBIAN - - // We'll hold the text streamed to this object here. - const internal::scoped_ptr< ::std::stringstream> ss_; - - // We declare (but don't implement) this to prevent the compiler - // from implementing the assignment operator. - void operator=(const Message&); -}; - -// Streams a Message to an ostream. -inline std::ostream& operator <<(std::ostream& os, const Message& sb) { - return os << sb.GetString(); -} - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ -// This file was GENERATED by command: -// pump.py gtest-param-test.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2008, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Authors: vladl@google.com (Vlad Losev) -// -// Macros and functions for implementing parameterized tests -// in Google C++ Testing Framework (Google Test) -// -// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! -// -#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ -#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ - - -// Value-parameterized tests allow you to test your code with different -// parameters without writing multiple copies of the same test. -// -// Here is how you use value-parameterized tests: - -#if 0 - -// To write value-parameterized tests, first you should define a fixture -// class. It is usually derived from testing::TestWithParam (see below for -// another inheritance scheme that's sometimes useful in more complicated -// class hierarchies), where the type of your parameter values. -// TestWithParam is itself derived from testing::Test. T can be any -// copyable type. If it's a raw pointer, you are responsible for managing the -// lifespan of the pointed values. - -class FooTest : public ::testing::TestWithParam { - // You can implement all the usual class fixture members here. -}; - -// Then, use the TEST_P macro to define as many parameterized tests -// for this fixture as you want. The _P suffix is for "parameterized" -// or "pattern", whichever you prefer to think. - -TEST_P(FooTest, DoesBlah) { - // Inside a test, access the test parameter with the GetParam() method - // of the TestWithParam class: - EXPECT_TRUE(foo.Blah(GetParam())); - ... -} - -TEST_P(FooTest, HasBlahBlah) { - ... -} - -// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test -// case with any set of parameters you want. Google Test defines a number -// of functions for generating test parameters. They return what we call -// (surprise!) parameter generators. Here is a summary of them, which -// are all in the testing namespace: -// -// -// Range(begin, end [, step]) - Yields values {begin, begin+step, -// begin+step+step, ...}. The values do not -// include end. step defaults to 1. -// Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}. -// ValuesIn(container) - Yields values from a C-style array, an STL -// ValuesIn(begin,end) container, or an iterator range [begin, end). -// Bool() - Yields sequence {false, true}. -// Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product -// for the math savvy) of the values generated -// by the N generators. -// -// For more details, see comments at the definitions of these functions below -// in this file. -// -// The following statement will instantiate tests from the FooTest test case -// each with parameter values "meeny", "miny", and "moe". - -INSTANTIATE_TEST_CASE_P(InstantiationName, - FooTest, - Values("meeny", "miny", "moe")); - -// To distinguish different instances of the pattern, (yes, you -// can instantiate it more then once) the first argument to the -// INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the -// actual test case name. Remember to pick unique prefixes for different -// instantiations. The tests from the instantiation above will have -// these names: -// -// * InstantiationName/FooTest.DoesBlah/0 for "meeny" -// * InstantiationName/FooTest.DoesBlah/1 for "miny" -// * InstantiationName/FooTest.DoesBlah/2 for "moe" -// * InstantiationName/FooTest.HasBlahBlah/0 for "meeny" -// * InstantiationName/FooTest.HasBlahBlah/1 for "miny" -// * InstantiationName/FooTest.HasBlahBlah/2 for "moe" -// -// You can use these names in --gtest_filter. -// -// This statement will instantiate all tests from FooTest again, each -// with parameter values "cat" and "dog": - -const char* pets[] = {"cat", "dog"}; -INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); - -// The tests from the instantiation above will have these names: -// -// * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat" -// * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog" -// * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" -// * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" -// -// Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests -// in the given test case, whether their definitions come before or -// AFTER the INSTANTIATE_TEST_CASE_P statement. -// -// Please also note that generator expressions (including parameters to the -// generators) are evaluated in InitGoogleTest(), after main() has started. -// This allows the user on one hand, to adjust generator parameters in order -// to dynamically determine a set of tests to run and on the other hand, -// give the user a chance to inspect the generated tests with Google Test -// reflection API before RUN_ALL_TESTS() is executed. -// -// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc -// for more examples. -// -// In the future, we plan to publish the API for defining new parameter -// generators. But for now this interface remains part of the internal -// implementation and is subject to change. -// -// -// A parameterized test fixture must be derived from testing::Test and from -// testing::WithParamInterface, where T is the type of the parameter -// values. Inheriting from TestWithParam satisfies that requirement because -// TestWithParam inherits from both Test and WithParamInterface. In more -// complicated hierarchies, however, it is occasionally useful to inherit -// separately from Test and WithParamInterface. For example: - -class BaseTest : public ::testing::Test { - // You can inherit all the usual members for a non-parameterized test - // fixture here. -}; - -class DerivedTest : public BaseTest, public ::testing::WithParamInterface { - // The usual test fixture members go here too. -}; - -TEST_F(BaseTest, HasFoo) { - // This is an ordinary non-parameterized test. -} - -TEST_P(DerivedTest, DoesBlah) { - // GetParam works just the same here as if you inherit from TestWithParam. - EXPECT_TRUE(foo.Blah(GetParam())); -} - -#endif // 0 - - -#if !GTEST_OS_SYMBIAN -# include -#endif - -// scripts/fuse_gtest.py depends on gtest's own header being #included -// *unconditionally*. Therefore these #includes cannot be moved -// inside #if GTEST_HAS_PARAM_TEST. -// Copyright 2008 Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: vladl@google.com (Vlad Losev) - -// Type and function utilities for implementing parameterized tests. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ - -#include -#include -#include - -// scripts/fuse_gtest.py depends on gtest's own header being #included -// *unconditionally*. Therefore these #includes cannot be moved -// inside #if GTEST_HAS_PARAM_TEST. -// Copyright 2003 Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Authors: Dan Egnor (egnor@google.com) -// -// A "smart" pointer type with reference tracking. Every pointer to a -// particular object is kept on a circular linked list. When the last pointer -// to an object is destroyed or reassigned, the object is deleted. -// -// Used properly, this deletes the object when the last reference goes away. -// There are several caveats: -// - Like all reference counting schemes, cycles lead to leaks. -// - Each smart pointer is actually two pointers (8 bytes instead of 4). -// - Every time a pointer is assigned, the entire list of pointers to that -// object is traversed. This class is therefore NOT SUITABLE when there -// will often be more than two or three pointers to a particular object. -// - References are only tracked as long as linked_ptr<> objects are copied. -// If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS -// will happen (double deletion). -// -// A good use of this class is storing object references in STL containers. -// You can safely put linked_ptr<> in a vector<>. -// Other uses may not be as good. -// -// Note: If you use an incomplete type with linked_ptr<>, the class -// *containing* linked_ptr<> must have a constructor and destructor (even -// if they do nothing!). -// -// Bill Gibbons suggested we use something like this. -// -// Thread Safety: -// Unlike other linked_ptr implementations, in this implementation -// a linked_ptr object is thread-safe in the sense that: -// - it's safe to copy linked_ptr objects concurrently, -// - it's safe to copy *from* a linked_ptr and read its underlying -// raw pointer (e.g. via get()) concurrently, and -// - it's safe to write to two linked_ptrs that point to the same -// shared object concurrently. -// TODO(wan@google.com): rename this to safe_linked_ptr to avoid -// confusion with normal linked_ptr. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ - -#include -#include - - -namespace testing { -namespace internal { - -// Protects copying of all linked_ptr objects. -GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_linked_ptr_mutex); - -// This is used internally by all instances of linked_ptr<>. It needs to be -// a non-template class because different types of linked_ptr<> can refer to -// the same object (linked_ptr(obj) vs linked_ptr(obj)). -// So, it needs to be possible for different types of linked_ptr to participate -// in the same circular linked list, so we need a single class type here. -// -// DO NOT USE THIS CLASS DIRECTLY YOURSELF. Use linked_ptr. -class linked_ptr_internal { - public: - // Create a new circle that includes only this instance. - void join_new() { - next_ = this; - } - - // Many linked_ptr operations may change p.link_ for some linked_ptr - // variable p in the same circle as this object. Therefore we need - // to prevent two such operations from occurring concurrently. - // - // Note that different types of linked_ptr objects can coexist in a - // circle (e.g. linked_ptr, linked_ptr, and - // linked_ptr). Therefore we must use a single mutex to - // protect all linked_ptr objects. This can create serious - // contention in production code, but is acceptable in a testing - // framework. - - // Join an existing circle. - // L < g_linked_ptr_mutex - void join(linked_ptr_internal const* ptr) { - MutexLock lock(&g_linked_ptr_mutex); - - linked_ptr_internal const* p = ptr; - while (p->next_ != ptr) p = p->next_; - p->next_ = this; - next_ = ptr; - } - - // Leave whatever circle we're part of. Returns true if we were the - // last member of the circle. Once this is done, you can join() another. - // L < g_linked_ptr_mutex - bool depart() { - MutexLock lock(&g_linked_ptr_mutex); - - if (next_ == this) return true; - linked_ptr_internal const* p = next_; - while (p->next_ != this) p = p->next_; - p->next_ = next_; - return false; - } - - private: - mutable linked_ptr_internal const* next_; -}; - -template -class linked_ptr { - public: - typedef T element_type; - - // Take over ownership of a raw pointer. This should happen as soon as - // possible after the object is created. - explicit linked_ptr(T* ptr = NULL) { capture(ptr); } - ~linked_ptr() { depart(); } - - // Copy an existing linked_ptr<>, adding ourselves to the list of references. - template linked_ptr(linked_ptr const& ptr) { copy(&ptr); } - linked_ptr(linked_ptr const& ptr) { // NOLINT - assert(&ptr != this); - copy(&ptr); - } - - // Assignment releases the old value and acquires the new. - template linked_ptr& operator=(linked_ptr const& ptr) { - depart(); - copy(&ptr); - return *this; - } - - linked_ptr& operator=(linked_ptr const& ptr) { - if (&ptr != this) { - depart(); - copy(&ptr); - } - return *this; - } - - // Smart pointer members. - void reset(T* ptr = NULL) { - depart(); - capture(ptr); - } - T* get() const { return value_; } - T* operator->() const { return value_; } - T& operator*() const { return *value_; } - - bool operator==(T* p) const { return value_ == p; } - bool operator!=(T* p) const { return value_ != p; } - template - bool operator==(linked_ptr const& ptr) const { - return value_ == ptr.get(); - } - template - bool operator!=(linked_ptr const& ptr) const { - return value_ != ptr.get(); - } - - private: - template - friend class linked_ptr; - - T* value_; - linked_ptr_internal link_; - - void depart() { - if (link_.depart()) delete value_; - } - - void capture(T* ptr) { - value_ = ptr; - link_.join_new(); - } - - template void copy(linked_ptr const* ptr) { - value_ = ptr->get(); - if (value_) - link_.join(&ptr->link_); - else - link_.join_new(); - } -}; - -template inline -bool operator==(T* ptr, const linked_ptr& x) { - return ptr == x.get(); -} - -template inline -bool operator!=(T* ptr, const linked_ptr& x) { - return ptr != x.get(); -} - -// A function to convert T* into linked_ptr -// Doing e.g. make_linked_ptr(new FooBarBaz(arg)) is a shorter notation -// for linked_ptr >(new FooBarBaz(arg)) -template -linked_ptr make_linked_ptr(T* ptr) { - return linked_ptr(ptr); -} - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ -// Copyright 2007, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) - -// Google Test - The Google C++ Testing Framework -// -// This file implements a universal value printer that can print a -// value of any type T: -// -// void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); -// -// A user can teach this function how to print a class type T by -// defining either operator<<() or PrintTo() in the namespace that -// defines T. More specifically, the FIRST defined function in the -// following list will be used (assuming T is defined in namespace -// foo): -// -// 1. foo::PrintTo(const T&, ostream*) -// 2. operator<<(ostream&, const T&) defined in either foo or the -// global namespace. -// -// If none of the above is defined, it will print the debug string of -// the value if it is a protocol buffer, or print the raw bytes in the -// value otherwise. -// -// To aid debugging: when T is a reference type, the address of the -// value is also printed; when T is a (const) char pointer, both the -// pointer value and the NUL-terminated string it points to are -// printed. -// -// We also provide some convenient wrappers: -// -// // Prints a value to a string. For a (const or not) char -// // pointer, the NUL-terminated string (but not the pointer) is -// // printed. -// std::string ::testing::PrintToString(const T& value); -// -// // Prints a value tersely: for a reference type, the referenced -// // value (but not the address) is printed; for a (const or not) char -// // pointer, the NUL-terminated string (but not the pointer) is -// // printed. -// void ::testing::internal::UniversalTersePrint(const T& value, ostream*); -// -// // Prints value using the type inferred by the compiler. The difference -// // from UniversalTersePrint() is that this function prints both the -// // pointer and the NUL-terminated string for a (const or not) char pointer. -// void ::testing::internal::UniversalPrint(const T& value, ostream*); -// -// // Prints the fields of a tuple tersely to a string vector, one -// // element for each field. Tuple support must be enabled in -// // gtest-port.h. -// std::vector UniversalTersePrintTupleFieldsToStrings( -// const Tuple& value); -// -// Known limitation: -// -// The print primitives print the elements of an STL-style container -// using the compiler-inferred type of *iter where iter is a -// const_iterator of the container. When const_iterator is an input -// iterator but not a forward iterator, this inferred type may not -// match value_type, and the print output may be incorrect. In -// practice, this is rarely a problem as for most containers -// const_iterator is a forward iterator. We'll fix this if there's an -// actual need for it. Note that this fix cannot rely on value_type -// being defined as many user-defined container types don't have -// value_type. - -#ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ -#define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ - -#include // NOLINT -#include -#include -#include -#include - -namespace testing { - -// Definitions in the 'internal' and 'internal2' name spaces are -// subject to change without notice. DO NOT USE THEM IN USER CODE! -namespace internal2 { - -// Prints the given number of bytes in the given object to the given -// ostream. -GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, - size_t count, - ::std::ostream* os); - -// For selecting which printer to use when a given type has neither << -// nor PrintTo(). -enum TypeKind { - kProtobuf, // a protobuf type - kConvertibleToInteger, // a type implicitly convertible to BiggestInt - // (e.g. a named or unnamed enum type) - kOtherType // anything else -}; - -// TypeWithoutFormatter::PrintValue(value, os) is called -// by the universal printer to print a value of type T when neither -// operator<< nor PrintTo() is defined for T, where kTypeKind is the -// "kind" of T as defined by enum TypeKind. -template -class TypeWithoutFormatter { - public: - // This default version is called when kTypeKind is kOtherType. - static void PrintValue(const T& value, ::std::ostream* os) { - PrintBytesInObjectTo(reinterpret_cast(&value), - sizeof(value), os); - } -}; - -// We print a protobuf using its ShortDebugString() when the string -// doesn't exceed this many characters; otherwise we print it using -// DebugString() for better readability. -const size_t kProtobufOneLinerMaxLength = 50; - -template -class TypeWithoutFormatter { - public: - static void PrintValue(const T& value, ::std::ostream* os) { - const ::testing::internal::string short_str = value.ShortDebugString(); - const ::testing::internal::string pretty_str = - short_str.length() <= kProtobufOneLinerMaxLength ? - short_str : ("\n" + value.DebugString()); - *os << ("<" + pretty_str + ">"); - } -}; - -template -class TypeWithoutFormatter { - public: - // Since T has no << operator or PrintTo() but can be implicitly - // converted to BiggestInt, we print it as a BiggestInt. - // - // Most likely T is an enum type (either named or unnamed), in which - // case printing it as an integer is the desired behavior. In case - // T is not an enum, printing it as an integer is the best we can do - // given that it has no user-defined printer. - static void PrintValue(const T& value, ::std::ostream* os) { - const internal::BiggestInt kBigInt = value; - *os << kBigInt; - } -}; - -// Prints the given value to the given ostream. If the value is a -// protocol message, its debug string is printed; if it's an enum or -// of a type implicitly convertible to BiggestInt, it's printed as an -// integer; otherwise the bytes in the value are printed. This is -// what UniversalPrinter::Print() does when it knows nothing about -// type T and T has neither << operator nor PrintTo(). -// -// A user can override this behavior for a class type Foo by defining -// a << operator in the namespace where Foo is defined. -// -// We put this operator in namespace 'internal2' instead of 'internal' -// to simplify the implementation, as much code in 'internal' needs to -// use << in STL, which would conflict with our own << were it defined -// in 'internal'. -// -// Note that this operator<< takes a generic std::basic_ostream type instead of the more restricted std::ostream. If -// we define it to take an std::ostream instead, we'll get an -// "ambiguous overloads" compiler error when trying to print a type -// Foo that supports streaming to std::basic_ostream, as the compiler cannot tell whether -// operator<<(std::ostream&, const T&) or -// operator<<(std::basic_stream, const Foo&) is more -// specific. -template -::std::basic_ostream& operator<<( - ::std::basic_ostream& os, const T& x) { - TypeWithoutFormatter::value ? kProtobuf : - internal::ImplicitlyConvertible::value ? - kConvertibleToInteger : kOtherType)>::PrintValue(x, &os); - return os; -} - -} // namespace internal2 -} // namespace testing - -// This namespace MUST NOT BE NESTED IN ::testing, or the name look-up -// magic needed for implementing UniversalPrinter won't work. -namespace testing_internal { - -// Used to print a value that is not an STL-style container when the -// user doesn't define PrintTo() for it. -template -void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) { - // With the following statement, during unqualified name lookup, - // testing::internal2::operator<< appears as if it was declared in - // the nearest enclosing namespace that contains both - // ::testing_internal and ::testing::internal2, i.e. the global - // namespace. For more details, refer to the C++ Standard section - // 7.3.4-1 [namespace.udir]. This allows us to fall back onto - // testing::internal2::operator<< in case T doesn't come with a << - // operator. - // - // We cannot write 'using ::testing::internal2::operator<<;', which - // gcc 3.3 fails to compile due to a compiler bug. - using namespace ::testing::internal2; // NOLINT - - // Assuming T is defined in namespace foo, in the next statement, - // the compiler will consider all of: - // - // 1. foo::operator<< (thanks to Koenig look-up), - // 2. ::operator<< (as the current namespace is enclosed in ::), - // 3. testing::internal2::operator<< (thanks to the using statement above). - // - // The operator<< whose type matches T best will be picked. - // - // We deliberately allow #2 to be a candidate, as sometimes it's - // impossible to define #1 (e.g. when foo is ::std, defining - // anything in it is undefined behavior unless you are a compiler - // vendor.). - *os << value; -} - -} // namespace testing_internal - -namespace testing { -namespace internal { - -// UniversalPrinter::Print(value, ostream_ptr) prints the given -// value to the given ostream. The caller must ensure that -// 'ostream_ptr' is not NULL, or the behavior is undefined. -// -// We define UniversalPrinter as a class template (as opposed to a -// function template), as we need to partially specialize it for -// reference types, which cannot be done with function templates. -template -class UniversalPrinter; - -template -void UniversalPrint(const T& value, ::std::ostream* os); - -// Used to print an STL-style container when the user doesn't define -// a PrintTo() for it. -template -void DefaultPrintTo(IsContainer /* dummy */, - false_type /* is not a pointer */, - const C& container, ::std::ostream* os) { - const size_t kMaxCount = 32; // The maximum number of elements to print. - *os << '{'; - size_t count = 0; - for (typename C::const_iterator it = container.begin(); - it != container.end(); ++it, ++count) { - if (count > 0) { - *os << ','; - if (count == kMaxCount) { // Enough has been printed. - *os << " ..."; - break; - } - } - *os << ' '; - // We cannot call PrintTo(*it, os) here as PrintTo() doesn't - // handle *it being a native array. - internal::UniversalPrint(*it, os); - } - - if (count > 0) { - *os << ' '; - } - *os << '}'; -} - -// Used to print a pointer that is neither a char pointer nor a member -// pointer, when the user doesn't define PrintTo() for it. (A member -// variable pointer or member function pointer doesn't really point to -// a location in the address space. Their representation is -// implementation-defined. Therefore they will be printed as raw -// bytes.) -template -void DefaultPrintTo(IsNotContainer /* dummy */, - true_type /* is a pointer */, - T* p, ::std::ostream* os) { - if (p == NULL) { - *os << "NULL"; - } else { - // C++ doesn't allow casting from a function pointer to any object - // pointer. - // - // IsTrue() silences warnings: "Condition is always true", - // "unreachable code". - if (IsTrue(ImplicitlyConvertible::value)) { - // T is not a function type. We just call << to print p, - // relying on ADL to pick up user-defined << for their pointer - // types, if any. - *os << p; - } else { - // T is a function type, so '*os << p' doesn't do what we want - // (it just prints p as bool). We want to print p as a const - // void*. However, we cannot cast it to const void* directly, - // even using reinterpret_cast, as earlier versions of gcc - // (e.g. 3.4.5) cannot compile the cast when p is a function - // pointer. Casting to UInt64 first solves the problem. - *os << reinterpret_cast( - reinterpret_cast(p)); - } - } -} - -// Used to print a non-container, non-pointer value when the user -// doesn't define PrintTo() for it. -template -void DefaultPrintTo(IsNotContainer /* dummy */, - false_type /* is not a pointer */, - const T& value, ::std::ostream* os) { - ::testing_internal::DefaultPrintNonContainerTo(value, os); -} - -// Prints the given value using the << operator if it has one; -// otherwise prints the bytes in it. This is what -// UniversalPrinter::Print() does when PrintTo() is not specialized -// or overloaded for type T. -// -// A user can override this behavior for a class type Foo by defining -// an overload of PrintTo() in the namespace where Foo is defined. We -// give the user this option as sometimes defining a << operator for -// Foo is not desirable (e.g. the coding style may prevent doing it, -// or there is already a << operator but it doesn't do what the user -// wants). -template -void PrintTo(const T& value, ::std::ostream* os) { - // DefaultPrintTo() is overloaded. The type of its first two - // arguments determine which version will be picked. If T is an - // STL-style container, the version for container will be called; if - // T is a pointer, the pointer version will be called; otherwise the - // generic version will be called. - // - // Note that we check for container types here, prior to we check - // for protocol message types in our operator<<. The rationale is: - // - // For protocol messages, we want to give people a chance to - // override Google Mock's format by defining a PrintTo() or - // operator<<. For STL containers, other formats can be - // incompatible with Google Mock's format for the container - // elements; therefore we check for container types here to ensure - // that our format is used. - // - // The second argument of DefaultPrintTo() is needed to bypass a bug - // in Symbian's C++ compiler that prevents it from picking the right - // overload between: - // - // PrintTo(const T& x, ...); - // PrintTo(T* x, ...); - DefaultPrintTo(IsContainerTest(0), is_pointer(), value, os); -} - -// The following list of PrintTo() overloads tells -// UniversalPrinter::Print() how to print standard types (built-in -// types, strings, plain arrays, and pointers). - -// Overloads for various char types. -GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os); -GTEST_API_ void PrintTo(signed char c, ::std::ostream* os); -inline void PrintTo(char c, ::std::ostream* os) { - // When printing a plain char, we always treat it as unsigned. This - // way, the output won't be affected by whether the compiler thinks - // char is signed or not. - PrintTo(static_cast(c), os); -} - -// Overloads for other simple built-in types. -inline void PrintTo(bool x, ::std::ostream* os) { - *os << (x ? "true" : "false"); -} - -// Overload for wchar_t type. -// Prints a wchar_t as a symbol if it is printable or as its internal -// code otherwise and also as its decimal code (except for L'\0'). -// The L'\0' char is printed as "L'\\0'". The decimal code is printed -// as signed integer when wchar_t is implemented by the compiler -// as a signed type and is printed as an unsigned integer when wchar_t -// is implemented as an unsigned type. -GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os); - -// Overloads for C strings. -GTEST_API_ void PrintTo(const char* s, ::std::ostream* os); -inline void PrintTo(char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} - -// signed/unsigned char is often used for representing binary data, so -// we print pointers to it as void* to be safe. -inline void PrintTo(const signed char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -inline void PrintTo(signed char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -inline void PrintTo(const unsigned char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -inline void PrintTo(unsigned char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} - -// MSVC can be configured to define wchar_t as a typedef of unsigned -// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native -// type. When wchar_t is a typedef, defining an overload for const -// wchar_t* would cause unsigned short* be printed as a wide string, -// possibly causing invalid memory accesses. -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) -// Overloads for wide C strings -GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os); -inline void PrintTo(wchar_t* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -#endif - -// Overload for C arrays. Multi-dimensional arrays are printed -// properly. - -// Prints the given number of elements in an array, without printing -// the curly braces. -template -void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) { - UniversalPrint(a[0], os); - for (size_t i = 1; i != count; i++) { - *os << ", "; - UniversalPrint(a[i], os); - } -} - -// Overloads for ::string and ::std::string. -#if GTEST_HAS_GLOBAL_STRING -GTEST_API_ void PrintStringTo(const ::string&s, ::std::ostream* os); -inline void PrintTo(const ::string& s, ::std::ostream* os) { - PrintStringTo(s, os); -} -#endif // GTEST_HAS_GLOBAL_STRING - -GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os); -inline void PrintTo(const ::std::string& s, ::std::ostream* os) { - PrintStringTo(s, os); -} - -// Overloads for ::wstring and ::std::wstring. -#if GTEST_HAS_GLOBAL_WSTRING -GTEST_API_ void PrintWideStringTo(const ::wstring&s, ::std::ostream* os); -inline void PrintTo(const ::wstring& s, ::std::ostream* os) { - PrintWideStringTo(s, os); -} -#endif // GTEST_HAS_GLOBAL_WSTRING - -#if GTEST_HAS_STD_WSTRING -GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); -inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { - PrintWideStringTo(s, os); -} -#endif // GTEST_HAS_STD_WSTRING - -#if GTEST_HAS_TR1_TUPLE -// Overload for ::std::tr1::tuple. Needed for printing function arguments, -// which are packed as tuples. - -// Helper function for printing a tuple. T must be instantiated with -// a tuple type. -template -void PrintTupleTo(const T& t, ::std::ostream* os); - -// Overloaded PrintTo() for tuples of various arities. We support -// tuples of up-to 10 fields. The following implementation works -// regardless of whether tr1::tuple is implemented using the -// non-standard variadic template feature or not. - -inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo( - const ::std::tr1::tuple& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} -#endif // GTEST_HAS_TR1_TUPLE - -// Overload for std::pair. -template -void PrintTo(const ::std::pair& value, ::std::ostream* os) { - *os << '('; - // We cannot use UniversalPrint(value.first, os) here, as T1 may be - // a reference type. The same for printing value.second. - UniversalPrinter::Print(value.first, os); - *os << ", "; - UniversalPrinter::Print(value.second, os); - *os << ')'; -} - -// Implements printing a non-reference type T by letting the compiler -// pick the right overload of PrintTo() for T. -template -class UniversalPrinter { - public: - // MSVC warns about adding const to a function type, so we want to - // disable the warning. -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4180) // Temporarily disables warning 4180. -#endif // _MSC_VER - - // Note: we deliberately don't call this PrintTo(), as that name - // conflicts with ::testing::internal::PrintTo in the body of the - // function. - static void Print(const T& value, ::std::ostream* os) { - // By default, ::testing::internal::PrintTo() is used for printing - // the value. - // - // Thanks to Koenig look-up, if T is a class and has its own - // PrintTo() function defined in its namespace, that function will - // be visible here. Since it is more specific than the generic ones - // in ::testing::internal, it will be picked by the compiler in the - // following statement - exactly what we want. - PrintTo(value, os); - } - -#ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif // _MSC_VER -}; - -// UniversalPrintArray(begin, len, os) prints an array of 'len' -// elements, starting at address 'begin'. -template -void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { - if (len == 0) { - *os << "{}"; - } else { - *os << "{ "; - const size_t kThreshold = 18; - const size_t kChunkSize = 8; - // If the array has more than kThreshold elements, we'll have to - // omit some details by printing only the first and the last - // kChunkSize elements. - // TODO(wan@google.com): let the user control the threshold using a flag. - if (len <= kThreshold) { - PrintRawArrayTo(begin, len, os); - } else { - PrintRawArrayTo(begin, kChunkSize, os); - *os << ", ..., "; - PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os); - } - *os << " }"; - } -} -// This overload prints a (const) char array compactly. -GTEST_API_ void UniversalPrintArray(const char* begin, - size_t len, - ::std::ostream* os); - -// Implements printing an array type T[N]. -template -class UniversalPrinter { - public: - // Prints the given array, omitting some elements when there are too - // many. - static void Print(const T (&a)[N], ::std::ostream* os) { - UniversalPrintArray(a, N, os); - } -}; - -// Implements printing a reference type T&. -template -class UniversalPrinter { - public: - // MSVC warns about adding const to a function type, so we want to - // disable the warning. -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4180) // Temporarily disables warning 4180. -#endif // _MSC_VER - - static void Print(const T& value, ::std::ostream* os) { - // Prints the address of the value. We use reinterpret_cast here - // as static_cast doesn't compile when T is a function type. - *os << "@" << reinterpret_cast(&value) << " "; - - // Then prints the value itself. - UniversalPrint(value, os); - } - -#ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif // _MSC_VER -}; - -// Prints a value tersely: for a reference type, the referenced value -// (but not the address) is printed; for a (const) char pointer, the -// NUL-terminated string (but not the pointer) is printed. -template -void UniversalTersePrint(const T& value, ::std::ostream* os) { - UniversalPrint(value, os); -} -inline void UniversalTersePrint(const char* str, ::std::ostream* os) { - if (str == NULL) { - *os << "NULL"; - } else { - UniversalPrint(string(str), os); - } -} -inline void UniversalTersePrint(char* str, ::std::ostream* os) { - UniversalTersePrint(static_cast(str), os); -} - -// Prints a value using the type inferred by the compiler. The -// difference between this and UniversalTersePrint() is that for a -// (const) char pointer, this prints both the pointer and the -// NUL-terminated string. -template -void UniversalPrint(const T& value, ::std::ostream* os) { - UniversalPrinter::Print(value, os); -} - -#if GTEST_HAS_TR1_TUPLE -typedef ::std::vector Strings; - -// This helper template allows PrintTo() for tuples and -// UniversalTersePrintTupleFieldsToStrings() to be defined by -// induction on the number of tuple fields. The idea is that -// TuplePrefixPrinter::PrintPrefixTo(t, os) prints the first N -// fields in tuple t, and can be defined in terms of -// TuplePrefixPrinter. - -// The inductive case. -template -struct TuplePrefixPrinter { - // Prints the first N fields of a tuple. - template - static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { - TuplePrefixPrinter::PrintPrefixTo(t, os); - *os << ", "; - UniversalPrinter::type> - ::Print(::std::tr1::get(t), os); - } - - // Tersely prints the first N fields of a tuple to a string vector, - // one element for each field. - template - static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { - TuplePrefixPrinter::TersePrintPrefixToStrings(t, strings); - ::std::stringstream ss; - UniversalTersePrint(::std::tr1::get(t), &ss); - strings->push_back(ss.str()); - } -}; - -// Base cases. -template <> -struct TuplePrefixPrinter<0> { - template - static void PrintPrefixTo(const Tuple&, ::std::ostream*) {} - - template - static void TersePrintPrefixToStrings(const Tuple&, Strings*) {} -}; -// We have to specialize the entire TuplePrefixPrinter<> class -// template here, even though the definition of -// TersePrintPrefixToStrings() is the same as the generic version, as -// Embarcadero (formerly CodeGear, formerly Borland) C++ doesn't -// support specializing a method template of a class template. -template <> -struct TuplePrefixPrinter<1> { - template - static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { - UniversalPrinter::type>:: - Print(::std::tr1::get<0>(t), os); - } - - template - static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { - ::std::stringstream ss; - UniversalTersePrint(::std::tr1::get<0>(t), &ss); - strings->push_back(ss.str()); - } -}; - -// Helper function for printing a tuple. T must be instantiated with -// a tuple type. -template -void PrintTupleTo(const T& t, ::std::ostream* os) { - *os << "("; - TuplePrefixPrinter< ::std::tr1::tuple_size::value>:: - PrintPrefixTo(t, os); - *os << ")"; -} - -// Prints the fields of a tuple tersely to a string vector, one -// element for each field. See the comment before -// UniversalTersePrint() for how we define "tersely". -template -Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { - Strings result; - TuplePrefixPrinter< ::std::tr1::tuple_size::value>:: - TersePrintPrefixToStrings(value, &result); - return result; -} -#endif // GTEST_HAS_TR1_TUPLE - -} // namespace internal - -template -::std::string PrintToString(const T& value) { - ::std::stringstream ss; - internal::UniversalTersePrint(value, &ss); - return ss.str(); -} - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ - -#if GTEST_HAS_PARAM_TEST - -namespace testing { -namespace internal { - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Outputs a message explaining invalid registration of different -// fixture class for the same test case. This may happen when -// TEST_P macro is used to define two tests with the same name -// but in different namespaces. -GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, - const char* file, int line); - -template class ParamGeneratorInterface; -template class ParamGenerator; - -// Interface for iterating over elements provided by an implementation -// of ParamGeneratorInterface. -template -class ParamIteratorInterface { - public: - virtual ~ParamIteratorInterface() {} - // A pointer to the base generator instance. - // Used only for the purposes of iterator comparison - // to make sure that two iterators belong to the same generator. - virtual const ParamGeneratorInterface* BaseGenerator() const = 0; - // Advances iterator to point to the next element - // provided by the generator. The caller is responsible - // for not calling Advance() on an iterator equal to - // BaseGenerator()->End(). - virtual void Advance() = 0; - // Clones the iterator object. Used for implementing copy semantics - // of ParamIterator. - virtual ParamIteratorInterface* Clone() const = 0; - // Dereferences the current iterator and provides (read-only) access - // to the pointed value. It is the caller's responsibility not to call - // Current() on an iterator equal to BaseGenerator()->End(). - // Used for implementing ParamGenerator::operator*(). - virtual const T* Current() const = 0; - // Determines whether the given iterator and other point to the same - // element in the sequence generated by the generator. - // Used for implementing ParamGenerator::operator==(). - virtual bool Equals(const ParamIteratorInterface& other) const = 0; -}; - -// Class iterating over elements provided by an implementation of -// ParamGeneratorInterface. It wraps ParamIteratorInterface -// and implements the const forward iterator concept. -template -class ParamIterator { - public: - typedef T value_type; - typedef const T& reference; - typedef ptrdiff_t difference_type; - - // ParamIterator assumes ownership of the impl_ pointer. - ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} - ParamIterator& operator=(const ParamIterator& other) { - if (this != &other) - impl_.reset(other.impl_->Clone()); - return *this; - } - - const T& operator*() const { return *impl_->Current(); } - const T* operator->() const { return impl_->Current(); } - // Prefix version of operator++. - ParamIterator& operator++() { - impl_->Advance(); - return *this; - } - // Postfix version of operator++. - ParamIterator operator++(int /*unused*/) { - ParamIteratorInterface* clone = impl_->Clone(); - impl_->Advance(); - return ParamIterator(clone); - } - bool operator==(const ParamIterator& other) const { - return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_); - } - bool operator!=(const ParamIterator& other) const { - return !(*this == other); - } - - private: - friend class ParamGenerator; - explicit ParamIterator(ParamIteratorInterface* impl) : impl_(impl) {} - scoped_ptr > impl_; -}; - -// ParamGeneratorInterface is the binary interface to access generators -// defined in other translation units. -template -class ParamGeneratorInterface { - public: - typedef T ParamType; - - virtual ~ParamGeneratorInterface() {} - - // Generator interface definition - virtual ParamIteratorInterface* Begin() const = 0; - virtual ParamIteratorInterface* End() const = 0; -}; - -// Wraps ParamGeneratorInterface and provides general generator syntax -// compatible with the STL Container concept. -// This class implements copy initialization semantics and the contained -// ParamGeneratorInterface instance is shared among all copies -// of the original object. This is possible because that instance is immutable. -template -class ParamGenerator { - public: - typedef ParamIterator iterator; - - explicit ParamGenerator(ParamGeneratorInterface* impl) : impl_(impl) {} - ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {} - - ParamGenerator& operator=(const ParamGenerator& other) { - impl_ = other.impl_; - return *this; - } - - iterator begin() const { return iterator(impl_->Begin()); } - iterator end() const { return iterator(impl_->End()); } - - private: - linked_ptr > impl_; -}; - -// Generates values from a range of two comparable values. Can be used to -// generate sequences of user-defined types that implement operator+() and -// operator<(). -// This class is used in the Range() function. -template -class RangeGenerator : public ParamGeneratorInterface { - public: - RangeGenerator(T begin, T end, IncrementT step) - : begin_(begin), end_(end), - step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} - virtual ~RangeGenerator() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, begin_, 0, step_); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, end_, end_index_, step_); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, T value, int index, - IncrementT step) - : base_(base), value_(value), index_(index), step_(step) {} - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - virtual void Advance() { - value_ = value_ + step_; - index_++; - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const T* Current() const { return &value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const int other_index = - CheckedDowncastToActualType(&other)->index_; - return index_ == other_index; - } - - private: - Iterator(const Iterator& other) - : ParamIteratorInterface(), - base_(other.base_), value_(other.value_), index_(other.index_), - step_(other.step_) {} - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - T value_; - int index_; - const IncrementT step_; - }; // class RangeGenerator::Iterator - - static int CalculateEndIndex(const T& begin, - const T& end, - const IncrementT& step) { - int end_index = 0; - for (T i = begin; i < end; i = i + step) - end_index++; - return end_index; - } - - // No implementation - assignment is unsupported. - void operator=(const RangeGenerator& other); - - const T begin_; - const T end_; - const IncrementT step_; - // The index for the end() iterator. All the elements in the generated - // sequence are indexed (0-based) to aid iterator comparison. - const int end_index_; -}; // class RangeGenerator - - -// Generates values from a pair of STL-style iterators. Used in the -// ValuesIn() function. The elements are copied from the source range -// since the source can be located on the stack, and the generator -// is likely to persist beyond that stack frame. -template -class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { - public: - template - ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) - : container_(begin, end) {} - virtual ~ValuesInIteratorRangeGenerator() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, container_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, container_.end()); - } - - private: - typedef typename ::std::vector ContainerType; - - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - typename ContainerType::const_iterator iterator) - : base_(base), iterator_(iterator) {} - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - virtual void Advance() { - ++iterator_; - value_.reset(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - // We need to use cached value referenced by iterator_ because *iterator_ - // can return a temporary object (and of type other then T), so just - // having "return &*iterator_;" doesn't work. - // value_ is updated here and not in Advance() because Advance() - // can advance iterator_ beyond the end of the range, and we cannot - // detect that fact. The client code, on the other hand, is - // responsible for not calling Current() on an out-of-range iterator. - virtual const T* Current() const { - if (value_.get() == NULL) - value_.reset(new T(*iterator_)); - return value_.get(); - } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - return iterator_ == - CheckedDowncastToActualType(&other)->iterator_; - } - - private: - Iterator(const Iterator& other) - // The explicit constructor call suppresses a false warning - // emitted by gcc when supplied with the -Wextra option. - : ParamIteratorInterface(), - base_(other.base_), - iterator_(other.iterator_) {} - - const ParamGeneratorInterface* const base_; - typename ContainerType::const_iterator iterator_; - // A cached value of *iterator_. We keep it here to allow access by - // pointer in the wrapping iterator's operator->(). - // value_ needs to be mutable to be accessed in Current(). - // Use of scoped_ptr helps manage cached value's lifetime, - // which is bound by the lifespan of the iterator itself. - mutable scoped_ptr value_; - }; // class ValuesInIteratorRangeGenerator::Iterator - - // No implementation - assignment is unsupported. - void operator=(const ValuesInIteratorRangeGenerator& other); - - const ContainerType container_; -}; // class ValuesInIteratorRangeGenerator - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Stores a parameter value and later creates tests parameterized with that -// value. -template -class ParameterizedTestFactory : public TestFactoryBase { - public: - typedef typename TestClass::ParamType ParamType; - explicit ParameterizedTestFactory(ParamType parameter) : - parameter_(parameter) {} - virtual Test* CreateTest() { - TestClass::SetParam(¶meter_); - return new TestClass(); - } - - private: - const ParamType parameter_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory); -}; - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// TestMetaFactoryBase is a base class for meta-factories that create -// test factories for passing into MakeAndRegisterTestInfo function. -template -class TestMetaFactoryBase { - public: - virtual ~TestMetaFactoryBase() {} - - virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0; -}; - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// TestMetaFactory creates test factories for passing into -// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives -// ownership of test factory pointer, same factory object cannot be passed -// into that method twice. But ParameterizedTestCaseInfo is going to call -// it for each Test/Parameter value combination. Thus it needs meta factory -// creator class. -template -class TestMetaFactory - : public TestMetaFactoryBase { - public: - typedef typename TestCase::ParamType ParamType; - - TestMetaFactory() {} - - virtual TestFactoryBase* CreateTestFactory(ParamType parameter) { - return new ParameterizedTestFactory(parameter); - } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory); -}; - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// ParameterizedTestCaseInfoBase is a generic interface -// to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase -// accumulates test information provided by TEST_P macro invocations -// and generators provided by INSTANTIATE_TEST_CASE_P macro invocations -// and uses that information to register all resulting test instances -// in RegisterTests method. The ParameterizeTestCaseRegistry class holds -// a collection of pointers to the ParameterizedTestCaseInfo objects -// and calls RegisterTests() on each of them when asked. -class ParameterizedTestCaseInfoBase { - public: - virtual ~ParameterizedTestCaseInfoBase() {} - - // Base part of test case name for display purposes. - virtual const string& GetTestCaseName() const = 0; - // Test case id to verify identity. - virtual TypeId GetTestCaseTypeId() const = 0; - // UnitTest class invokes this method to register tests in this - // test case right before running them in RUN_ALL_TESTS macro. - // This method should not be called more then once on any single - // instance of a ParameterizedTestCaseInfoBase derived class. - virtual void RegisterTests() = 0; - - protected: - ParameterizedTestCaseInfoBase() {} - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase); -}; - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// ParameterizedTestCaseInfo accumulates tests obtained from TEST_P -// macro invocations for a particular test case and generators -// obtained from INSTANTIATE_TEST_CASE_P macro invocations for that -// test case. It registers tests with all values generated by all -// generators when asked. -template -class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { - public: - // ParamType and GeneratorCreationFunc are private types but are required - // for declarations of public methods AddTestPattern() and - // AddTestCaseInstantiation(). - typedef typename TestCase::ParamType ParamType; - // A function that returns an instance of appropriate generator type. - typedef ParamGenerator(GeneratorCreationFunc)(); - - explicit ParameterizedTestCaseInfo(const char* name) - : test_case_name_(name) {} - - // Test case base name for display purposes. - virtual const string& GetTestCaseName() const { return test_case_name_; } - // Test case id to verify identity. - virtual TypeId GetTestCaseTypeId() const { return GetTypeId(); } - // TEST_P macro uses AddTestPattern() to record information - // about a single test in a LocalTestInfo structure. - // test_case_name is the base name of the test case (without invocation - // prefix). test_base_name is the name of an individual test without - // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is - // test case base name and DoBar is test base name. - void AddTestPattern(const char* test_case_name, - const char* test_base_name, - TestMetaFactoryBase* meta_factory) { - tests_.push_back(linked_ptr(new TestInfo(test_case_name, - test_base_name, - meta_factory))); - } - // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information - // about a generator. - int AddTestCaseInstantiation(const string& instantiation_name, - GeneratorCreationFunc* func, - const char* /* file */, - int /* line */) { - instantiations_.push_back(::std::make_pair(instantiation_name, func)); - return 0; // Return value used only to run this method in namespace scope. - } - // UnitTest class invokes this method to register tests in this test case - // test cases right before running tests in RUN_ALL_TESTS macro. - // This method should not be called more then once on any single - // instance of a ParameterizedTestCaseInfoBase derived class. - // UnitTest has a guard to prevent from calling this method more then once. - virtual void RegisterTests() { - for (typename TestInfoContainer::iterator test_it = tests_.begin(); - test_it != tests_.end(); ++test_it) { - linked_ptr test_info = *test_it; - for (typename InstantiationContainer::iterator gen_it = - instantiations_.begin(); gen_it != instantiations_.end(); - ++gen_it) { - const string& instantiation_name = gen_it->first; - ParamGenerator generator((*gen_it->second)()); - - Message test_case_name_stream; - if ( !instantiation_name.empty() ) - test_case_name_stream << instantiation_name << "/"; - test_case_name_stream << test_info->test_case_base_name; - - int i = 0; - for (typename ParamGenerator::iterator param_it = - generator.begin(); - param_it != generator.end(); ++param_it, ++i) { - Message test_name_stream; - test_name_stream << test_info->test_base_name << "/" << i; - MakeAndRegisterTestInfo( - test_case_name_stream.GetString().c_str(), - test_name_stream.GetString().c_str(), - NULL, // No type parameter. - PrintToString(*param_it).c_str(), - GetTestCaseTypeId(), - TestCase::SetUpTestCase, - TestCase::TearDownTestCase, - test_info->test_meta_factory->CreateTestFactory(*param_it)); - } // for param_it - } // for gen_it - } // for test_it - } // RegisterTests - - private: - // LocalTestInfo structure keeps information about a single test registered - // with TEST_P macro. - struct TestInfo { - TestInfo(const char* a_test_case_base_name, - const char* a_test_base_name, - TestMetaFactoryBase* a_test_meta_factory) : - test_case_base_name(a_test_case_base_name), - test_base_name(a_test_base_name), - test_meta_factory(a_test_meta_factory) {} - - const string test_case_base_name; - const string test_base_name; - const scoped_ptr > test_meta_factory; - }; - typedef ::std::vector > TestInfoContainer; - // Keeps pairs of - // received from INSTANTIATE_TEST_CASE_P macros. - typedef ::std::vector > - InstantiationContainer; - - const string test_case_name_; - TestInfoContainer tests_; - InstantiationContainer instantiations_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo); -}; // class ParameterizedTestCaseInfo - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase -// classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P -// macros use it to locate their corresponding ParameterizedTestCaseInfo -// descriptors. -class ParameterizedTestCaseRegistry { - public: - ParameterizedTestCaseRegistry() {} - ~ParameterizedTestCaseRegistry() { - for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); - it != test_case_infos_.end(); ++it) { - delete *it; - } - } - - // Looks up or creates and returns a structure containing information about - // tests and instantiations of a particular test case. - template - ParameterizedTestCaseInfo* GetTestCasePatternHolder( - const char* test_case_name, - const char* file, - int line) { - ParameterizedTestCaseInfo* typed_test_info = NULL; - for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); - it != test_case_infos_.end(); ++it) { - if ((*it)->GetTestCaseName() == test_case_name) { - if ((*it)->GetTestCaseTypeId() != GetTypeId()) { - // Complain about incorrect usage of Google Test facilities - // and terminate the program since we cannot guaranty correct - // test case setup and tear-down in this case. - ReportInvalidTestCaseType(test_case_name, file, line); - posix::Abort(); - } else { - // At this point we are sure that the object we found is of the same - // type we are looking for, so we downcast it to that type - // without further checks. - typed_test_info = CheckedDowncastToActualType< - ParameterizedTestCaseInfo >(*it); - } - break; - } - } - if (typed_test_info == NULL) { - typed_test_info = new ParameterizedTestCaseInfo(test_case_name); - test_case_infos_.push_back(typed_test_info); - } - return typed_test_info; - } - void RegisterTests() { - for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); - it != test_case_infos_.end(); ++it) { - (*it)->RegisterTests(); - } - } - - private: - typedef ::std::vector TestCaseInfoContainer; - - TestCaseInfoContainer test_case_infos_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry); -}; - -} // namespace internal -} // namespace testing - -#endif // GTEST_HAS_PARAM_TEST - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ -// This file was GENERATED by command: -// pump.py gtest-param-util-generated.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2008 Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: vladl@google.com (Vlad Losev) - -// Type and function utilities for implementing parameterized tests. -// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! -// -// Currently Google Test supports at most 50 arguments in Values, -// and at most 10 arguments in Combine. Please contact -// googletestframework@googlegroups.com if you need more. -// Please note that the number of arguments to Combine is limited -// by the maximum arity of the implementation of tr1::tuple which is -// currently set at 10. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ - -// scripts/fuse_gtest.py depends on gtest's own header being #included -// *unconditionally*. Therefore these #includes cannot be moved -// inside #if GTEST_HAS_PARAM_TEST. - -#if GTEST_HAS_PARAM_TEST - -namespace testing { - -// Forward declarations of ValuesIn(), which is implemented in -// include/gtest/gtest-param-test.h. -template -internal::ParamGenerator< - typename ::testing::internal::IteratorTraits::value_type> -ValuesIn(ForwardIterator begin, ForwardIterator end); - -template -internal::ParamGenerator ValuesIn(const T (&array)[N]); - -template -internal::ParamGenerator ValuesIn( - const Container& container); - -namespace internal { - -// Used in the Values() function to provide polymorphic capabilities. -template -class ValueArray1 { - public: - explicit ValueArray1(T1 v1) : v1_(v1) {} - - template - operator ParamGenerator() const { return ValuesIn(&v1_, &v1_ + 1); } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray1& other); - - const T1 v1_; -}; - -template -class ValueArray2 { - public: - ValueArray2(T1 v1, T2 v2) : v1_(v1), v2_(v2) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray2& other); - - const T1 v1_; - const T2 v2_; -}; - -template -class ValueArray3 { - public: - ValueArray3(T1 v1, T2 v2, T3 v3) : v1_(v1), v2_(v2), v3_(v3) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray3& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; -}; - -template -class ValueArray4 { - public: - ValueArray4(T1 v1, T2 v2, T3 v3, T4 v4) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray4& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; -}; - -template -class ValueArray5 { - public: - ValueArray5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray5& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; -}; - -template -class ValueArray6 { - public: - ValueArray6(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray6& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; -}; - -template -class ValueArray7 { - public: - ValueArray7(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray7& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; -}; - -template -class ValueArray8 { - public: - ValueArray8(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray8& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; -}; - -template -class ValueArray9 { - public: - ValueArray9(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, - T9 v9) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray9& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; -}; - -template -class ValueArray10 { - public: - ValueArray10(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray10& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; -}; - -template -class ValueArray11 { - public: - ValueArray11(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray11& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; -}; - -template -class ValueArray12 { - public: - ValueArray12(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray12& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; -}; - -template -class ValueArray13 { - public: - ValueArray13(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray13& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; -}; - -template -class ValueArray14 { - public: - ValueArray14(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray14& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; -}; - -template -class ValueArray15 { - public: - ValueArray15(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray15& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; -}; - -template -class ValueArray16 { - public: - ValueArray16(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray16& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; -}; - -template -class ValueArray17 { - public: - ValueArray17(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, - T17 v17) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray17& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; -}; - -template -class ValueArray18 { - public: - ValueArray18(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray18& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; -}; - -template -class ValueArray19 { - public: - ValueArray19(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), - v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray19& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; -}; - -template -class ValueArray20 { - public: - ValueArray20(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), - v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), - v19_(v19), v20_(v20) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray20& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; -}; - -template -class ValueArray21 { - public: - ValueArray21(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), - v18_(v18), v19_(v19), v20_(v20), v21_(v21) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray21& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; -}; - -template -class ValueArray22 { - public: - ValueArray22(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray22& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; -}; - -template -class ValueArray23 { - public: - ValueArray23(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, - v23_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray23& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; -}; - -template -class ValueArray24 { - public: - ValueArray24(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), - v22_(v22), v23_(v23), v24_(v24) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray24& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; -}; - -template -class ValueArray25 { - public: - ValueArray25(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, - T25 v25) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray25& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; -}; - -template -class ValueArray26 { - public: - ValueArray26(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray26& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; -}; - -template -class ValueArray27 { - public: - ValueArray27(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), - v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), - v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), - v26_(v26), v27_(v27) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray27& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; -}; - -template -class ValueArray28 { - public: - ValueArray28(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), - v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), - v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), - v25_(v25), v26_(v26), v27_(v27), v28_(v28) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray28& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; -}; - -template -class ValueArray29 { - public: - ValueArray29(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), - v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), - v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray29& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; -}; - -template -class ValueArray30 { - public: - ValueArray30(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray30& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; -}; - -template -class ValueArray31 { - public: - ValueArray31(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray31& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; -}; - -template -class ValueArray32 { - public: - ValueArray32(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), - v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), - v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray32& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; -}; - -template -class ValueArray33 { - public: - ValueArray33(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, - T33 v33) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray33& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; -}; - -template -class ValueArray34 { - public: - ValueArray34(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray34& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; -}; - -template -class ValueArray35 { - public: - ValueArray35(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), - v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), - v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), - v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), - v32_(v32), v33_(v33), v34_(v34), v35_(v35) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, - v35_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray35& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; -}; - -template -class ValueArray36 { - public: - ValueArray36(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), - v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), - v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), - v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), - v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray36& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; -}; - -template -class ValueArray37 { - public: - ValueArray37(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), - v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), - v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), - v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), - v36_(v36), v37_(v37) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray37& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; -}; - -template -class ValueArray38 { - public: - ValueArray38(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), - v35_(v35), v36_(v36), v37_(v37), v38_(v38) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray38& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; -}; - -template -class ValueArray39 { - public: - ValueArray39(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), - v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray39& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; -}; - -template -class ValueArray40 { - public: - ValueArray40(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), - v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), - v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), - v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), - v40_(v40) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray40& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; -}; - -template -class ValueArray41 { - public: - ValueArray41(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, - T41 v41) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), - v39_(v39), v40_(v40), v41_(v41) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray41& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; -}; - -template -class ValueArray42 { - public: - ValueArray42(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), - v39_(v39), v40_(v40), v41_(v41), v42_(v42) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray42& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; -}; - -template -class ValueArray43 { - public: - ValueArray43(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), - v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), - v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), - v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), - v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), - v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray43& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; -}; - -template -class ValueArray44 { - public: - ValueArray44(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), - v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), - v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), - v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), - v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), - v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), - v43_(v43), v44_(v44) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray44& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; -}; - -template -class ValueArray45 { - public: - ValueArray45(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), - v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), - v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), - v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), - v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), - v42_(v42), v43_(v43), v44_(v44), v45_(v45) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray45& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; - const T45 v45_; -}; - -template -class ValueArray46 { - public: - ValueArray46(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), - v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), - v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray46& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; - const T45 v45_; - const T46 v46_; -}; - -template -class ValueArray47 { - public: - ValueArray47(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), - v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), - v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), - v47_(v47) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, - v47_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray47& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; - const T45 v45_; - const T46 v46_; - const T47 v47_; -}; - -template -class ValueArray48 { - public: - ValueArray48(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), - v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), - v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), - v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), - v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), - v46_(v46), v47_(v47), v48_(v48) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, v47_, - v48_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray48& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; - const T45 v45_; - const T46 v46_; - const T47 v47_; - const T48 v48_; -}; - -template -class ValueArray49 { - public: - ValueArray49(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, - T49 v49) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), - v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), - v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, v47_, - v48_, v49_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray49& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; - const T45 v45_; - const T46 v46_; - const T47 v47_; - const T48 v48_; - const T49 v49_; -}; - -template -class ValueArray50 { - public: - ValueArray50(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49, - T50 v50) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), - v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), - v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49), v50_(v50) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, v47_, - v48_, v49_, v50_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray50& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; - const T45 v45_; - const T46 v46_; - const T47 v47_; - const T48 v48_; - const T49 v49_; - const T50 v50_; -}; - -# if GTEST_HAS_COMBINE -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Generates values from the Cartesian product of values produced -// by the argument generators. -// -template -class CartesianProductGenerator2 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator2(const ParamGenerator& g1, - const ParamGenerator& g2) - : g1_(g1), g2_(g2) {} - virtual ~CartesianProductGenerator2() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current2_; - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - ParamType current_value_; - }; // class CartesianProductGenerator2::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator2& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; -}; // class CartesianProductGenerator2 - - -template -class CartesianProductGenerator3 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator3(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3) - : g1_(g1), g2_(g2), g3_(g3) {} - virtual ~CartesianProductGenerator3() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current3_; - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - ParamType current_value_; - }; // class CartesianProductGenerator3::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator3& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; -}; // class CartesianProductGenerator3 - - -template -class CartesianProductGenerator4 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator4(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} - virtual ~CartesianProductGenerator4() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current4_; - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - ParamType current_value_; - }; // class CartesianProductGenerator4::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator4& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; -}; // class CartesianProductGenerator4 - - -template -class CartesianProductGenerator5 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator5(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} - virtual ~CartesianProductGenerator5() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current5_; - if (current5_ == end5_) { - current5_ = begin5_; - ++current4_; - } - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - const typename ParamGenerator::iterator begin5_; - const typename ParamGenerator::iterator end5_; - typename ParamGenerator::iterator current5_; - ParamType current_value_; - }; // class CartesianProductGenerator5::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator5& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; - const ParamGenerator g5_; -}; // class CartesianProductGenerator5 - - -template -class CartesianProductGenerator6 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator6(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} - virtual ~CartesianProductGenerator6() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current6_; - if (current6_ == end6_) { - current6_ = begin6_; - ++current5_; - } - if (current5_ == end5_) { - current5_ = begin5_; - ++current4_; - } - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - const typename ParamGenerator::iterator begin5_; - const typename ParamGenerator::iterator end5_; - typename ParamGenerator::iterator current5_; - const typename ParamGenerator::iterator begin6_; - const typename ParamGenerator::iterator end6_; - typename ParamGenerator::iterator current6_; - ParamType current_value_; - }; // class CartesianProductGenerator6::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator6& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; - const ParamGenerator g5_; - const ParamGenerator g6_; -}; // class CartesianProductGenerator6 - - -template -class CartesianProductGenerator7 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator7(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6, const ParamGenerator& g7) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} - virtual ~CartesianProductGenerator7() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, - g7_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6, - const ParamGenerator& g7, - const typename ParamGenerator::iterator& current7) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6), - begin7_(g7.begin()), end7_(g7.end()), current7_(current7) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current7_; - if (current7_ == end7_) { - current7_ = begin7_; - ++current6_; - } - if (current6_ == end6_) { - current6_ = begin6_; - ++current5_; - } - if (current5_ == end5_) { - current5_ = begin5_; - ++current4_; - } - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_ && - current7_ == typed_other->current7_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_), - begin7_(other.begin7_), - end7_(other.end7_), - current7_(other.current7_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_, *current7_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_ || - current7_ == end7_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - const typename ParamGenerator::iterator begin5_; - const typename ParamGenerator::iterator end5_; - typename ParamGenerator::iterator current5_; - const typename ParamGenerator::iterator begin6_; - const typename ParamGenerator::iterator end6_; - typename ParamGenerator::iterator current6_; - const typename ParamGenerator::iterator begin7_; - const typename ParamGenerator::iterator end7_; - typename ParamGenerator::iterator current7_; - ParamType current_value_; - }; // class CartesianProductGenerator7::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator7& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; - const ParamGenerator g5_; - const ParamGenerator g6_; - const ParamGenerator g7_; -}; // class CartesianProductGenerator7 - - -template -class CartesianProductGenerator8 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator8(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6, const ParamGenerator& g7, - const ParamGenerator& g8) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), - g8_(g8) {} - virtual ~CartesianProductGenerator8() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, - g7_.begin(), g8_, g8_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, - g8_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6, - const ParamGenerator& g7, - const typename ParamGenerator::iterator& current7, - const ParamGenerator& g8, - const typename ParamGenerator::iterator& current8) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6), - begin7_(g7.begin()), end7_(g7.end()), current7_(current7), - begin8_(g8.begin()), end8_(g8.end()), current8_(current8) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current8_; - if (current8_ == end8_) { - current8_ = begin8_; - ++current7_; - } - if (current7_ == end7_) { - current7_ = begin7_; - ++current6_; - } - if (current6_ == end6_) { - current6_ = begin6_; - ++current5_; - } - if (current5_ == end5_) { - current5_ = begin5_; - ++current4_; - } - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_ && - current7_ == typed_other->current7_ && - current8_ == typed_other->current8_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_), - begin7_(other.begin7_), - end7_(other.end7_), - current7_(other.current7_), - begin8_(other.begin8_), - end8_(other.end8_), - current8_(other.current8_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_, *current7_, *current8_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_ || - current7_ == end7_ || - current8_ == end8_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - const typename ParamGenerator::iterator begin5_; - const typename ParamGenerator::iterator end5_; - typename ParamGenerator::iterator current5_; - const typename ParamGenerator::iterator begin6_; - const typename ParamGenerator::iterator end6_; - typename ParamGenerator::iterator current6_; - const typename ParamGenerator::iterator begin7_; - const typename ParamGenerator::iterator end7_; - typename ParamGenerator::iterator current7_; - const typename ParamGenerator::iterator begin8_; - const typename ParamGenerator::iterator end8_; - typename ParamGenerator::iterator current8_; - ParamType current_value_; - }; // class CartesianProductGenerator8::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator8& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; - const ParamGenerator g5_; - const ParamGenerator g6_; - const ParamGenerator g7_; - const ParamGenerator g8_; -}; // class CartesianProductGenerator8 - - -template -class CartesianProductGenerator9 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator9(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6, const ParamGenerator& g7, - const ParamGenerator& g8, const ParamGenerator& g9) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), - g9_(g9) {} - virtual ~CartesianProductGenerator9() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, - g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, - g8_.end(), g9_, g9_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6, - const ParamGenerator& g7, - const typename ParamGenerator::iterator& current7, - const ParamGenerator& g8, - const typename ParamGenerator::iterator& current8, - const ParamGenerator& g9, - const typename ParamGenerator::iterator& current9) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6), - begin7_(g7.begin()), end7_(g7.end()), current7_(current7), - begin8_(g8.begin()), end8_(g8.end()), current8_(current8), - begin9_(g9.begin()), end9_(g9.end()), current9_(current9) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current9_; - if (current9_ == end9_) { - current9_ = begin9_; - ++current8_; - } - if (current8_ == end8_) { - current8_ = begin8_; - ++current7_; - } - if (current7_ == end7_) { - current7_ = begin7_; - ++current6_; - } - if (current6_ == end6_) { - current6_ = begin6_; - ++current5_; - } - if (current5_ == end5_) { - current5_ = begin5_; - ++current4_; - } - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_ && - current7_ == typed_other->current7_ && - current8_ == typed_other->current8_ && - current9_ == typed_other->current9_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_), - begin7_(other.begin7_), - end7_(other.end7_), - current7_(other.current7_), - begin8_(other.begin8_), - end8_(other.end8_), - current8_(other.current8_), - begin9_(other.begin9_), - end9_(other.end9_), - current9_(other.current9_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_, *current7_, *current8_, - *current9_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_ || - current7_ == end7_ || - current8_ == end8_ || - current9_ == end9_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - const typename ParamGenerator::iterator begin5_; - const typename ParamGenerator::iterator end5_; - typename ParamGenerator::iterator current5_; - const typename ParamGenerator::iterator begin6_; - const typename ParamGenerator::iterator end6_; - typename ParamGenerator::iterator current6_; - const typename ParamGenerator::iterator begin7_; - const typename ParamGenerator::iterator end7_; - typename ParamGenerator::iterator current7_; - const typename ParamGenerator::iterator begin8_; - const typename ParamGenerator::iterator end8_; - typename ParamGenerator::iterator current8_; - const typename ParamGenerator::iterator begin9_; - const typename ParamGenerator::iterator end9_; - typename ParamGenerator::iterator current9_; - ParamType current_value_; - }; // class CartesianProductGenerator9::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator9& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; - const ParamGenerator g5_; - const ParamGenerator g6_; - const ParamGenerator g7_; - const ParamGenerator g8_; - const ParamGenerator g9_; -}; // class CartesianProductGenerator9 - - -template -class CartesianProductGenerator10 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator10(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6, const ParamGenerator& g7, - const ParamGenerator& g8, const ParamGenerator& g9, - const ParamGenerator& g10) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), - g9_(g9), g10_(g10) {} - virtual ~CartesianProductGenerator10() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, - g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin(), g10_, g10_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, - g8_.end(), g9_, g9_.end(), g10_, g10_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6, - const ParamGenerator& g7, - const typename ParamGenerator::iterator& current7, - const ParamGenerator& g8, - const typename ParamGenerator::iterator& current8, - const ParamGenerator& g9, - const typename ParamGenerator::iterator& current9, - const ParamGenerator& g10, - const typename ParamGenerator::iterator& current10) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6), - begin7_(g7.begin()), end7_(g7.end()), current7_(current7), - begin8_(g8.begin()), end8_(g8.end()), current8_(current8), - begin9_(g9.begin()), end9_(g9.end()), current9_(current9), - begin10_(g10.begin()), end10_(g10.end()), current10_(current10) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current10_; - if (current10_ == end10_) { - current10_ = begin10_; - ++current9_; - } - if (current9_ == end9_) { - current9_ = begin9_; - ++current8_; - } - if (current8_ == end8_) { - current8_ = begin8_; - ++current7_; - } - if (current7_ == end7_) { - current7_ = begin7_; - ++current6_; - } - if (current6_ == end6_) { - current6_ = begin6_; - ++current5_; - } - if (current5_ == end5_) { - current5_ = begin5_; - ++current4_; - } - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_ && - current7_ == typed_other->current7_ && - current8_ == typed_other->current8_ && - current9_ == typed_other->current9_ && - current10_ == typed_other->current10_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_), - begin7_(other.begin7_), - end7_(other.end7_), - current7_(other.current7_), - begin8_(other.begin8_), - end8_(other.end8_), - current8_(other.current8_), - begin9_(other.begin9_), - end9_(other.end9_), - current9_(other.current9_), - begin10_(other.begin10_), - end10_(other.end10_), - current10_(other.current10_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_, *current7_, *current8_, - *current9_, *current10_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_ || - current7_ == end7_ || - current8_ == end8_ || - current9_ == end9_ || - current10_ == end10_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - const typename ParamGenerator::iterator begin5_; - const typename ParamGenerator::iterator end5_; - typename ParamGenerator::iterator current5_; - const typename ParamGenerator::iterator begin6_; - const typename ParamGenerator::iterator end6_; - typename ParamGenerator::iterator current6_; - const typename ParamGenerator::iterator begin7_; - const typename ParamGenerator::iterator end7_; - typename ParamGenerator::iterator current7_; - const typename ParamGenerator::iterator begin8_; - const typename ParamGenerator::iterator end8_; - typename ParamGenerator::iterator current8_; - const typename ParamGenerator::iterator begin9_; - const typename ParamGenerator::iterator end9_; - typename ParamGenerator::iterator current9_; - const typename ParamGenerator::iterator begin10_; - const typename ParamGenerator::iterator end10_; - typename ParamGenerator::iterator current10_; - ParamType current_value_; - }; // class CartesianProductGenerator10::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator10& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; - const ParamGenerator g5_; - const ParamGenerator g6_; - const ParamGenerator g7_; - const ParamGenerator g8_; - const ParamGenerator g9_; - const ParamGenerator g10_; -}; // class CartesianProductGenerator10 - - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Helper classes providing Combine() with polymorphic features. They allow -// casting CartesianProductGeneratorN to ParamGenerator if T is -// convertible to U. -// -template -class CartesianProductHolder2 { - public: -CartesianProductHolder2(const Generator1& g1, const Generator2& g2) - : g1_(g1), g2_(g2) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator2( - static_cast >(g1_), - static_cast >(g2_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder2& other); - - const Generator1 g1_; - const Generator2 g2_; -}; // class CartesianProductHolder2 - -template -class CartesianProductHolder3 { - public: -CartesianProductHolder3(const Generator1& g1, const Generator2& g2, - const Generator3& g3) - : g1_(g1), g2_(g2), g3_(g3) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator3( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder3& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; -}; // class CartesianProductHolder3 - -template -class CartesianProductHolder4 { - public: -CartesianProductHolder4(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator4( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder4& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; -}; // class CartesianProductHolder4 - -template -class CartesianProductHolder5 { - public: -CartesianProductHolder5(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator5( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder5& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; - const Generator5 g5_; -}; // class CartesianProductHolder5 - -template -class CartesianProductHolder6 { - public: -CartesianProductHolder6(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator6( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder6& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; - const Generator5 g5_; - const Generator6 g6_; -}; // class CartesianProductHolder6 - -template -class CartesianProductHolder7 { - public: -CartesianProductHolder7(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6, const Generator7& g7) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator7( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_), - static_cast >(g7_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder7& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; - const Generator5 g5_; - const Generator6 g6_; - const Generator7 g7_; -}; // class CartesianProductHolder7 - -template -class CartesianProductHolder8 { - public: -CartesianProductHolder8(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6, const Generator7& g7, const Generator8& g8) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), - g8_(g8) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator8( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_), - static_cast >(g7_), - static_cast >(g8_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder8& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; - const Generator5 g5_; - const Generator6 g6_; - const Generator7 g7_; - const Generator8 g8_; -}; // class CartesianProductHolder8 - -template -class CartesianProductHolder9 { - public: -CartesianProductHolder9(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6, const Generator7& g7, const Generator8& g8, - const Generator9& g9) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), - g9_(g9) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator9( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_), - static_cast >(g7_), - static_cast >(g8_), - static_cast >(g9_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder9& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; - const Generator5 g5_; - const Generator6 g6_; - const Generator7 g7_; - const Generator8 g8_; - const Generator9 g9_; -}; // class CartesianProductHolder9 - -template -class CartesianProductHolder10 { - public: -CartesianProductHolder10(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6, const Generator7& g7, const Generator8& g8, - const Generator9& g9, const Generator10& g10) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), - g9_(g9), g10_(g10) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator10( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_), - static_cast >(g7_), - static_cast >(g8_), - static_cast >(g9_), - static_cast >(g10_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder10& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; - const Generator5 g5_; - const Generator6 g6_; - const Generator7 g7_; - const Generator8 g8_; - const Generator9 g9_; - const Generator10 g10_; -}; // class CartesianProductHolder10 - -# endif // GTEST_HAS_COMBINE - -} // namespace internal -} // namespace testing - -#endif // GTEST_HAS_PARAM_TEST - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ - -#if GTEST_HAS_PARAM_TEST - -namespace testing { - -// Functions producing parameter generators. -// -// Google Test uses these generators to produce parameters for value- -// parameterized tests. When a parameterized test case is instantiated -// with a particular generator, Google Test creates and runs tests -// for each element in the sequence produced by the generator. -// -// In the following sample, tests from test case FooTest are instantiated -// each three times with parameter values 3, 5, and 8: -// -// class FooTest : public TestWithParam { ... }; -// -// TEST_P(FooTest, TestThis) { -// } -// TEST_P(FooTest, TestThat) { -// } -// INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8)); -// - -// Range() returns generators providing sequences of values in a range. -// -// Synopsis: -// Range(start, end) -// - returns a generator producing a sequence of values {start, start+1, -// start+2, ..., }. -// Range(start, end, step) -// - returns a generator producing a sequence of values {start, start+step, -// start+step+step, ..., }. -// Notes: -// * The generated sequences never include end. For example, Range(1, 5) -// returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2) -// returns a generator producing {1, 3, 5, 7}. -// * start and end must have the same type. That type may be any integral or -// floating-point type or a user defined type satisfying these conditions: -// * It must be assignable (have operator=() defined). -// * It must have operator+() (operator+(int-compatible type) for -// two-operand version). -// * It must have operator<() defined. -// Elements in the resulting sequences will also have that type. -// * Condition start < end must be satisfied in order for resulting sequences -// to contain any elements. -// -template -internal::ParamGenerator Range(T start, T end, IncrementT step) { - return internal::ParamGenerator( - new internal::RangeGenerator(start, end, step)); -} - -template -internal::ParamGenerator Range(T start, T end) { - return Range(start, end, 1); -} - -// ValuesIn() function allows generation of tests with parameters coming from -// a container. -// -// Synopsis: -// ValuesIn(const T (&array)[N]) -// - returns a generator producing sequences with elements from -// a C-style array. -// ValuesIn(const Container& container) -// - returns a generator producing sequences with elements from -// an STL-style container. -// ValuesIn(Iterator begin, Iterator end) -// - returns a generator producing sequences with elements from -// a range [begin, end) defined by a pair of STL-style iterators. These -// iterators can also be plain C pointers. -// -// Please note that ValuesIn copies the values from the containers -// passed in and keeps them to generate tests in RUN_ALL_TESTS(). -// -// Examples: -// -// This instantiates tests from test case StringTest -// each with C-string values of "foo", "bar", and "baz": -// -// const char* strings[] = {"foo", "bar", "baz"}; -// INSTANTIATE_TEST_CASE_P(StringSequence, SrtingTest, ValuesIn(strings)); -// -// This instantiates tests from test case StlStringTest -// each with STL strings with values "a" and "b": -// -// ::std::vector< ::std::string> GetParameterStrings() { -// ::std::vector< ::std::string> v; -// v.push_back("a"); -// v.push_back("b"); -// return v; -// } -// -// INSTANTIATE_TEST_CASE_P(CharSequence, -// StlStringTest, -// ValuesIn(GetParameterStrings())); -// -// -// This will also instantiate tests from CharTest -// each with parameter values 'a' and 'b': -// -// ::std::list GetParameterChars() { -// ::std::list list; -// list.push_back('a'); -// list.push_back('b'); -// return list; -// } -// ::std::list l = GetParameterChars(); -// INSTANTIATE_TEST_CASE_P(CharSequence2, -// CharTest, -// ValuesIn(l.begin(), l.end())); -// -template -internal::ParamGenerator< - typename ::testing::internal::IteratorTraits::value_type> -ValuesIn(ForwardIterator begin, ForwardIterator end) { - typedef typename ::testing::internal::IteratorTraits - ::value_type ParamType; - return internal::ParamGenerator( - new internal::ValuesInIteratorRangeGenerator(begin, end)); -} - -template -internal::ParamGenerator ValuesIn(const T (&array)[N]) { - return ValuesIn(array, array + N); -} - -template -internal::ParamGenerator ValuesIn( - const Container& container) { - return ValuesIn(container.begin(), container.end()); -} - -// Values() allows generating tests from explicitly specified list of -// parameters. -// -// Synopsis: -// Values(T v1, T v2, ..., T vN) -// - returns a generator producing sequences with elements v1, v2, ..., vN. -// -// For example, this instantiates tests from test case BarTest each -// with values "one", "two", and "three": -// -// INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three")); -// -// This instantiates tests from test case BazTest each with values 1, 2, 3.5. -// The exact type of values will depend on the type of parameter in BazTest. -// -// INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); -// -// Currently, Values() supports from 1 to 50 parameters. -// -template -internal::ValueArray1 Values(T1 v1) { - return internal::ValueArray1(v1); -} - -template -internal::ValueArray2 Values(T1 v1, T2 v2) { - return internal::ValueArray2(v1, v2); -} - -template -internal::ValueArray3 Values(T1 v1, T2 v2, T3 v3) { - return internal::ValueArray3(v1, v2, v3); -} - -template -internal::ValueArray4 Values(T1 v1, T2 v2, T3 v3, T4 v4) { - return internal::ValueArray4(v1, v2, v3, v4); -} - -template -internal::ValueArray5 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5) { - return internal::ValueArray5(v1, v2, v3, v4, v5); -} - -template -internal::ValueArray6 Values(T1 v1, T2 v2, T3 v3, - T4 v4, T5 v5, T6 v6) { - return internal::ValueArray6(v1, v2, v3, v4, v5, v6); -} - -template -internal::ValueArray7 Values(T1 v1, T2 v2, T3 v3, - T4 v4, T5 v5, T6 v6, T7 v7) { - return internal::ValueArray7(v1, v2, v3, v4, v5, - v6, v7); -} - -template -internal::ValueArray8 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) { - return internal::ValueArray8(v1, v2, v3, v4, - v5, v6, v7, v8); -} - -template -internal::ValueArray9 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) { - return internal::ValueArray9(v1, v2, v3, - v4, v5, v6, v7, v8, v9); -} - -template -internal::ValueArray10 Values(T1 v1, - T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) { - return internal::ValueArray10(v1, - v2, v3, v4, v5, v6, v7, v8, v9, v10); -} - -template -internal::ValueArray11 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11) { - return internal::ValueArray11(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11); -} - -template -internal::ValueArray12 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12) { - return internal::ValueArray12(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12); -} - -template -internal::ValueArray13 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13) { - return internal::ValueArray13(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13); -} - -template -internal::ValueArray14 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) { - return internal::ValueArray14(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, - v14); -} - -template -internal::ValueArray15 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, - T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) { - return internal::ValueArray15(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, - v13, v14, v15); -} - -template -internal::ValueArray16 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16) { - return internal::ValueArray16(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, - v12, v13, v14, v15, v16); -} - -template -internal::ValueArray17 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17) { - return internal::ValueArray17(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, - v11, v12, v13, v14, v15, v16, v17); -} - -template -internal::ValueArray18 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, - T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18) { - return internal::ValueArray18(v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18); -} - -template -internal::ValueArray19 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, - T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, - T15 v15, T16 v16, T17 v17, T18 v18, T19 v19) { - return internal::ValueArray19(v1, v2, v3, v4, v5, v6, v7, v8, - v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19); -} - -template -internal::ValueArray20 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20) { - return internal::ValueArray20(v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20); -} - -template -internal::ValueArray21 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21) { - return internal::ValueArray21(v1, v2, v3, v4, v5, v6, - v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21); -} - -template -internal::ValueArray22 Values(T1 v1, T2 v2, T3 v3, - T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22) { - return internal::ValueArray22(v1, v2, v3, v4, - v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22); -} - -template -internal::ValueArray23 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23) { - return internal::ValueArray23(v1, v2, v3, - v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23); -} - -template -internal::ValueArray24 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23, T24 v24) { - return internal::ValueArray24(v1, v2, - v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, - v19, v20, v21, v22, v23, v24); -} - -template -internal::ValueArray25 Values(T1 v1, - T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, - T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, - T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25) { - return internal::ValueArray25(v1, - v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, - v18, v19, v20, v21, v22, v23, v24, v25); -} - -template -internal::ValueArray26 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26) { - return internal::ValueArray26(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, - v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26); -} - -template -internal::ValueArray27 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27) { - return internal::ValueArray27(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, - v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27); -} - -template -internal::ValueArray28 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28) { - return internal::ValueArray28(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, - v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, - v28); -} - -template -internal::ValueArray29 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29) { - return internal::ValueArray29(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, - v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, - v27, v28, v29); -} - -template -internal::ValueArray30 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, - T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, - T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, - T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) { - return internal::ValueArray30(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, - v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, - v26, v27, v28, v29, v30); -} - -template -internal::ValueArray31 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) { - return internal::ValueArray31(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, - v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, - v25, v26, v27, v28, v29, v30, v31); -} - -template -internal::ValueArray32 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32) { - return internal::ValueArray32(v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, - v24, v25, v26, v27, v28, v29, v30, v31, v32); -} - -template -internal::ValueArray33 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, - T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32, T33 v33) { - return internal::ValueArray33(v1, v2, v3, v4, v5, v6, v7, v8, - v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, - v24, v25, v26, v27, v28, v29, v30, v31, v32, v33); -} - -template -internal::ValueArray34 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, - T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, - T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, - T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, - T31 v31, T32 v32, T33 v33, T34 v34) { - return internal::ValueArray34(v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, - v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34); -} - -template -internal::ValueArray35 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, - T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, - T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35) { - return internal::ValueArray35(v1, v2, v3, v4, v5, v6, - v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, - v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35); -} - -template -internal::ValueArray36 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, - T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, - T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36) { - return internal::ValueArray36(v1, v2, v3, v4, - v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, - v34, v35, v36); -} - -template -internal::ValueArray37 Values(T1 v1, T2 v2, T3 v3, - T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, - T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, - T37 v37) { - return internal::ValueArray37(v1, v2, v3, - v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, - v34, v35, v36, v37); -} - -template -internal::ValueArray38 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, - T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, - T37 v37, T38 v38) { - return internal::ValueArray38(v1, v2, - v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, - v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, - v33, v34, v35, v36, v37, v38); -} - -template -internal::ValueArray39 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, - T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, - T37 v37, T38 v38, T39 v39) { - return internal::ValueArray39(v1, - v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, - v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, - v32, v33, v34, v35, v36, v37, v38, v39); -} - -template -internal::ValueArray40 Values(T1 v1, - T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, - T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, - T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, - T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, - T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) { - return internal::ValueArray40(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, - v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, - v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40); -} - -template -internal::ValueArray41 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41) { - return internal::ValueArray41(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, - v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, - v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41); -} - -template -internal::ValueArray42 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42) { - return internal::ValueArray42(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, - v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, - v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, - v42); -} - -template -internal::ValueArray43 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43) { - return internal::ValueArray43(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, - v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, - v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, - v41, v42, v43); -} - -template -internal::ValueArray44 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44) { - return internal::ValueArray44(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, - v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, - v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, - v40, v41, v42, v43, v44); -} - -template -internal::ValueArray45 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, - T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, - T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, - T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, - T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, - T41 v41, T42 v42, T43 v43, T44 v44, T45 v45) { - return internal::ValueArray45(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, - v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, - v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, - v39, v40, v41, v42, v43, v44, v45); -} - -template -internal::ValueArray46 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, - T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) { - return internal::ValueArray46(v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, - v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, - v38, v39, v40, v41, v42, v43, v44, v45, v46); -} - -template -internal::ValueArray47 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, - T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) { - return internal::ValueArray47(v1, v2, v3, v4, v5, v6, v7, v8, - v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, - v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, - v38, v39, v40, v41, v42, v43, v44, v45, v46, v47); -} - -template -internal::ValueArray48 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, - T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, - T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, - T48 v48) { - return internal::ValueArray48(v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, - v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, - v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48); -} - -template -internal::ValueArray49 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, - T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, - T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, - T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, - T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, - T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, - T47 v47, T48 v48, T49 v49) { - return internal::ValueArray49(v1, v2, v3, v4, v5, v6, - v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, - v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, - v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49); -} - -template -internal::ValueArray50 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, - T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, - T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, - T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, - T46 v46, T47 v47, T48 v48, T49 v49, T50 v50) { - return internal::ValueArray50(v1, v2, v3, v4, - v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, - v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, - v48, v49, v50); -} - -// Bool() allows generating tests with parameters in a set of (false, true). -// -// Synopsis: -// Bool() -// - returns a generator producing sequences with elements {false, true}. -// -// It is useful when testing code that depends on Boolean flags. Combinations -// of multiple flags can be tested when several Bool()'s are combined using -// Combine() function. -// -// In the following example all tests in the test case FlagDependentTest -// will be instantiated twice with parameters false and true. -// -// class FlagDependentTest : public testing::TestWithParam { -// virtual void SetUp() { -// external_flag = GetParam(); -// } -// } -// INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool()); -// -inline internal::ParamGenerator Bool() { - return Values(false, true); -} - -# if GTEST_HAS_COMBINE -// Combine() allows the user to combine two or more sequences to produce -// values of a Cartesian product of those sequences' elements. -// -// Synopsis: -// Combine(gen1, gen2, ..., genN) -// - returns a generator producing sequences with elements coming from -// the Cartesian product of elements from the sequences generated by -// gen1, gen2, ..., genN. The sequence elements will have a type of -// tuple where T1, T2, ..., TN are the types -// of elements from sequences produces by gen1, gen2, ..., genN. -// -// Combine can have up to 10 arguments. This number is currently limited -// by the maximum number of elements in the tuple implementation used by Google -// Test. -// -// Example: -// -// This will instantiate tests in test case AnimalTest each one with -// the parameter values tuple("cat", BLACK), tuple("cat", WHITE), -// tuple("dog", BLACK), and tuple("dog", WHITE): -// -// enum Color { BLACK, GRAY, WHITE }; -// class AnimalTest -// : public testing::TestWithParam > {...}; -// -// TEST_P(AnimalTest, AnimalLooksNice) {...} -// -// INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest, -// Combine(Values("cat", "dog"), -// Values(BLACK, WHITE))); -// -// This will instantiate tests in FlagDependentTest with all variations of two -// Boolean flags: -// -// class FlagDependentTest -// : public testing::TestWithParam > { -// virtual void SetUp() { -// // Assigns external_flag_1 and external_flag_2 values from the tuple. -// tie(external_flag_1, external_flag_2) = GetParam(); -// } -// }; -// -// TEST_P(FlagDependentTest, TestFeature1) { -// // Test your code using external_flag_1 and external_flag_2 here. -// } -// INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest, -// Combine(Bool(), Bool())); -// -template -internal::CartesianProductHolder2 Combine( - const Generator1& g1, const Generator2& g2) { - return internal::CartesianProductHolder2( - g1, g2); -} - -template -internal::CartesianProductHolder3 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3) { - return internal::CartesianProductHolder3( - g1, g2, g3); -} - -template -internal::CartesianProductHolder4 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4) { - return internal::CartesianProductHolder4( - g1, g2, g3, g4); -} - -template -internal::CartesianProductHolder5 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5) { - return internal::CartesianProductHolder5( - g1, g2, g3, g4, g5); -} - -template -internal::CartesianProductHolder6 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6) { - return internal::CartesianProductHolder6( - g1, g2, g3, g4, g5, g6); -} - -template -internal::CartesianProductHolder7 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6, - const Generator7& g7) { - return internal::CartesianProductHolder7( - g1, g2, g3, g4, g5, g6, g7); -} - -template -internal::CartesianProductHolder8 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6, - const Generator7& g7, const Generator8& g8) { - return internal::CartesianProductHolder8( - g1, g2, g3, g4, g5, g6, g7, g8); -} - -template -internal::CartesianProductHolder9 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6, - const Generator7& g7, const Generator8& g8, const Generator9& g9) { - return internal::CartesianProductHolder9( - g1, g2, g3, g4, g5, g6, g7, g8, g9); -} - -template -internal::CartesianProductHolder10 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6, - const Generator7& g7, const Generator8& g8, const Generator9& g9, - const Generator10& g10) { - return internal::CartesianProductHolder10( - g1, g2, g3, g4, g5, g6, g7, g8, g9, g10); -} -# endif // GTEST_HAS_COMBINE - - - -# define TEST_P(test_case_name, test_name) \ - class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ - : public test_case_name { \ - public: \ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ - virtual void TestBody(); \ - private: \ - static int AddToRegistry() { \ - ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ - GetTestCasePatternHolder(\ - #test_case_name, __FILE__, __LINE__)->AddTestPattern(\ - #test_case_name, \ - #test_name, \ - new ::testing::internal::TestMetaFactory< \ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>()); \ - return 0; \ - } \ - static int gtest_registering_dummy_; \ - GTEST_DISALLOW_COPY_AND_ASSIGN_(\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ - }; \ - int GTEST_TEST_CLASS_NAME_(test_case_name, \ - test_name)::gtest_registering_dummy_ = \ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ - void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() - -# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator) \ - ::testing::internal::ParamGenerator \ - gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ - int gtest_##prefix##test_case_name##_dummy_ = \ - ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ - GetTestCasePatternHolder(\ - #test_case_name, __FILE__, __LINE__)->AddTestCaseInstantiation(\ - #prefix, \ - >est_##prefix##test_case_name##_EvalGenerator_, \ - __FILE__, __LINE__) - -} // namespace testing - -#endif // GTEST_HAS_PARAM_TEST - -#endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ -// Copyright 2006, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) -// -// Google C++ Testing Framework definitions useful in production code. - -#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ -#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ - -// When you need to test the private or protected members of a class, -// use the FRIEND_TEST macro to declare your tests as friends of the -// class. For example: -// -// class MyClass { -// private: -// void MyMethod(); -// FRIEND_TEST(MyClassTest, MyMethod); -// }; -// -// class MyClassTest : public testing::Test { -// // ... -// }; -// -// TEST_F(MyClassTest, MyMethod) { -// // Can call MyClass::MyMethod() here. -// } - -#define FRIEND_TEST(test_case_name, test_name)\ -friend class test_case_name##_##test_name##_Test - -#endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_ -// Copyright 2008, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: mheule@google.com (Markus Heule) -// - -#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ -#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ - -#include -#include - -namespace testing { - -// A copyable object representing the result of a test part (i.e. an -// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()). -// -// Don't inherit from TestPartResult as its destructor is not virtual. -class GTEST_API_ TestPartResult { - public: - // The possible outcomes of a test part (i.e. an assertion or an - // explicit SUCCEED(), FAIL(), or ADD_FAILURE()). - enum Type { - kSuccess, // Succeeded. - kNonFatalFailure, // Failed but the test can continue. - kFatalFailure // Failed and the test should be terminated. - }; - - // C'tor. TestPartResult does NOT have a default constructor. - // Always use this constructor (with parameters) to create a - // TestPartResult object. - TestPartResult(Type a_type, - const char* a_file_name, - int a_line_number, - const char* a_message) - : type_(a_type), - file_name_(a_file_name), - line_number_(a_line_number), - summary_(ExtractSummary(a_message)), - message_(a_message) { - } - - // Gets the outcome of the test part. - Type type() const { return type_; } - - // Gets the name of the source file where the test part took place, or - // NULL if it's unknown. - const char* file_name() const { return file_name_.c_str(); } - - // Gets the line in the source file where the test part took place, - // or -1 if it's unknown. - int line_number() const { return line_number_; } - - // Gets the summary of the failure message. - const char* summary() const { return summary_.c_str(); } - - // Gets the message associated with the test part. - const char* message() const { return message_.c_str(); } - - // Returns true iff the test part passed. - bool passed() const { return type_ == kSuccess; } - - // Returns true iff the test part failed. - bool failed() const { return type_ != kSuccess; } - - // Returns true iff the test part non-fatally failed. - bool nonfatally_failed() const { return type_ == kNonFatalFailure; } - - // Returns true iff the test part fatally failed. - bool fatally_failed() const { return type_ == kFatalFailure; } - private: - Type type_; - - // Gets the summary of the failure message by omitting the stack - // trace in it. - static internal::String ExtractSummary(const char* message); - - // The name of the source file where the test part took place, or - // NULL if the source file is unknown. - internal::String file_name_; - // The line in the source file where the test part took place, or -1 - // if the line number is unknown. - int line_number_; - internal::String summary_; // The test failure summary. - internal::String message_; // The test failure message. -}; - -// Prints a TestPartResult object. -std::ostream& operator<<(std::ostream& os, const TestPartResult& result); - -// An array of TestPartResult objects. -// -// Don't inherit from TestPartResultArray as its destructor is not -// virtual. -class GTEST_API_ TestPartResultArray { - public: - TestPartResultArray() {} - - // Appends the given TestPartResult to the array. - void Append(const TestPartResult& result); - - // Returns the TestPartResult at the given index (0-based). - const TestPartResult& GetTestPartResult(int index) const; - - // Returns the number of TestPartResult objects in the array. - int size() const; - - private: - std::vector array_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray); -}; - -// This interface knows how to report a test part result. -class TestPartResultReporterInterface { - public: - virtual ~TestPartResultReporterInterface() {} - - virtual void ReportTestPartResult(const TestPartResult& result) = 0; -}; - -namespace internal { - -// This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a -// statement generates new fatal failures. To do so it registers itself as the -// current test part result reporter. Besides checking if fatal failures were -// reported, it only delegates the reporting to the former result reporter. -// The original result reporter is restored in the destructor. -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -class GTEST_API_ HasNewFatalFailureHelper - : public TestPartResultReporterInterface { - public: - HasNewFatalFailureHelper(); - virtual ~HasNewFatalFailureHelper(); - virtual void ReportTestPartResult(const TestPartResult& result); - bool has_new_fatal_failure() const { return has_new_fatal_failure_; } - private: - bool has_new_fatal_failure_; - TestPartResultReporterInterface* original_reporter_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper); -}; - -} // namespace internal - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ -// Copyright 2008 Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) - -#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ -#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ - -// This header implements typed tests and type-parameterized tests. - -// Typed (aka type-driven) tests repeat the same test for types in a -// list. You must know which types you want to test with when writing -// typed tests. Here's how you do it: - -#if 0 - -// First, define a fixture class template. It should be parameterized -// by a type. Remember to derive it from testing::Test. -template -class FooTest : public testing::Test { - public: - ... - typedef std::list List; - static T shared_; - T value_; -}; - -// Next, associate a list of types with the test case, which will be -// repeated for each type in the list. The typedef is necessary for -// the macro to parse correctly. -typedef testing::Types MyTypes; -TYPED_TEST_CASE(FooTest, MyTypes); - -// If the type list contains only one type, you can write that type -// directly without Types<...>: -// TYPED_TEST_CASE(FooTest, int); - -// Then, use TYPED_TEST() instead of TEST_F() to define as many typed -// tests for this test case as you want. -TYPED_TEST(FooTest, DoesBlah) { - // Inside a test, refer to TypeParam to get the type parameter. - // Since we are inside a derived class template, C++ requires use to - // visit the members of FooTest via 'this'. - TypeParam n = this->value_; - - // To visit static members of the fixture, add the TestFixture:: - // prefix. - n += TestFixture::shared_; - - // To refer to typedefs in the fixture, add the "typename - // TestFixture::" prefix. - typename TestFixture::List values; - values.push_back(n); - ... -} - -TYPED_TEST(FooTest, HasPropertyA) { ... } - -#endif // 0 - -// Type-parameterized tests are abstract test patterns parameterized -// by a type. Compared with typed tests, type-parameterized tests -// allow you to define the test pattern without knowing what the type -// parameters are. The defined pattern can be instantiated with -// different types any number of times, in any number of translation -// units. -// -// If you are designing an interface or concept, you can define a -// suite of type-parameterized tests to verify properties that any -// valid implementation of the interface/concept should have. Then, -// each implementation can easily instantiate the test suite to verify -// that it conforms to the requirements, without having to write -// similar tests repeatedly. Here's an example: - -#if 0 - -// First, define a fixture class template. It should be parameterized -// by a type. Remember to derive it from testing::Test. -template -class FooTest : public testing::Test { - ... -}; - -// Next, declare that you will define a type-parameterized test case -// (the _P suffix is for "parameterized" or "pattern", whichever you -// prefer): -TYPED_TEST_CASE_P(FooTest); - -// Then, use TYPED_TEST_P() to define as many type-parameterized tests -// for this type-parameterized test case as you want. -TYPED_TEST_P(FooTest, DoesBlah) { - // Inside a test, refer to TypeParam to get the type parameter. - TypeParam n = 0; - ... -} - -TYPED_TEST_P(FooTest, HasPropertyA) { ... } - -// Now the tricky part: you need to register all test patterns before -// you can instantiate them. The first argument of the macro is the -// test case name; the rest are the names of the tests in this test -// case. -REGISTER_TYPED_TEST_CASE_P(FooTest, - DoesBlah, HasPropertyA); - -// Finally, you are free to instantiate the pattern with the types you -// want. If you put the above code in a header file, you can #include -// it in multiple C++ source files and instantiate it multiple times. -// -// To distinguish different instances of the pattern, the first -// argument to the INSTANTIATE_* macro is a prefix that will be added -// to the actual test case name. Remember to pick unique prefixes for -// different instances. -typedef testing::Types MyTypes; -INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); - -// If the type list contains only one type, you can write that type -// directly without Types<...>: -// INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); - -#endif // 0 - - -// Implements typed tests. - -#if GTEST_HAS_TYPED_TEST - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Expands to the name of the typedef for the type parameters of the -// given test case. -# define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_ - -// The 'Types' template argument below must have spaces around it -// since some compilers may choke on '>>' when passing a template -// instance (e.g. Types) -# define TYPED_TEST_CASE(CaseName, Types) \ - typedef ::testing::internal::TypeList< Types >::type \ - GTEST_TYPE_PARAMS_(CaseName) - -# define TYPED_TEST(CaseName, TestName) \ - template \ - class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ - : public CaseName { \ - private: \ - typedef CaseName TestFixture; \ - typedef gtest_TypeParam_ TypeParam; \ - virtual void TestBody(); \ - }; \ - bool gtest_##CaseName##_##TestName##_registered_ GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTest< \ - CaseName, \ - ::testing::internal::TemplateSel< \ - GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \ - GTEST_TYPE_PARAMS_(CaseName)>::Register(\ - "", #CaseName, #TestName, 0); \ - template \ - void GTEST_TEST_CLASS_NAME_(CaseName, TestName)::TestBody() - -#endif // GTEST_HAS_TYPED_TEST - -// Implements type-parameterized tests. - -#if GTEST_HAS_TYPED_TEST_P - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Expands to the namespace name that the type-parameterized tests for -// the given type-parameterized test case are defined in. The exact -// name of the namespace is subject to change without notice. -# define GTEST_CASE_NAMESPACE_(TestCaseName) \ - gtest_case_##TestCaseName##_ - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Expands to the name of the variable used to remember the names of -// the defined tests in the given test case. -# define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \ - gtest_typed_test_case_p_state_##TestCaseName##_ - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. -// -// Expands to the name of the variable used to remember the names of -// the registered tests in the given test case. -# define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \ - gtest_registered_test_names_##TestCaseName##_ - -// The variables defined in the type-parameterized test macros are -// static as typically these macros are used in a .h file that can be -// #included in multiple translation units linked together. -# define TYPED_TEST_CASE_P(CaseName) \ - static ::testing::internal::TypedTestCasePState \ - GTEST_TYPED_TEST_CASE_P_STATE_(CaseName) - -# define TYPED_TEST_P(CaseName, TestName) \ - namespace GTEST_CASE_NAMESPACE_(CaseName) { \ - template \ - class TestName : public CaseName { \ - private: \ - typedef CaseName TestFixture; \ - typedef gtest_TypeParam_ TypeParam; \ - virtual void TestBody(); \ - }; \ - static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ - GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\ - __FILE__, __LINE__, #CaseName, #TestName); \ - } \ - template \ - void GTEST_CASE_NAMESPACE_(CaseName)::TestName::TestBody() - -# define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \ - namespace GTEST_CASE_NAMESPACE_(CaseName) { \ - typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ - } \ - static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \ - GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\ - __FILE__, __LINE__, #__VA_ARGS__) - -// The 'Types' template argument below must have spaces around it -// since some compilers may choke on '>>' when passing a template -// instance (e.g. Types) -# define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \ - bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTestCase::type>::Register(\ - #Prefix, #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName)) - -#endif // GTEST_HAS_TYPED_TEST_P - -#endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ - -// Depending on the platform, different string classes are available. -// On Linux, in addition to ::std::string, Google also makes use of -// class ::string, which has the same interface as ::std::string, but -// has a different implementation. -// -// The user can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that -// ::string is available AND is a distinct type to ::std::string, or -// define it to 0 to indicate otherwise. -// -// If the user's ::std::string and ::string are the same class due to -// aliasing, he should define GTEST_HAS_GLOBAL_STRING to 0. -// -// If the user doesn't define GTEST_HAS_GLOBAL_STRING, it is defined -// heuristically. - -namespace testing { - -// Declares the flags. - -// This flag temporary enables the disabled tests. -GTEST_DECLARE_bool_(also_run_disabled_tests); - -// This flag brings the debugger on an assertion failure. -GTEST_DECLARE_bool_(break_on_failure); - -// This flag controls whether Google Test catches all test-thrown exceptions -// and logs them as failures. -GTEST_DECLARE_bool_(catch_exceptions); - -// This flag enables using colors in terminal output. Available values are -// "yes" to enable colors, "no" (disable colors), or "auto" (the default) -// to let Google Test decide. -GTEST_DECLARE_string_(color); - -// This flag sets up the filter to select by name using a glob pattern -// the tests to run. If the filter is not given all tests are executed. -GTEST_DECLARE_string_(filter); - -// This flag causes the Google Test to list tests. None of the tests listed -// are actually run if the flag is provided. -GTEST_DECLARE_bool_(list_tests); - -// This flag controls whether Google Test emits a detailed XML report to a file -// in addition to its normal textual output. -GTEST_DECLARE_string_(output); - -// This flags control whether Google Test prints the elapsed time for each -// test. -GTEST_DECLARE_bool_(print_time); - -// This flag specifies the random number seed. -GTEST_DECLARE_int32_(random_seed); - -// This flag sets how many times the tests are repeated. The default value -// is 1. If the value is -1 the tests are repeating forever. -GTEST_DECLARE_int32_(repeat); - -// This flag controls whether Google Test includes Google Test internal -// stack frames in failure stack traces. -GTEST_DECLARE_bool_(show_internal_stack_frames); - -// When this flag is specified, tests' order is randomized on every iteration. -GTEST_DECLARE_bool_(shuffle); - -// This flag specifies the maximum number of stack frames to be -// printed in a failure message. -GTEST_DECLARE_int32_(stack_trace_depth); - -// When this flag is specified, a failed assertion will throw an -// exception if exceptions are enabled, or exit the program with a -// non-zero code otherwise. -GTEST_DECLARE_bool_(throw_on_failure); - -// When this flag is set with a "host:port" string, on supported -// platforms test results are streamed to the specified port on -// the specified host machine. -GTEST_DECLARE_string_(stream_result_to); - -// The upper limit for valid stack trace depths. -const int kMaxStackTraceDepth = 100; - -namespace internal { - -class AssertHelper; -class DefaultGlobalTestPartResultReporter; -class ExecDeathTest; -class NoExecDeathTest; -class FinalSuccessChecker; -class GTestFlagSaver; -class TestResultAccessor; -class TestEventListenersAccessor; -class TestEventRepeater; -class WindowsDeathTest; -class UnitTestImpl* GetUnitTestImpl(); -void ReportFailureInUnknownLocation(TestPartResult::Type result_type, - const String& message); - -// Converts a streamable value to a String. A NULL pointer is -// converted to "(null)". When the input value is a ::string, -// ::std::string, ::wstring, or ::std::wstring object, each NUL -// character in it is replaced with "\\0". -// Declared in gtest-internal.h but defined here, so that it has access -// to the definition of the Message class, required by the ARM -// compiler. -template -String StreamableToString(const T& streamable) { - return (Message() << streamable).GetString(); -} - -} // namespace internal - -// The friend relationship of some of these classes is cyclic. -// If we don't forward declare them the compiler might confuse the classes -// in friendship clauses with same named classes on the scope. -class Test; -class TestCase; -class TestInfo; -class UnitTest; - -// A class for indicating whether an assertion was successful. When -// the assertion wasn't successful, the AssertionResult object -// remembers a non-empty message that describes how it failed. -// -// To create an instance of this class, use one of the factory functions -// (AssertionSuccess() and AssertionFailure()). -// -// This class is useful for two purposes: -// 1. Defining predicate functions to be used with Boolean test assertions -// EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts -// 2. Defining predicate-format functions to be -// used with predicate assertions (ASSERT_PRED_FORMAT*, etc). -// -// For example, if you define IsEven predicate: -// -// testing::AssertionResult IsEven(int n) { -// if ((n % 2) == 0) -// return testing::AssertionSuccess(); -// else -// return testing::AssertionFailure() << n << " is odd"; -// } -// -// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5))) -// will print the message -// -// Value of: IsEven(Fib(5)) -// Actual: false (5 is odd) -// Expected: true -// -// instead of a more opaque -// -// Value of: IsEven(Fib(5)) -// Actual: false -// Expected: true -// -// in case IsEven is a simple Boolean predicate. -// -// If you expect your predicate to be reused and want to support informative -// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up -// about half as often as positive ones in our tests), supply messages for -// both success and failure cases: -// -// testing::AssertionResult IsEven(int n) { -// if ((n % 2) == 0) -// return testing::AssertionSuccess() << n << " is even"; -// else -// return testing::AssertionFailure() << n << " is odd"; -// } -// -// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print -// -// Value of: IsEven(Fib(6)) -// Actual: true (8 is even) -// Expected: false -// -// NB: Predicates that support negative Boolean assertions have reduced -// performance in positive ones so be careful not to use them in tests -// that have lots (tens of thousands) of positive Boolean assertions. -// -// To use this class with EXPECT_PRED_FORMAT assertions such as: -// -// // Verifies that Foo() returns an even number. -// EXPECT_PRED_FORMAT1(IsEven, Foo()); -// -// you need to define: -// -// testing::AssertionResult IsEven(const char* expr, int n) { -// if ((n % 2) == 0) -// return testing::AssertionSuccess(); -// else -// return testing::AssertionFailure() -// << "Expected: " << expr << " is even\n Actual: it's " << n; -// } -// -// If Foo() returns 5, you will see the following message: -// -// Expected: Foo() is even -// Actual: it's 5 -// -class GTEST_API_ AssertionResult { - public: - // Copy constructor. - // Used in EXPECT_TRUE/FALSE(assertion_result). - AssertionResult(const AssertionResult& other); - // Used in the EXPECT_TRUE/FALSE(bool_expression). - explicit AssertionResult(bool success) : success_(success) {} - - // Returns true iff the assertion succeeded. - operator bool() const { return success_; } // NOLINT - - // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. - AssertionResult operator!() const; - - // Returns the text streamed into this AssertionResult. Test assertions - // use it when they fail (i.e., the predicate's outcome doesn't match the - // assertion's expectation). When nothing has been streamed into the - // object, returns an empty string. - const char* message() const { - return message_.get() != NULL ? message_->c_str() : ""; - } - // TODO(vladl@google.com): Remove this after making sure no clients use it. - // Deprecated; please use message() instead. - const char* failure_message() const { return message(); } - - // Streams a custom failure message into this object. - template AssertionResult& operator<<(const T& value) { - AppendMessage(Message() << value); - return *this; - } - - // Allows streaming basic output manipulators such as endl or flush into - // this object. - AssertionResult& operator<<( - ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) { - AppendMessage(Message() << basic_manipulator); - return *this; - } - - private: - // Appends the contents of message to message_. - void AppendMessage(const Message& a_message) { - if (message_.get() == NULL) - message_.reset(new ::std::string); - message_->append(a_message.GetString().c_str()); - } - - // Stores result of the assertion predicate. - bool success_; - // Stores the message describing the condition in case the expectation - // construct is not satisfied with the predicate's outcome. - // Referenced via a pointer to avoid taking too much stack frame space - // with test assertions. - internal::scoped_ptr< ::std::string> message_; - - GTEST_DISALLOW_ASSIGN_(AssertionResult); -}; - -// Makes a successful assertion result. -GTEST_API_ AssertionResult AssertionSuccess(); - -// Makes a failed assertion result. -GTEST_API_ AssertionResult AssertionFailure(); - -// Makes a failed assertion result with the given failure message. -// Deprecated; use AssertionFailure() << msg. -GTEST_API_ AssertionResult AssertionFailure(const Message& msg); - -// The abstract class that all tests inherit from. -// -// In Google Test, a unit test program contains one or many TestCases, and -// each TestCase contains one or many Tests. -// -// When you define a test using the TEST macro, you don't need to -// explicitly derive from Test - the TEST macro automatically does -// this for you. -// -// The only time you derive from Test is when defining a test fixture -// to be used a TEST_F. For example: -// -// class FooTest : public testing::Test { -// protected: -// virtual void SetUp() { ... } -// virtual void TearDown() { ... } -// ... -// }; -// -// TEST_F(FooTest, Bar) { ... } -// TEST_F(FooTest, Baz) { ... } -// -// Test is not copyable. -class GTEST_API_ Test { - public: - friend class TestInfo; - - // Defines types for pointers to functions that set up and tear down - // a test case. - typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc; - typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc; - - // The d'tor is virtual as we intend to inherit from Test. - virtual ~Test(); - - // Sets up the stuff shared by all tests in this test case. - // - // Google Test will call Foo::SetUpTestCase() before running the first - // test in test case Foo. Hence a sub-class can define its own - // SetUpTestCase() method to shadow the one defined in the super - // class. - static void SetUpTestCase() {} - - // Tears down the stuff shared by all tests in this test case. - // - // Google Test will call Foo::TearDownTestCase() after running the last - // test in test case Foo. Hence a sub-class can define its own - // TearDownTestCase() method to shadow the one defined in the super - // class. - static void TearDownTestCase() {} - - // Returns true iff the current test has a fatal failure. - static bool HasFatalFailure(); - - // Returns true iff the current test has a non-fatal failure. - static bool HasNonfatalFailure(); - - // Returns true iff the current test has a (either fatal or - // non-fatal) failure. - static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } - - // Logs a property for the current test. Only the last value for a given - // key is remembered. - // These are public static so they can be called from utility functions - // that are not members of the test fixture. - // The arguments are const char* instead strings, as Google Test is used - // on platforms where string doesn't compile. - // - // Note that a driving consideration for these RecordProperty methods - // was to produce xml output suited to the Greenspan charting utility, - // which at present will only chart values that fit in a 32-bit int. It - // is the user's responsibility to restrict their values to 32-bit ints - // if they intend them to be used with Greenspan. - static void RecordProperty(const char* key, const char* value); - static void RecordProperty(const char* key, int value); - - protected: - // Creates a Test object. - Test(); - - // Sets up the test fixture. - virtual void SetUp(); - - // Tears down the test fixture. - virtual void TearDown(); - - private: - // Returns true iff the current test has the same fixture class as - // the first test in the current test case. - static bool HasSameFixtureClass(); - - // Runs the test after the test fixture has been set up. - // - // A sub-class must implement this to define the test logic. - // - // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM. - // Instead, use the TEST or TEST_F macro. - virtual void TestBody() = 0; - - // Sets up, executes, and tears down the test. - void Run(); - - // Deletes self. We deliberately pick an unusual name for this - // internal method to avoid clashing with names used in user TESTs. - void DeleteSelf_() { delete this; } - - // Uses a GTestFlagSaver to save and restore all Google Test flags. - const internal::GTestFlagSaver* const gtest_flag_saver_; - - // Often a user mis-spells SetUp() as Setup() and spends a long time - // wondering why it is never called by Google Test. The declaration of - // the following method is solely for catching such an error at - // compile time: - // - // - The return type is deliberately chosen to be not void, so it - // will be a conflict if a user declares void Setup() in his test - // fixture. - // - // - This method is private, so it will be another compiler error - // if a user calls it from his test fixture. - // - // DO NOT OVERRIDE THIS FUNCTION. - // - // If you see an error about overriding the following function or - // about it being private, you have mis-spelled SetUp() as Setup(). - struct Setup_should_be_spelled_SetUp {}; - virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } - - // We disallow copying Tests. - GTEST_DISALLOW_COPY_AND_ASSIGN_(Test); -}; - -typedef internal::TimeInMillis TimeInMillis; - -// A copyable object representing a user specified test property which can be -// output as a key/value string pair. -// -// Don't inherit from TestProperty as its destructor is not virtual. -class TestProperty { - public: - // C'tor. TestProperty does NOT have a default constructor. - // Always use this constructor (with parameters) to create a - // TestProperty object. - TestProperty(const char* a_key, const char* a_value) : - key_(a_key), value_(a_value) { - } - - // Gets the user supplied key. - const char* key() const { - return key_.c_str(); - } - - // Gets the user supplied value. - const char* value() const { - return value_.c_str(); - } - - // Sets a new value, overriding the one supplied in the constructor. - void SetValue(const char* new_value) { - value_ = new_value; - } - - private: - // The key supplied by the user. - internal::String key_; - // The value supplied by the user. - internal::String value_; -}; - -// The result of a single Test. This includes a list of -// TestPartResults, a list of TestProperties, a count of how many -// death tests there are in the Test, and how much time it took to run -// the Test. -// -// TestResult is not copyable. -class GTEST_API_ TestResult { - public: - // Creates an empty TestResult. - TestResult(); - - // D'tor. Do not inherit from TestResult. - ~TestResult(); - - // Gets the number of all test parts. This is the sum of the number - // of successful test parts and the number of failed test parts. - int total_part_count() const; - - // Returns the number of the test properties. - int test_property_count() const; - - // Returns true iff the test passed (i.e. no test part failed). - bool Passed() const { return !Failed(); } - - // Returns true iff the test failed. - bool Failed() const; - - // Returns true iff the test fatally failed. - bool HasFatalFailure() const; - - // Returns true iff the test has a non-fatal failure. - bool HasNonfatalFailure() const; - - // Returns the elapsed time, in milliseconds. - TimeInMillis elapsed_time() const { return elapsed_time_; } - - // Returns the i-th test part result among all the results. i can range - // from 0 to test_property_count() - 1. If i is not in that range, aborts - // the program. - const TestPartResult& GetTestPartResult(int i) const; - - // Returns the i-th test property. i can range from 0 to - // test_property_count() - 1. If i is not in that range, aborts the - // program. - const TestProperty& GetTestProperty(int i) const; - - private: - friend class TestInfo; - friend class UnitTest; - friend class internal::DefaultGlobalTestPartResultReporter; - friend class internal::ExecDeathTest; - friend class internal::TestResultAccessor; - friend class internal::UnitTestImpl; - friend class internal::WindowsDeathTest; - - // Gets the vector of TestPartResults. - const std::vector& test_part_results() const { - return test_part_results_; - } - - // Gets the vector of TestProperties. - const std::vector& test_properties() const { - return test_properties_; - } - - // Sets the elapsed time. - void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } - - // Adds a test property to the list. The property is validated and may add - // a non-fatal failure if invalid (e.g., if it conflicts with reserved - // key names). If a property is already recorded for the same key, the - // value will be updated, rather than storing multiple values for the same - // key. - void RecordProperty(const TestProperty& test_property); - - // Adds a failure if the key is a reserved attribute of Google Test - // testcase tags. Returns true if the property is valid. - // TODO(russr): Validate attribute names are legal and human readable. - static bool ValidateTestProperty(const TestProperty& test_property); - - // Adds a test part result to the list. - void AddTestPartResult(const TestPartResult& test_part_result); - - // Returns the death test count. - int death_test_count() const { return death_test_count_; } - - // Increments the death test count, returning the new count. - int increment_death_test_count() { return ++death_test_count_; } - - // Clears the test part results. - void ClearTestPartResults(); - - // Clears the object. - void Clear(); - - // Protects mutable state of the property vector and of owned - // properties, whose values may be updated. - internal::Mutex test_properites_mutex_; - - // The vector of TestPartResults - std::vector test_part_results_; - // The vector of TestProperties - std::vector test_properties_; - // Running count of death tests. - int death_test_count_; - // The elapsed time, in milliseconds. - TimeInMillis elapsed_time_; - - // We disallow copying TestResult. - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult); -}; // class TestResult - -// A TestInfo object stores the following information about a test: -// -// Test case name -// Test name -// Whether the test should be run -// A function pointer that creates the test object when invoked -// Test result -// -// The constructor of TestInfo registers itself with the UnitTest -// singleton such that the RUN_ALL_TESTS() macro knows which tests to -// run. -class GTEST_API_ TestInfo { - public: - // Destructs a TestInfo object. This function is not virtual, so - // don't inherit from TestInfo. - ~TestInfo(); - - // Returns the test case name. - const char* test_case_name() const { return test_case_name_.c_str(); } - - // Returns the test name. - const char* name() const { return name_.c_str(); } - - // Returns the name of the parameter type, or NULL if this is not a typed - // or a type-parameterized test. - const char* type_param() const { - if (type_param_.get() != NULL) - return type_param_->c_str(); - return NULL; - } - - // Returns the text representation of the value parameter, or NULL if this - // is not a value-parameterized test. - const char* value_param() const { - if (value_param_.get() != NULL) - return value_param_->c_str(); - return NULL; - } - - // Returns true if this test should run, that is if the test is not disabled - // (or it is disabled but the also_run_disabled_tests flag has been specified) - // and its full name matches the user-specified filter. - // - // Google Test allows the user to filter the tests by their full names. - // The full name of a test Bar in test case Foo is defined as - // "Foo.Bar". Only the tests that match the filter will run. - // - // A filter is a colon-separated list of glob (not regex) patterns, - // optionally followed by a '-' and a colon-separated list of - // negative patterns (tests to exclude). A test is run if it - // matches one of the positive patterns and does not match any of - // the negative patterns. - // - // For example, *A*:Foo.* is a filter that matches any string that - // contains the character 'A' or starts with "Foo.". - bool should_run() const { return should_run_; } - - // Returns the result of the test. - const TestResult* result() const { return &result_; } - - private: - -#if GTEST_HAS_DEATH_TEST - friend class internal::DefaultDeathTestFactory; -#endif // GTEST_HAS_DEATH_TEST - friend class Test; - friend class TestCase; - friend class internal::UnitTestImpl; - friend TestInfo* internal::MakeAndRegisterTestInfo( - const char* test_case_name, const char* name, - const char* type_param, - const char* value_param, - internal::TypeId fixture_class_id, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc, - internal::TestFactoryBase* factory); - - // Constructs a TestInfo object. The newly constructed instance assumes - // ownership of the factory object. - TestInfo(const char* test_case_name, const char* name, - const char* a_type_param, - const char* a_value_param, - internal::TypeId fixture_class_id, - internal::TestFactoryBase* factory); - - // Increments the number of death tests encountered in this test so - // far. - int increment_death_test_count() { - return result_.increment_death_test_count(); - } - - // Creates the test object, runs it, records its result, and then - // deletes it. - void Run(); - - static void ClearTestResult(TestInfo* test_info) { - test_info->result_.Clear(); - } - - // These fields are immutable properties of the test. - const std::string test_case_name_; // Test case name - const std::string name_; // Test name - // Name of the parameter type, or NULL if this is not a typed or a - // type-parameterized test. - const internal::scoped_ptr type_param_; - // Text representation of the value parameter, or NULL if this is not a - // value-parameterized test. - const internal::scoped_ptr value_param_; - const internal::TypeId fixture_class_id_; // ID of the test fixture class - bool should_run_; // True iff this test should run - bool is_disabled_; // True iff this test is disabled - bool matches_filter_; // True if this test matches the - // user-specified filter. - internal::TestFactoryBase* const factory_; // The factory that creates - // the test object - - // This field is mutable and needs to be reset before running the - // test for the second time. - TestResult result_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); -}; - -// A test case, which consists of a vector of TestInfos. -// -// TestCase is not copyable. -class GTEST_API_ TestCase { - public: - // Creates a TestCase with the given name. - // - // TestCase does NOT have a default constructor. Always use this - // constructor to create a TestCase object. - // - // Arguments: - // - // name: name of the test case - // a_type_param: the name of the test's type parameter, or NULL if - // this is not a type-parameterized test. - // set_up_tc: pointer to the function that sets up the test case - // tear_down_tc: pointer to the function that tears down the test case - TestCase(const char* name, const char* a_type_param, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc); - - // Destructor of TestCase. - virtual ~TestCase(); - - // Gets the name of the TestCase. - const char* name() const { return name_.c_str(); } - - // Returns the name of the parameter type, or NULL if this is not a - // type-parameterized test case. - const char* type_param() const { - if (type_param_.get() != NULL) - return type_param_->c_str(); - return NULL; - } - - // Returns true if any test in this test case should run. - bool should_run() const { return should_run_; } - - // Gets the number of successful tests in this test case. - int successful_test_count() const; - - // Gets the number of failed tests in this test case. - int failed_test_count() const; - - // Gets the number of disabled tests in this test case. - int disabled_test_count() const; - - // Get the number of tests in this test case that should run. - int test_to_run_count() const; - - // Gets the number of all tests in this test case. - int total_test_count() const; - - // Returns true iff the test case passed. - bool Passed() const { return !Failed(); } - - // Returns true iff the test case failed. - bool Failed() const { return failed_test_count() > 0; } - - // Returns the elapsed time, in milliseconds. - TimeInMillis elapsed_time() const { return elapsed_time_; } - - // Returns the i-th test among all the tests. i can range from 0 to - // total_test_count() - 1. If i is not in that range, returns NULL. - const TestInfo* GetTestInfo(int i) const; - - private: - friend class Test; - friend class internal::UnitTestImpl; - - // Gets the (mutable) vector of TestInfos in this TestCase. - std::vector& test_info_list() { return test_info_list_; } - - // Gets the (immutable) vector of TestInfos in this TestCase. - const std::vector& test_info_list() const { - return test_info_list_; - } - - // Returns the i-th test among all the tests. i can range from 0 to - // total_test_count() - 1. If i is not in that range, returns NULL. - TestInfo* GetMutableTestInfo(int i); - - // Sets the should_run member. - void set_should_run(bool should) { should_run_ = should; } - - // Adds a TestInfo to this test case. Will delete the TestInfo upon - // destruction of the TestCase object. - void AddTestInfo(TestInfo * test_info); - - // Clears the results of all tests in this test case. - void ClearResult(); - - // Clears the results of all tests in the given test case. - static void ClearTestCaseResult(TestCase* test_case) { - test_case->ClearResult(); - } - - // Runs every test in this TestCase. - void Run(); - - // Runs SetUpTestCase() for this TestCase. This wrapper is needed - // for catching exceptions thrown from SetUpTestCase(). - void RunSetUpTestCase() { (*set_up_tc_)(); } - - // Runs TearDownTestCase() for this TestCase. This wrapper is - // needed for catching exceptions thrown from TearDownTestCase(). - void RunTearDownTestCase() { (*tear_down_tc_)(); } - - // Returns true iff test passed. - static bool TestPassed(const TestInfo* test_info) { - return test_info->should_run() && test_info->result()->Passed(); - } - - // Returns true iff test failed. - static bool TestFailed(const TestInfo* test_info) { - return test_info->should_run() && test_info->result()->Failed(); - } - - // Returns true iff test is disabled. - static bool TestDisabled(const TestInfo* test_info) { - return test_info->is_disabled_; - } - - // Returns true if the given test should run. - static bool ShouldRunTest(const TestInfo* test_info) { - return test_info->should_run(); - } - - // Shuffles the tests in this test case. - void ShuffleTests(internal::Random* random); - - // Restores the test order to before the first shuffle. - void UnshuffleTests(); - - // Name of the test case. - internal::String name_; - // Name of the parameter type, or NULL if this is not a typed or a - // type-parameterized test. - const internal::scoped_ptr type_param_; - // The vector of TestInfos in their original order. It owns the - // elements in the vector. - std::vector test_info_list_; - // Provides a level of indirection for the test list to allow easy - // shuffling and restoring the test order. The i-th element in this - // vector is the index of the i-th test in the shuffled test list. - std::vector test_indices_; - // Pointer to the function that sets up the test case. - Test::SetUpTestCaseFunc set_up_tc_; - // Pointer to the function that tears down the test case. - Test::TearDownTestCaseFunc tear_down_tc_; - // True iff any test in this test case should run. - bool should_run_; - // Elapsed time, in milliseconds. - TimeInMillis elapsed_time_; - - // We disallow copying TestCases. - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); -}; - -// An Environment object is capable of setting up and tearing down an -// environment. The user should subclass this to define his own -// environment(s). -// -// An Environment object does the set-up and tear-down in virtual -// methods SetUp() and TearDown() instead of the constructor and the -// destructor, as: -// -// 1. You cannot safely throw from a destructor. This is a problem -// as in some cases Google Test is used where exceptions are enabled, and -// we may want to implement ASSERT_* using exceptions where they are -// available. -// 2. You cannot use ASSERT_* directly in a constructor or -// destructor. -class Environment { - public: - // The d'tor is virtual as we need to subclass Environment. - virtual ~Environment() {} - - // Override this to define how to set up the environment. - virtual void SetUp() {} - - // Override this to define how to tear down the environment. - virtual void TearDown() {} - private: - // If you see an error about overriding the following function or - // about it being private, you have mis-spelled SetUp() as Setup(). - struct Setup_should_be_spelled_SetUp {}; - virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } -}; - -// The interface for tracing execution of tests. The methods are organized in -// the order the corresponding events are fired. -class TestEventListener { - public: - virtual ~TestEventListener() {} - - // Fired before any test activity starts. - virtual void OnTestProgramStart(const UnitTest& unit_test) = 0; - - // Fired before each iteration of tests starts. There may be more than - // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration - // index, starting from 0. - virtual void OnTestIterationStart(const UnitTest& unit_test, - int iteration) = 0; - - // Fired before environment set-up for each iteration of tests starts. - virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0; - - // Fired after environment set-up for each iteration of tests ends. - virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0; - - // Fired before the test case starts. - virtual void OnTestCaseStart(const TestCase& test_case) = 0; - - // Fired before the test starts. - virtual void OnTestStart(const TestInfo& test_info) = 0; - - // Fired after a failed assertion or a SUCCEED() invocation. - virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0; - - // Fired after the test ends. - virtual void OnTestEnd(const TestInfo& test_info) = 0; - - // Fired after the test case ends. - virtual void OnTestCaseEnd(const TestCase& test_case) = 0; - - // Fired before environment tear-down for each iteration of tests starts. - virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0; - - // Fired after environment tear-down for each iteration of tests ends. - virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; - - // Fired after each iteration of tests finishes. - virtual void OnTestIterationEnd(const UnitTest& unit_test, - int iteration) = 0; - - // Fired after all test activities have ended. - virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; -}; - -// The convenience class for users who need to override just one or two -// methods and are not concerned that a possible change to a signature of -// the methods they override will not be caught during the build. For -// comments about each method please see the definition of TestEventListener -// above. -class EmptyTestEventListener : public TestEventListener { - public: - virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} - virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, - int /*iteration*/) {} - virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {} - virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} - virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} - virtual void OnTestStart(const TestInfo& /*test_info*/) {} - virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {} - virtual void OnTestEnd(const TestInfo& /*test_info*/) {} - virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} - virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {} - virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} - virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, - int /*iteration*/) {} - virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} -}; - -// TestEventListeners lets users add listeners to track events in Google Test. -class GTEST_API_ TestEventListeners { - public: - TestEventListeners(); - ~TestEventListeners(); - - // Appends an event listener to the end of the list. Google Test assumes - // the ownership of the listener (i.e. it will delete the listener when - // the test program finishes). - void Append(TestEventListener* listener); - - // Removes the given event listener from the list and returns it. It then - // becomes the caller's responsibility to delete the listener. Returns - // NULL if the listener is not found in the list. - TestEventListener* Release(TestEventListener* listener); - - // Returns the standard listener responsible for the default console - // output. Can be removed from the listeners list to shut down default - // console output. Note that removing this object from the listener list - // with Release transfers its ownership to the caller and makes this - // function return NULL the next time. - TestEventListener* default_result_printer() const { - return default_result_printer_; - } - - // Returns the standard listener responsible for the default XML output - // controlled by the --gtest_output=xml flag. Can be removed from the - // listeners list by users who want to shut down the default XML output - // controlled by this flag and substitute it with custom one. Note that - // removing this object from the listener list with Release transfers its - // ownership to the caller and makes this function return NULL the next - // time. - TestEventListener* default_xml_generator() const { - return default_xml_generator_; - } - - private: - friend class TestCase; - friend class TestInfo; - friend class internal::DefaultGlobalTestPartResultReporter; - friend class internal::NoExecDeathTest; - friend class internal::TestEventListenersAccessor; - friend class internal::UnitTestImpl; - - // Returns repeater that broadcasts the TestEventListener events to all - // subscribers. - TestEventListener* repeater(); - - // Sets the default_result_printer attribute to the provided listener. - // The listener is also added to the listener list and previous - // default_result_printer is removed from it and deleted. The listener can - // also be NULL in which case it will not be added to the list. Does - // nothing if the previous and the current listener objects are the same. - void SetDefaultResultPrinter(TestEventListener* listener); - - // Sets the default_xml_generator attribute to the provided listener. The - // listener is also added to the listener list and previous - // default_xml_generator is removed from it and deleted. The listener can - // also be NULL in which case it will not be added to the list. Does - // nothing if the previous and the current listener objects are the same. - void SetDefaultXmlGenerator(TestEventListener* listener); - - // Controls whether events will be forwarded by the repeater to the - // listeners in the list. - bool EventForwardingEnabled() const; - void SuppressEventForwarding(); - - // The actual list of listeners. - internal::TestEventRepeater* repeater_; - // Listener responsible for the standard result output. - TestEventListener* default_result_printer_; - // Listener responsible for the creation of the XML output file. - TestEventListener* default_xml_generator_; - - // We disallow copying TestEventListeners. - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); -}; - -// A UnitTest consists of a vector of TestCases. -// -// This is a singleton class. The only instance of UnitTest is -// created when UnitTest::GetInstance() is first called. This -// instance is never deleted. -// -// UnitTest is not copyable. -// -// This class is thread-safe as long as the methods are called -// according to their specification. -class GTEST_API_ UnitTest { - public: - // Gets the singleton UnitTest object. The first time this method - // is called, a UnitTest object is constructed and returned. - // Consecutive calls will return the same object. - static UnitTest* GetInstance(); - - // Runs all tests in this UnitTest object and prints the result. - // Returns 0 if successful, or 1 otherwise. - // - // This method can only be called from the main thread. - // - // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - int Run() GTEST_MUST_USE_RESULT_; - - // Returns the working directory when the first TEST() or TEST_F() - // was executed. The UnitTest object owns the string. - const char* original_working_dir() const; - - // Returns the TestCase object for the test that's currently running, - // or NULL if no test is running. - const TestCase* current_test_case() const; - - // Returns the TestInfo object for the test that's currently running, - // or NULL if no test is running. - const TestInfo* current_test_info() const; - - // Returns the random seed used at the start of the current test run. - int random_seed() const; - -#if GTEST_HAS_PARAM_TEST - // Returns the ParameterizedTestCaseRegistry object used to keep track of - // value-parameterized tests and instantiate and register them. - // - // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - internal::ParameterizedTestCaseRegistry& parameterized_test_registry(); -#endif // GTEST_HAS_PARAM_TEST - - // Gets the number of successful test cases. - int successful_test_case_count() const; - - // Gets the number of failed test cases. - int failed_test_case_count() const; - - // Gets the number of all test cases. - int total_test_case_count() const; - - // Gets the number of all test cases that contain at least one test - // that should run. - int test_case_to_run_count() const; - - // Gets the number of successful tests. - int successful_test_count() const; - - // Gets the number of failed tests. - int failed_test_count() const; - - // Gets the number of disabled tests. - int disabled_test_count() const; - - // Gets the number of all tests. - int total_test_count() const; - - // Gets the number of tests that should run. - int test_to_run_count() const; - - // Gets the elapsed time, in milliseconds. - TimeInMillis elapsed_time() const; - - // Returns true iff the unit test passed (i.e. all test cases passed). - bool Passed() const; - - // Returns true iff the unit test failed (i.e. some test case failed - // or something outside of all tests failed). - bool Failed() const; - - // Gets the i-th test case among all the test cases. i can range from 0 to - // total_test_case_count() - 1. If i is not in that range, returns NULL. - const TestCase* GetTestCase(int i) const; - - // Returns the list of event listeners that can be used to track events - // inside Google Test. - TestEventListeners& listeners(); - - private: - // Registers and returns a global test environment. When a test - // program is run, all global test environments will be set-up in - // the order they were registered. After all tests in the program - // have finished, all global test environments will be torn-down in - // the *reverse* order they were registered. - // - // The UnitTest object takes ownership of the given environment. - // - // This method can only be called from the main thread. - Environment* AddEnvironment(Environment* env); - - // Adds a TestPartResult to the current TestResult object. All - // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) - // eventually call this to report their results. The user code - // should use the assertion macros instead of calling this directly. - void AddTestPartResult(TestPartResult::Type result_type, - const char* file_name, - int line_number, - const internal::String& message, - const internal::String& os_stack_trace); - - // Adds a TestProperty to the current TestResult object. If the result already - // contains a property with the same key, the value will be updated. - void RecordPropertyForCurrentTest(const char* key, const char* value); - - // Gets the i-th test case among all the test cases. i can range from 0 to - // total_test_case_count() - 1. If i is not in that range, returns NULL. - TestCase* GetMutableTestCase(int i); - - // Accessors for the implementation object. - internal::UnitTestImpl* impl() { return impl_; } - const internal::UnitTestImpl* impl() const { return impl_; } - - // These classes and funcions are friends as they need to access private - // members of UnitTest. - friend class Test; - friend class internal::AssertHelper; - friend class internal::ScopedTrace; - friend Environment* AddGlobalTestEnvironment(Environment* env); - friend internal::UnitTestImpl* internal::GetUnitTestImpl(); - friend void internal::ReportFailureInUnknownLocation( - TestPartResult::Type result_type, - const internal::String& message); - - // Creates an empty UnitTest. - UnitTest(); - - // D'tor - virtual ~UnitTest(); - - // Pushes a trace defined by SCOPED_TRACE() on to the per-thread - // Google Test trace stack. - void PushGTestTrace(const internal::TraceInfo& trace); - - // Pops a trace from the per-thread Google Test trace stack. - void PopGTestTrace(); - - // Protects mutable state in *impl_. This is mutable as some const - // methods need to lock it too. - mutable internal::Mutex mutex_; - - // Opaque implementation object. This field is never changed once - // the object is constructed. We don't mark it as const here, as - // doing so will cause a warning in the constructor of UnitTest. - // Mutable state in *impl_ is protected by mutex_. - internal::UnitTestImpl* impl_; - - // We disallow copying UnitTest. - GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest); -}; - -// A convenient wrapper for adding an environment for the test -// program. -// -// You should call this before RUN_ALL_TESTS() is called, probably in -// main(). If you use gtest_main, you need to call this before main() -// starts for it to take effect. For example, you can define a global -// variable like this: -// -// testing::Environment* const foo_env = -// testing::AddGlobalTestEnvironment(new FooEnvironment); -// -// However, we strongly recommend you to write your own main() and -// call AddGlobalTestEnvironment() there, as relying on initialization -// of global variables makes the code harder to read and may cause -// problems when you register multiple environments from different -// translation units and the environments have dependencies among them -// (remember that the compiler doesn't guarantee the order in which -// global variables from different translation units are initialized). -inline Environment* AddGlobalTestEnvironment(Environment* env) { - return UnitTest::GetInstance()->AddEnvironment(env); -} - -// Initializes Google Test. This must be called before calling -// RUN_ALL_TESTS(). In particular, it parses a command line for the -// flags that Google Test recognizes. Whenever a Google Test flag is -// seen, it is removed from argv, and *argc is decremented. -// -// No value is returned. Instead, the Google Test flag variables are -// updated. -// -// Calling the function for the second time has no user-visible effect. -GTEST_API_ void InitGoogleTest(int* argc, char** argv); - -// This overloaded version can be used in Windows programs compiled in -// UNICODE mode. -GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); - -namespace internal { - -// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc) -// operand to be used in a failure message. The type (but not value) -// of the other operand may affect the format. This allows us to -// print a char* as a raw pointer when it is compared against another -// char*, and print it as a C string when it is compared against an -// std::string object, for example. -// -// The default implementation ignores the type of the other operand. -// Some specialized versions are used to handle formatting wide or -// narrow C strings. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -template -String FormatForComparisonFailureMessage(const T1& value, - const T2& /* other_operand */) { - // C++Builder compiles this incorrectly if the namespace isn't explicitly - // given. - return ::testing::PrintToString(value); -} - -// The helper function for {ASSERT|EXPECT}_EQ. -template -AssertionResult CmpHelperEQ(const char* expected_expression, - const char* actual_expression, - const T1& expected, - const T2& actual) { -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4389) // Temporarily disables warning on - // signed/unsigned mismatch. -#endif - - if (expected == actual) { - return AssertionSuccess(); - } - -#ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif - - return EqFailure(expected_expression, - actual_expression, - FormatForComparisonFailureMessage(expected, actual), - FormatForComparisonFailureMessage(actual, expected), - false); -} - -// With this overloaded version, we allow anonymous enums to be used -// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums -// can be implicitly cast to BiggestInt. -GTEST_API_ AssertionResult CmpHelperEQ(const char* expected_expression, - const char* actual_expression, - BiggestInt expected, - BiggestInt actual); - -// The helper class for {ASSERT|EXPECT}_EQ. The template argument -// lhs_is_null_literal is true iff the first argument to ASSERT_EQ() -// is a null pointer literal. The following default implementation is -// for lhs_is_null_literal being false. -template -class EqHelper { - public: - // This templatized version is for the general case. - template - static AssertionResult Compare(const char* expected_expression, - const char* actual_expression, - const T1& expected, - const T2& actual) { - return CmpHelperEQ(expected_expression, actual_expression, expected, - actual); - } - - // With this overloaded version, we allow anonymous enums to be used - // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous - // enums can be implicitly cast to BiggestInt. - // - // Even though its body looks the same as the above version, we - // cannot merge the two, as it will make anonymous enums unhappy. - static AssertionResult Compare(const char* expected_expression, - const char* actual_expression, - BiggestInt expected, - BiggestInt actual) { - return CmpHelperEQ(expected_expression, actual_expression, expected, - actual); - } -}; - -// This specialization is used when the first argument to ASSERT_EQ() -// is a null pointer literal, like NULL, false, or 0. -template <> -class EqHelper { - public: - // We define two overloaded versions of Compare(). The first - // version will be picked when the second argument to ASSERT_EQ() is - // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or - // EXPECT_EQ(false, a_bool). - template - static AssertionResult Compare( - const char* expected_expression, - const char* actual_expression, - const T1& expected, - const T2& actual, - // The following line prevents this overload from being considered if T2 - // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr) - // expands to Compare("", "", NULL, my_ptr), which requires a conversion - // to match the Secret* in the other overload, which would otherwise make - // this template match better. - typename EnableIf::value>::type* = 0) { - return CmpHelperEQ(expected_expression, actual_expression, expected, - actual); - } - - // This version will be picked when the second argument to ASSERT_EQ() is a - // pointer, e.g. ASSERT_EQ(NULL, a_pointer). - template - static AssertionResult Compare( - const char* expected_expression, - const char* actual_expression, - // We used to have a second template parameter instead of Secret*. That - // template parameter would deduce to 'long', making this a better match - // than the first overload even without the first overload's EnableIf. - // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to - // non-pointer argument" (even a deduced integral argument), so the old - // implementation caused warnings in user code. - Secret* /* expected (NULL) */, - T* actual) { - // We already know that 'expected' is a null pointer. - return CmpHelperEQ(expected_expression, actual_expression, - static_cast(NULL), actual); - } -}; - -// A macro for implementing the helper functions needed to implement -// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste -// of similar code. -// -// For each templatized helper function, we also define an overloaded -// version for BiggestInt in order to reduce code bloat and allow -// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled -// with gcc 4. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ -template \ -AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ - const T1& val1, const T2& val2) {\ - if (val1 op val2) {\ - return AssertionSuccess();\ - } else {\ - return AssertionFailure() \ - << "Expected: (" << expr1 << ") " #op " (" << expr2\ - << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ - << " vs " << FormatForComparisonFailureMessage(val2, val1);\ - }\ -}\ -GTEST_API_ AssertionResult CmpHelper##op_name(\ - const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) - -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - -// Implements the helper function for {ASSERT|EXPECT}_NE -GTEST_IMPL_CMP_HELPER_(NE, !=); -// Implements the helper function for {ASSERT|EXPECT}_LE -GTEST_IMPL_CMP_HELPER_(LE, <=); -// Implements the helper function for {ASSERT|EXPECT}_LT -GTEST_IMPL_CMP_HELPER_(LT, < ); -// Implements the helper function for {ASSERT|EXPECT}_GE -GTEST_IMPL_CMP_HELPER_(GE, >=); -// Implements the helper function for {ASSERT|EXPECT}_GT -GTEST_IMPL_CMP_HELPER_(GT, > ); - -#undef GTEST_IMPL_CMP_HELPER_ - -// The helper function for {ASSERT|EXPECT}_STREQ. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, - const char* actual_expression, - const char* expected, - const char* actual); - -// The helper function for {ASSERT|EXPECT}_STRCASEEQ. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, - const char* actual_expression, - const char* expected, - const char* actual); - -// The helper function for {ASSERT|EXPECT}_STRNE. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2); - -// The helper function for {ASSERT|EXPECT}_STRCASENE. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2); - - -// Helper function for *_STREQ on wide strings. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, - const char* actual_expression, - const wchar_t* expected, - const wchar_t* actual); - -// Helper function for *_STRNE on wide strings. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const wchar_t* s1, - const wchar_t* s2); - -} // namespace internal - -// IsSubstring() and IsNotSubstring() are intended to be used as the -// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by -// themselves. They check whether needle is a substring of haystack -// (NULL is considered a substring of itself only), and return an -// appropriate error message when they fail. -// -// The {needle,haystack}_expr arguments are the stringified -// expressions that generated the two real arguments. -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack); -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack); -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack); - -#if GTEST_HAS_STD_WSTRING -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack); -#endif // GTEST_HAS_STD_WSTRING - -namespace internal { - -// Helper template function for comparing floating-points. -// -// Template parameter: -// -// RawType: the raw floating-point type (either float or double) -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -template -AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression, - const char* actual_expression, - RawType expected, - RawType actual) { - const FloatingPoint lhs(expected), rhs(actual); - - if (lhs.AlmostEquals(rhs)) { - return AssertionSuccess(); - } - - ::std::stringstream expected_ss; - expected_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << expected; - - ::std::stringstream actual_ss; - actual_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << actual; - - return EqFailure(expected_expression, - actual_expression, - StringStreamToString(&expected_ss), - StringStreamToString(&actual_ss), - false); -} - -// Helper function for implementing ASSERT_NEAR. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, - const char* expr2, - const char* abs_error_expr, - double val1, - double val2, - double abs_error); - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// A class that enables one to stream messages to assertion macros -class GTEST_API_ AssertHelper { - public: - // Constructor. - AssertHelper(TestPartResult::Type type, - const char* file, - int line, - const char* message); - ~AssertHelper(); - - // Message assignment is a semantic trick to enable assertion - // streaming; see the GTEST_MESSAGE_ macro below. - void operator=(const Message& message) const; - - private: - // We put our data in a struct so that the size of the AssertHelper class can - // be as small as possible. This is important because gcc is incapable of - // re-using stack space even for temporary variables, so every EXPECT_EQ - // reserves stack space for another AssertHelper. - struct AssertHelperData { - AssertHelperData(TestPartResult::Type t, - const char* srcfile, - int line_num, - const char* msg) - : type(t), file(srcfile), line(line_num), message(msg) { } - - TestPartResult::Type const type; - const char* const file; - int const line; - String const message; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); - }; - - AssertHelperData* const data_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); -}; - -} // namespace internal - -#if GTEST_HAS_PARAM_TEST -// The pure interface class that all value-parameterized tests inherit from. -// A value-parameterized class must inherit from both ::testing::Test and -// ::testing::WithParamInterface. In most cases that just means inheriting -// from ::testing::TestWithParam, but more complicated test hierarchies -// may need to inherit from Test and WithParamInterface at different levels. -// -// This interface has support for accessing the test parameter value via -// the GetParam() method. -// -// Use it with one of the parameter generator defining functions, like Range(), -// Values(), ValuesIn(), Bool(), and Combine(). -// -// class FooTest : public ::testing::TestWithParam { -// protected: -// FooTest() { -// // Can use GetParam() here. -// } -// virtual ~FooTest() { -// // Can use GetParam() here. -// } -// virtual void SetUp() { -// // Can use GetParam() here. -// } -// virtual void TearDown { -// // Can use GetParam() here. -// } -// }; -// TEST_P(FooTest, DoesBar) { -// // Can use GetParam() method here. -// Foo foo; -// ASSERT_TRUE(foo.DoesBar(GetParam())); -// } -// INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); - -template -class WithParamInterface { - public: - typedef T ParamType; - virtual ~WithParamInterface() {} - - // The current parameter value. Is also available in the test fixture's - // constructor. This member function is non-static, even though it only - // references static data, to reduce the opportunity for incorrect uses - // like writing 'WithParamInterface::GetParam()' for a test that - // uses a fixture whose parameter type is int. - const ParamType& GetParam() const { return *parameter_; } - - private: - // Sets parameter value. The caller is responsible for making sure the value - // remains alive and unchanged throughout the current test. - static void SetParam(const ParamType* parameter) { - parameter_ = parameter; - } - - // Static value used for accessing parameter during a test lifetime. - static const ParamType* parameter_; - - // TestClass must be a subclass of WithParamInterface and Test. - template friend class internal::ParameterizedTestFactory; -}; - -template -const T* WithParamInterface::parameter_ = NULL; - -// Most value-parameterized classes can ignore the existence of -// WithParamInterface, and can just inherit from ::testing::TestWithParam. - -template -class TestWithParam : public Test, public WithParamInterface { -}; - -#endif // GTEST_HAS_PARAM_TEST - -// Macros for indicating success/failure in test code. - -// ADD_FAILURE unconditionally adds a failure to the current test. -// SUCCEED generates a success - it doesn't automatically make the -// current test successful, as a test is only successful when it has -// no failure. -// -// EXPECT_* verifies that a certain condition is satisfied. If not, -// it behaves like ADD_FAILURE. In particular: -// -// EXPECT_TRUE verifies that a Boolean condition is true. -// EXPECT_FALSE verifies that a Boolean condition is false. -// -// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except -// that they will also abort the current function on failure. People -// usually want the fail-fast behavior of FAIL and ASSERT_*, but those -// writing data-driven tests often find themselves using ADD_FAILURE -// and EXPECT_* more. -// -// Examples: -// -// EXPECT_TRUE(server.StatusIsOK()); -// ASSERT_FALSE(server.HasPendingRequest(port)) -// << "There are still pending requests " << "on port " << port; - -// Generates a nonfatal failure with a generic message. -#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") - -// Generates a nonfatal failure at the given source file location with -// a generic message. -#define ADD_FAILURE_AT(file, line) \ - GTEST_MESSAGE_AT_(file, line, "Failed", \ - ::testing::TestPartResult::kNonFatalFailure) - -// Generates a fatal failure with a generic message. -#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") - -// Define this macro to 1 to omit the definition of FAIL(), which is a -// generic name and clashes with some other libraries. -#if !GTEST_DONT_DEFINE_FAIL -# define FAIL() GTEST_FAIL() -#endif - -// Generates a success with a generic message. -#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded") - -// Define this macro to 1 to omit the definition of SUCCEED(), which -// is a generic name and clashes with some other libraries. -#if !GTEST_DONT_DEFINE_SUCCEED -# define SUCCEED() GTEST_SUCCEED() -#endif - -// Macros for testing exceptions. -// -// * {ASSERT|EXPECT}_THROW(statement, expected_exception): -// Tests that the statement throws the expected exception. -// * {ASSERT|EXPECT}_NO_THROW(statement): -// Tests that the statement doesn't throw any exception. -// * {ASSERT|EXPECT}_ANY_THROW(statement): -// Tests that the statement throws an exception. - -#define EXPECT_THROW(statement, expected_exception) \ - GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_) -#define EXPECT_NO_THROW(statement) \ - GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_) -#define EXPECT_ANY_THROW(statement) \ - GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_) -#define ASSERT_THROW(statement, expected_exception) \ - GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_) -#define ASSERT_NO_THROW(statement) \ - GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_) -#define ASSERT_ANY_THROW(statement) \ - GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) - -// Boolean assertions. Condition can be either a Boolean expression or an -// AssertionResult. For more information on how to use AssertionResult with -// these macros see comments on that class. -#define EXPECT_TRUE(condition) \ - GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ - GTEST_NONFATAL_FAILURE_) -#define EXPECT_FALSE(condition) \ - GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ - GTEST_NONFATAL_FAILURE_) -#define ASSERT_TRUE(condition) \ - GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ - GTEST_FATAL_FAILURE_) -#define ASSERT_FALSE(condition) \ - GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ - GTEST_FATAL_FAILURE_) - -// Includes the auto-generated header that implements a family of -// generic predicate assertion macros. -// Copyright 2006, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. - -// This file is AUTOMATICALLY GENERATED on 09/24/2010 by command -// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! -// -// Implements a family of generic predicate assertion macros. - -#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ -#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ - -// Makes sure this header is not included before gtest.h. -#ifndef GTEST_INCLUDE_GTEST_GTEST_H_ -# error Do not include gtest_pred_impl.h directly. Include gtest.h instead. -#endif // GTEST_INCLUDE_GTEST_GTEST_H_ - -// This header implements a family of generic predicate assertion -// macros: -// -// ASSERT_PRED_FORMAT1(pred_format, v1) -// ASSERT_PRED_FORMAT2(pred_format, v1, v2) -// ... -// -// where pred_format is a function or functor that takes n (in the -// case of ASSERT_PRED_FORMATn) values and their source expression -// text, and returns a testing::AssertionResult. See the definition -// of ASSERT_EQ in gtest.h for an example. -// -// If you don't care about formatting, you can use the more -// restrictive version: -// -// ASSERT_PRED1(pred, v1) -// ASSERT_PRED2(pred, v1, v2) -// ... -// -// where pred is an n-ary function or functor that returns bool, -// and the values v1, v2, ..., must support the << operator for -// streaming to std::ostream. -// -// We also define the EXPECT_* variations. -// -// For now we only support predicates whose arity is at most 5. -// Please email googletestframework@googlegroups.com if you need -// support for higher arities. - -// GTEST_ASSERT_ is the basic statement to which all of the assertions -// in this file reduce. Don't use this in your code. - -#define GTEST_ASSERT_(expression, on_failure) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (const ::testing::AssertionResult gtest_ar = (expression)) \ - ; \ - else \ - on_failure(gtest_ar.failure_message()) - - -// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use -// this in your code. -template -AssertionResult AssertPred1Helper(const char* pred_text, - const char* e1, - Pred pred, - const T1& v1) { - if (pred(v1)) return AssertionSuccess(); - - return AssertionFailure() << pred_text << "(" - << e1 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1; -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. -// Don't use this in your code. -#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, v1),\ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use -// this in your code. -#define GTEST_PRED1_(pred, v1, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \ - #v1, \ - pred, \ - v1), on_failure) - -// Unary predicate assertion macros. -#define EXPECT_PRED_FORMAT1(pred_format, v1) \ - GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED1(pred, v1) \ - GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT1(pred_format, v1) \ - GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED1(pred, v1) \ - GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) - - - -// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use -// this in your code. -template -AssertionResult AssertPred2Helper(const char* pred_text, - const char* e1, - const char* e2, - Pred pred, - const T1& v1, - const T2& v2) { - if (pred(v1, v2)) return AssertionSuccess(); - - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2; -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. -// Don't use this in your code. -#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2),\ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use -// this in your code. -#define GTEST_PRED2_(pred, v1, v2, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \ - #v1, \ - #v2, \ - pred, \ - v1, \ - v2), on_failure) - -// Binary predicate assertion macros. -#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ - GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED2(pred, v1, v2) \ - GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \ - GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED2(pred, v1, v2) \ - GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) - - - -// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use -// this in your code. -template -AssertionResult AssertPred3Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3) { - if (pred(v1, v2, v3)) return AssertionSuccess(); - - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3; -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. -// Don't use this in your code. -#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3),\ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use -// this in your code. -#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - pred, \ - v1, \ - v2, \ - v3), on_failure) - -// Ternary predicate assertion macros. -#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ - GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED3(pred, v1, v2, v3) \ - GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \ - GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED3(pred, v1, v2, v3) \ - GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) - - - -// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use -// this in your code. -template -AssertionResult AssertPred4Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - const char* e4, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4) { - if (pred(v1, v2, v3, v4)) return AssertionSuccess(); - - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ", " - << e4 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3 - << "\n" << e4 << " evaluates to " << v4; -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. -// Don't use this in your code. -#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4),\ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use -// this in your code. -#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - #v4, \ - pred, \ - v1, \ - v2, \ - v3, \ - v4), on_failure) - -// 4-ary predicate assertion macros. -#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ - GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED4(pred, v1, v2, v3, v4) \ - GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ - GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED4(pred, v1, v2, v3, v4) \ - GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) - - - -// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use -// this in your code. -template -AssertionResult AssertPred5Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - const char* e4, - const char* e5, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4, - const T5& v5) { - if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); - - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ", " - << e4 << ", " - << e5 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3 - << "\n" << e4 << " evaluates to " << v4 - << "\n" << e5 << " evaluates to " << v5; -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. -// Don't use this in your code. -#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5),\ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use -// this in your code. -#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - #v4, \ - #v5, \ - pred, \ - v1, \ - v2, \ - v3, \ - v4, \ - v5), on_failure) - -// 5-ary predicate assertion macros. -#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ - GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \ - GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ - GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ - GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) - - - -#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ - -// Macros for testing equalities and inequalities. -// -// * {ASSERT|EXPECT}_EQ(expected, actual): Tests that expected == actual -// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2 -// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2 -// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2 -// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2 -// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2 -// -// When they are not, Google Test prints both the tested expressions and -// their actual values. The values must be compatible built-in types, -// or you will get a compiler error. By "compatible" we mean that the -// values can be compared by the respective operator. -// -// Note: -// -// 1. It is possible to make a user-defined type work with -// {ASSERT|EXPECT}_??(), but that requires overloading the -// comparison operators and is thus discouraged by the Google C++ -// Usage Guide. Therefore, you are advised to use the -// {ASSERT|EXPECT}_TRUE() macro to assert that two objects are -// equal. -// -// 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on -// pointers (in particular, C strings). Therefore, if you use it -// with two C strings, you are testing how their locations in memory -// are related, not how their content is related. To compare two C -// strings by content, use {ASSERT|EXPECT}_STR*(). -// -// 3. {ASSERT|EXPECT}_EQ(expected, actual) is preferred to -// {ASSERT|EXPECT}_TRUE(expected == actual), as the former tells you -// what the actual value is when it fails, and similarly for the -// other comparisons. -// -// 4. Do not depend on the order in which {ASSERT|EXPECT}_??() -// evaluate their arguments, which is undefined. -// -// 5. These macros evaluate their arguments exactly once. -// -// Examples: -// -// EXPECT_NE(5, Foo()); -// EXPECT_EQ(NULL, a_pointer); -// ASSERT_LT(i, array_size); -// ASSERT_GT(records.size(), 0) << "There is no record left."; - -#define EXPECT_EQ(expected, actual) \ - EXPECT_PRED_FORMAT2(::testing::internal:: \ - EqHelper::Compare, \ - expected, actual) -#define EXPECT_NE(expected, actual) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, expected, actual) -#define EXPECT_LE(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) -#define EXPECT_LT(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) -#define EXPECT_GE(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) -#define EXPECT_GT(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) - -#define GTEST_ASSERT_EQ(expected, actual) \ - ASSERT_PRED_FORMAT2(::testing::internal:: \ - EqHelper::Compare, \ - expected, actual) -#define GTEST_ASSERT_NE(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) -#define GTEST_ASSERT_LE(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) -#define GTEST_ASSERT_LT(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) -#define GTEST_ASSERT_GE(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) -#define GTEST_ASSERT_GT(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) - -// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of -// ASSERT_XY(), which clashes with some users' own code. - -#if !GTEST_DONT_DEFINE_ASSERT_EQ -# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_NE -# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_LE -# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_LT -# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_GE -# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_GT -# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) -#endif - -// C String Comparisons. All tests treat NULL and any non-NULL string -// as different. Two NULLs are equal. -// -// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 -// * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2 -// * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case -// * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case -// -// For wide or narrow string objects, you can use the -// {ASSERT|EXPECT}_??() macros. -// -// Don't depend on the order in which the arguments are evaluated, -// which is undefined. -// -// These macros evaluate their arguments exactly once. - -#define EXPECT_STREQ(expected, actual) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) -#define EXPECT_STRNE(s1, s2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) -#define EXPECT_STRCASEEQ(expected, actual) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) -#define EXPECT_STRCASENE(s1, s2)\ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) - -#define ASSERT_STREQ(expected, actual) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) -#define ASSERT_STRNE(s1, s2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) -#define ASSERT_STRCASEEQ(expected, actual) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) -#define ASSERT_STRCASENE(s1, s2)\ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) - -// Macros for comparing floating-point numbers. -// -// * {ASSERT|EXPECT}_FLOAT_EQ(expected, actual): -// Tests that two float values are almost equal. -// * {ASSERT|EXPECT}_DOUBLE_EQ(expected, actual): -// Tests that two double values are almost equal. -// * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error): -// Tests that v1 and v2 are within the given distance to each other. -// -// Google Test uses ULP-based comparison to automatically pick a default -// error bound that is appropriate for the operands. See the -// FloatingPoint template class in gtest-internal.h if you are -// interested in the implementation details. - -#define EXPECT_FLOAT_EQ(expected, actual)\ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - expected, actual) - -#define EXPECT_DOUBLE_EQ(expected, actual)\ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - expected, actual) - -#define ASSERT_FLOAT_EQ(expected, actual)\ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - expected, actual) - -#define ASSERT_DOUBLE_EQ(expected, actual)\ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - expected, actual) - -#define EXPECT_NEAR(val1, val2, abs_error)\ - EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ - val1, val2, abs_error) - -#define ASSERT_NEAR(val1, val2, abs_error)\ - ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ - val1, val2, abs_error) - -// These predicate format functions work on floating-point values, and -// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. -// -// EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0); - -// Asserts that val1 is less than, or almost equal to, val2. Fails -// otherwise. In particular, it fails if either val1 or val2 is NaN. -GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, - float val1, float val2); -GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, - double val1, double val2); - - -#if GTEST_OS_WINDOWS - -// Macros that test for HRESULT failure and success, these are only useful -// on Windows, and rely on Windows SDK macros and APIs to compile. -// -// * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr) -// -// When expr unexpectedly fails or succeeds, Google Test prints the -// expected result and the actual result with both a human-readable -// string representation of the error, if available, as well as the -// hex result code. -# define EXPECT_HRESULT_SUCCEEDED(expr) \ - EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) - -# define ASSERT_HRESULT_SUCCEEDED(expr) \ - ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) - -# define EXPECT_HRESULT_FAILED(expr) \ - EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) - -# define ASSERT_HRESULT_FAILED(expr) \ - ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) - -#endif // GTEST_OS_WINDOWS - -// Macros that execute statement and check that it doesn't generate new fatal -// failures in the current thread. -// -// * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement); -// -// Examples: -// -// EXPECT_NO_FATAL_FAILURE(Process()); -// ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; -// -#define ASSERT_NO_FATAL_FAILURE(statement) \ - GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) -#define EXPECT_NO_FATAL_FAILURE(statement) \ - GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) - -// Causes a trace (including the source file path, the current line -// number, and the given message) to be included in every test failure -// message generated by code in the current scope. The effect is -// undone when the control leaves the current scope. -// -// The message argument can be anything streamable to std::ostream. -// -// In the implementation, we include the current line number as part -// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s -// to appear in the same block - as long as they are on different -// lines. -#define SCOPED_TRACE(message) \ - ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ - __FILE__, __LINE__, ::testing::Message() << (message)) - -// Compile-time assertion for type equality. -// StaticAssertTypeEq() compiles iff type1 and type2 are -// the same type. The value it returns is not interesting. -// -// Instead of making StaticAssertTypeEq a class template, we make it a -// function template that invokes a helper class template. This -// prevents a user from misusing StaticAssertTypeEq by -// defining objects of that type. -// -// CAVEAT: -// -// When used inside a method of a class template, -// StaticAssertTypeEq() is effective ONLY IF the method is -// instantiated. For example, given: -// -// template class Foo { -// public: -// void Bar() { testing::StaticAssertTypeEq(); } -// }; -// -// the code: -// -// void Test1() { Foo foo; } -// -// will NOT generate a compiler error, as Foo::Bar() is never -// actually instantiated. Instead, you need: -// -// void Test2() { Foo foo; foo.Bar(); } -// -// to cause a compiler error. -template -bool StaticAssertTypeEq() { - (void)internal::StaticAssertTypeEqHelper(); - return true; -} - -// Defines a test. -// -// The first parameter is the name of the test case, and the second -// parameter is the name of the test within the test case. -// -// The convention is to end the test case name with "Test". For -// example, a test case for the Foo class can be named FooTest. -// -// The user should put his test code between braces after using this -// macro. Example: -// -// TEST(FooTest, InitializesCorrectly) { -// Foo foo; -// EXPECT_TRUE(foo.StatusIsOK()); -// } - -// Note that we call GetTestTypeId() instead of GetTypeId< -// ::testing::Test>() here to get the type ID of testing::Test. This -// is to work around a suspected linker bug when using Google Test as -// a framework on Mac OS X. The bug causes GetTypeId< -// ::testing::Test>() to return different values depending on whether -// the call is from the Google Test framework itself or from user test -// code. GetTestTypeId() is guaranteed to always return the same -// value, as it always calls GetTypeId<>() from the Google Test -// framework. -#define GTEST_TEST(test_case_name, test_name)\ - GTEST_TEST_(test_case_name, test_name, \ - ::testing::Test, ::testing::internal::GetTestTypeId()) - -// Define this macro to 1 to omit the definition of TEST(), which -// is a generic name and clashes with some other libraries. -#if !GTEST_DONT_DEFINE_TEST -# define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) -#endif - -// Defines a test that uses a test fixture. -// -// The first parameter is the name of the test fixture class, which -// also doubles as the test case name. The second parameter is the -// name of the test within the test case. -// -// A test fixture class must be declared earlier. The user should put -// his test code between braces after using this macro. Example: -// -// class FooTest : public testing::Test { -// protected: -// virtual void SetUp() { b_.AddElement(3); } -// -// Foo a_; -// Foo b_; -// }; -// -// TEST_F(FooTest, InitializesCorrectly) { -// EXPECT_TRUE(a_.StatusIsOK()); -// } -// -// TEST_F(FooTest, ReturnsElementCountCorrectly) { -// EXPECT_EQ(0, a_.size()); -// EXPECT_EQ(1, b_.size()); -// } - -#define TEST_F(test_fixture, test_name)\ - GTEST_TEST_(test_fixture, test_name, test_fixture, \ - ::testing::internal::GetTypeId()) - -// Use this macro in main() to run all tests. It returns 0 if all -// tests are successful, or 1 otherwise. -// -// RUN_ALL_TESTS() should be invoked after the command line has been -// parsed by InitGoogleTest(). - -#define RUN_ALL_TESTS()\ - (::testing::UnitTest::GetInstance()->Run()) - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_H_ diff --git a/Testing/Unit/GoogleTest/gtest/gtest_main.cc b/Testing/Unit/GoogleTest/gtest/gtest_main.cc deleted file mode 100644 index a09bbe0c6..000000000 --- a/Testing/Unit/GoogleTest/gtest/gtest_main.cc +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2006, Google Inc. -// 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 name of Google Inc. nor the names of its -// 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 -// OWNER 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. - -#include - -#include "gtest/gtest.h" - -GTEST_API_ int main(int argc, char **argv) { - std::cout << "Running main() from gtest_main.cc\n"; - - testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} From e773012a55827e1d918fd5e5923e4c147f10886c Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 12 Jun 2015 15:03:06 -0400 Subject: [PATCH 030/412] Adding ObjectCount measurement to ConnectedComponents filter Change-Id: I1f7d2deda7ac72e886080ed170e9376f4910a837 --- .../json/ConnectedComponentImageFilter.json | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Code/BasicFilters/json/ConnectedComponentImageFilter.json b/Code/BasicFilters/json/ConnectedComponentImageFilter.json index 9b5d948d0..4f461b839 100644 --- a/Code/BasicFilters/json/ConnectedComponentImageFilter.json +++ b/Code/BasicFilters/json/ConnectedComponentImageFilter.json @@ -18,12 +18,27 @@ "detaileddescriptionGet" : "Set/Get whether the connected components are defined strictly by face connectivity or by face+edge+vertex connectivity. Default is FullyConnectedOff. For objects that are 1 pixel wide, use FullyConnectedOn." } ], + "measurements" : [ + { + "name" : "ObjectCount", + "type" : "uint32_t", + "default" : "0u", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "After the filter is executed, holds the number of connected components." + } + ], "custom_methods" : [], "tests" : [ { "tag" : "default", "description" : "2D", "settings" : [], + "measurements_results" : [ + { + "name" : "ObjectCount", + "value" : 23 + } + ], "md5hash" : "548f5184428db10d93e3bf377dee5253", "inputs" : [ "Input/WhiteDots.png" From b33586175df5581a71471ea1fecfba8e23a72eb0 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 15 Jun 2015 10:37:26 -0400 Subject: [PATCH 031/412] Use CMAKE_POSITION_INDEPENDENT_CODE property over compiler flag The SimpelITK library almost always get linked into a shared library for the wrapped languages. So force the generation of position independent code to ensure that we can create a shared libraries with the SimpleITK libraries. Change-Id: I14883736c75f55892ae91b4416da24baa30a5cbb --- CMakeLists.txt | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 283d5f023..8bf1c934e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -291,20 +291,10 @@ endif() include(CheckCXXCompilerFlag) -# The fPIC flags is used to create position independent code. It is -# required on some systems to produce shared libraries. On Apple -# systems the flag has no effect as it is the default. On other -# platforms, this flag may enable libraries to be better shared -# between processes. Therefore, if the compiler supports it, we will -# use it. -check_cxx_compiler_flag( "-fPIC" CXX_HAS_fPIC ) -if( CXX_HAS_fPIC ) - if(NOT "${CMAKE_CXX_FLAGS}" MATCHES "-fPIC") - set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC" ) - endif() -endif( ) - +# always create position independent code so that the libraries can be +# used with shared libraries needed for language bindings. +set( CMAKE_POSITION_INDEPENDENT_CODE 1 ) #----------------------------------------------------------- # Place all checks and try compile variable for sitkConfigure.h here From 867fe6794956d60bfae41549b7cc47530c0950ab Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 15 Jun 2015 10:39:42 -0400 Subject: [PATCH 032/412] Replace superbuild fPIC with CMake property for ITK. Change-Id: I687b79b26bd94852bf3a5f8b74426efc3c73cdf9 --- SuperBuild/CMakeLists.txt | 16 ---------------- SuperBuild/External_ITK.cmake | 1 + 2 files changed, 1 insertion(+), 16 deletions(-) diff --git a/SuperBuild/CMakeLists.txt b/SuperBuild/CMakeLists.txt index ca6e9ce24..566b63d7c 100644 --- a/SuperBuild/CMakeLists.txt +++ b/SuperBuild/CMakeLists.txt @@ -5,22 +5,6 @@ project ( SuperBuildSimpleITK ) # Superbuild script #----------------------------------------------------------------------------- -# -# Global configuration -# - -# Add needed flag for gnu on linux like enviroments -if(NOT APPLE AND "x${CMAKE_CXX_COMPILER_ID}x" MATCHES "xGNUx") - if(NOT "${CMAKE_CXX_FLAGS}" MATCHES "-fPIC") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") - endif() - if(NOT "${CMAKE_C_FLAGS}" MATCHES "-fPIC") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC") - endif() -endif() - - - # Actually run the super build script set(${CMAKE_PROJECT_NAME}_DEPENDENCIES "") #Dependancies will be determined during superbuild stage. include("${CMAKE_CURRENT_SOURCE_DIR}/SuperBuild.cmake") diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 33eeda7d6..7fbd37d73 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -58,6 +58,7 @@ ExternalProject_Add(${proj} -C "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" ${ep_itk_args} ${ep_common_args} + -DCMAKE_POSITION_INDEPENDENT_CODE:BOOL=ON -DBUILD_EXAMPLES:BOOL=OFF -DBUILD_TESTING:BOOL=OFF -DBUILD_SHARED_LIBS:BOOL=${ITK_BUILD_SHARED_LIBS} From 83a9c4393e1afb5ae349c2628b28959002fd0a7d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 15 Jun 2015 10:40:09 -0400 Subject: [PATCH 033/412] Remove adding fPIC flag in language options. This is no longer needed since we use the CMake property. Change-Id: I4bcf6e414ef9138d43176def23f0795d3b4b4ecb --- CMake/sitkLanguageOptions.cmake | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/CMake/sitkLanguageOptions.cmake b/CMake/sitkLanguageOptions.cmake index d3348f5d3..647b1578a 100644 --- a/CMake/sitkLanguageOptions.cmake +++ b/CMake/sitkLanguageOptions.cmake @@ -9,17 +9,6 @@ # -# for wrapping to wrok correctly fPIC is needed on certain system. -macro(check_PIC_flag Language) - string( TOUPPER ${Language} LANGUAGE ) - if ( UNIX AND NOT APPLE AND WRAP_${LANGUAGE} ) - if ( NOT ${CMAKE_CXX_FLAGS} MATCHES "-fPIC") - message ( FATAL_ERROR "${Language} wrapping requires CMAKE_CXX_FLAGS (or equivalent) to include -fPIC and ITK built with this flag." ) - endif() - endif() -endmacro() - - # # Setup the option for each language # @@ -59,7 +48,6 @@ if(PYTHON_INCLUDE_DIR2) ) endif() option( WRAP_PYTHON "Wrap Python" ${WRAP_PYTHON_DEFAULT} ) -check_PIC_flag ( Python ) find_package ( Java COMPONENTS Development Runtime QUIET ) find_package ( JNI QUIET ) @@ -90,7 +78,6 @@ list( APPEND SITK_LANGUAGES_VARS ) option ( WRAP_JAVA "Wrap Java" ${WRAP_JAVA_DEFAULT} ) -check_PIC_flag ( Java ) find_package ( TCL QUIET ) if ( ${TCL_FOUND} ) @@ -113,7 +100,6 @@ if ( ${RUBY_FOUND} ) else ( ${RUBY_FOUND} ) set ( WRAP_RUBY_DEFAULT OFF ) endif ( ${RUBY_FOUND} ) -check_PIC_flag ( Ruby ) list( APPEND SITK_LANGUAGES_VARS RUBY_EXECUTABLE RUBY_INCLUDE_DIRS @@ -122,7 +108,6 @@ list( APPEND SITK_LANGUAGES_VARS RUBY_FOUND RUBY_INCLUDE_PATH ) option ( WRAP_RUBY "Wrap Ruby" ${WRAP_RUBY_DEFAULT} ) -check_PIC_flag ( Ruby ) find_package( CSharp QUIET ) if ( ${CSHARP_FOUND} AND NOT MINGW ) From 632cb3a5a45412ab2f6378502ea92a72396eae11 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 15 Jun 2015 11:43:10 -0400 Subject: [PATCH 034/412] Add CMake variable to specify additional lua libraries Linking to lua may require additional libraries such as readline. Change-Id: I180398147c3ffefa4aff0daeb3ee553a81c96a44 --- CMake/sitkLanguageOptions.cmake | 3 +++ Wrapping/CMakeLists.txt | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CMake/sitkLanguageOptions.cmake b/CMake/sitkLanguageOptions.cmake index 2d4defa61..5875fb6c4 100644 --- a/CMake/sitkLanguageOptions.cmake +++ b/CMake/sitkLanguageOptions.cmake @@ -40,12 +40,15 @@ else() set( WRAP_LUA_DEFAULT OFF ) endif() +SET( LUA_ADDITIONAL_LIBRARIES "" CACHE STRING "Additional libraries which may be needed for lua such as readline.") + option ( WRAP_LUA "Wrap Lua" ${WRAP_LUA_DEFAULT} ) list( APPEND SITK_LANGUAGES_VARS LUA_LIBRARIES LUA_INCLUDE_DIR LUA_VERSION_STRING + LUA_ADDITIONAL_LIBRARIES ) diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index c8cc19069..1b6919c6a 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -62,7 +62,7 @@ if ( WRAP_LUA ) set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/SimpleITKLUA_wrap.cxx PROPERTIES COMPILE_FLAGS "-w" ) add_executable ( SimpleITKLua SimpleITKLuaMain.cxx SimpleITKLUA_wrap.cxx ) - target_link_libraries ( SimpleITKLua ${SimpleITK_LIBRARIES} ${LUA_LIBRARIES} ) + target_link_libraries ( SimpleITKLua ${SimpleITK_LIBRARIES} ${LUA_LIBRARIES} ${LUA_ADDITIONAL_LIBRARIES} ) sitk_strip_target( SimpleITKLua ) endif() From 71d6db1e57f22bf0a0458601b3ff569ed1d22920 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 15 Jun 2015 11:46:26 -0400 Subject: [PATCH 035/412] Add unsigned int specifier Change-Id: I76361b454240147ff5523983d74f32c297b20508 --- Code/BasicFilters/json/ConnectedComponentImageFilter.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/BasicFilters/json/ConnectedComponentImageFilter.json b/Code/BasicFilters/json/ConnectedComponentImageFilter.json index 4f461b839..0d761512c 100644 --- a/Code/BasicFilters/json/ConnectedComponentImageFilter.json +++ b/Code/BasicFilters/json/ConnectedComponentImageFilter.json @@ -36,7 +36,7 @@ "measurements_results" : [ { "name" : "ObjectCount", - "value" : 23 + "value" : "23u" } ], "md5hash" : "548f5184428db10d93e3bf377dee5253", From ed0882ffd26bb9707b2089e0987490d2610646c8 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 15 Jun 2015 13:50:07 -0400 Subject: [PATCH 036/412] Mark GTest superbuild options as advanced Change-Id: Idd57c1bb6b48afec459b34f5172d3b22e0a8b928 --- SuperBuild/SuperBuild.cmake | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 24fcc2615..4935661e3 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -263,6 +263,7 @@ endif() # Google Test #------------------------------------------------------------------------------ option( USE_SYSTEM_GTEST "Use a pre-compiled version of GoogleTest. " OFF ) +mark_as_advanced(USE_SYSTEM_GTEST) if ( BUILD_TESTING ) if (USE_SYSTEM_GTEST) find_package( GTest REQUIRED ) @@ -270,6 +271,7 @@ if ( BUILD_TESTING ) else() include(External_GTest) set( GTEST_ROOT ${GTEST_ROOT} CACHE PATH "The root directory of the gtest install prefix" ) + mark_as_advanced(GTEST_ROOT) list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES GTest) list(APPEND SimpleITKITK_VARS GTEST_ROOT) endif() From f99cecb4201a617937956c60cec976f14baf533b Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 15 Jun 2015 14:03:07 -0400 Subject: [PATCH 037/412] Mark additional Lua variables as advanced Change-Id: I402bfb4de3ee6c0614048611906f78c56e12d8b0 --- CMake/sitkLanguageOptions.cmake | 3 ++- SuperBuild/SuperBuild.cmake | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CMake/sitkLanguageOptions.cmake b/CMake/sitkLanguageOptions.cmake index 5875fb6c4..1de477211 100644 --- a/CMake/sitkLanguageOptions.cmake +++ b/CMake/sitkLanguageOptions.cmake @@ -40,7 +40,8 @@ else() set( WRAP_LUA_DEFAULT OFF ) endif() -SET( LUA_ADDITIONAL_LIBRARIES "" CACHE STRING "Additional libraries which may be needed for lua such as readline.") +set( LUA_ADDITIONAL_LIBRARIES "" CACHE STRING "Additional libraries which may be needed for lua such as readline.") +mark_as_advanced( LUA_ADDITIONAL_LIBRARIES ) option ( WRAP_LUA "Wrap Lua" ${WRAP_LUA_DEFAULT} ) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 3c9dc80df..e9d750515 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -255,11 +255,13 @@ mark_as_advanced(USE_SYSTEM_LUA) if ( USE_SYSTEM_LUA ) find_package( LuaInterp REQUIRED 5.1 ) set( SITK_LUA_EXECUTABLE ${LUA_EXECUTABLE} CACHE PATH "Lua executable used for code generation." ) + mark_as_advanced( SITK_LUA_EXECUTABLE ) unset( LUA_EXECUTABLE CACHE ) else() include(External_Lua) list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES Lua) set( SITK_LUA_EXECUTABLE ${SITK_LUA_EXECUTABLE} CACHE PATH "Lua executable used for code generation." ) + mark_as_advanced( SITK_LUA_EXECUTABLE ) endif() #------------------------------------------------------------------------------ From 78fa2f21dd70af09685e51a7d034e225b31a9d52 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 16 Jun 2015 10:55:41 -0400 Subject: [PATCH 038/412] Correct variable name SimpleITK_VARS GTEST_ROOT was not correctly being passes. Change-Id: Ib0d63c6ea38220d7f0667de195b333a69e22c26c --- SuperBuild/SuperBuild.cmake | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 51c2ed2ea..0a3338d01 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -283,13 +283,13 @@ mark_as_advanced(USE_SYSTEM_GTEST) if ( BUILD_TESTING ) if (USE_SYSTEM_GTEST) find_package( GTest REQUIRED ) - list(APPEND SimpleITKITK_VARS GTEST_LIBRARIES GTEST_INCLUDE_DIRS GTEST_MAIN_LIBRARIES) + list(APPEND SimpleITK_VARS GTEST_LIBRARIES GTEST_INCLUDE_DIRS GTEST_MAIN_LIBRARIES) else() include(External_GTest) set( GTEST_ROOT ${GTEST_ROOT} CACHE PATH "The root directory of the gtest install prefix" ) mark_as_advanced(GTEST_ROOT) list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES GTest) - list(APPEND SimpleITKITK_VARS GTEST_ROOT) + list(APPEND SimpleITK_VARS GTEST_ROOT) endif() endif() @@ -321,14 +321,14 @@ foreach (_varName ${_varNames}) if(_varName MATCHES "^SimpleITK_" OR _varName MATCHES "^SITK_" ) if (NOT _varName MATCHES "^SITK_LANGUAGES_VARS") message( STATUS "Passing variable \"${_varName}=${${_varName}}\" to SimpleITK external project.") - list(APPEND SimpleITKITK_VARS ${_varName}) + list(APPEND SimpleITK_VARS ${_varName}) endif() endif() endforeach() VariableListToCache( SimpleITK_VARS ep_simpleitk_cache ) -VariableListToArgs( SimpleITKITK_VARS ep_simpleitk_args ) +VariableListToArgs( SimpleITK_VARS ep_simpleitk_args ) VariableListToCache( SITK_LANGUAGES_VARS ep_languages_cache ) VariableListToArgs( SITK_LANGUAGES_VARS ep_languages_args ) From 1d9ad3a00f74f6708560607e4f38df24b007cd8f Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 16 Jun 2015 11:07:58 -0400 Subject: [PATCH 039/412] Adding CMake upstream FindGTest.cmake This for form CMake: 0f927b440adbe3ecca1b8987ed8c5e442a324ff0 It contains a fix to use executable targets with gtest_add_tests function. This fix is available in v3.1.0. Change-Id: I154808d723cd3a38846ba6503255e116c3844a9c --- CMake/FindGTest.cmake | 211 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 211 insertions(+) create mode 100644 CMake/FindGTest.cmake diff --git a/CMake/FindGTest.cmake b/CMake/FindGTest.cmake new file mode 100644 index 000000000..1940b5af8 --- /dev/null +++ b/CMake/FindGTest.cmake @@ -0,0 +1,211 @@ +#.rst: +# FindGTest +# --------- +# +# Locate the Google C++ Testing Framework. +# +# Defines the following variables: +# +# :: +# +# GTEST_FOUND - Found the Google Testing framework +# GTEST_INCLUDE_DIRS - Include directories +# +# +# +# Also defines the library variables below as normal variables. These +# contain debug/optimized keywords when a debugging library is found. +# +# :: +# +# GTEST_BOTH_LIBRARIES - Both libgtest & libgtest-main +# GTEST_LIBRARIES - libgtest +# GTEST_MAIN_LIBRARIES - libgtest-main +# +# +# +# Accepts the following variables as input: +# +# :: +# +# GTEST_ROOT - (as a CMake or environment variable) +# The root directory of the gtest install prefix +# +# +# +# :: +# +# GTEST_MSVC_SEARCH - If compiling with MSVC, this variable can be set to +# "MD" or "MT" to enable searching a GTest build tree +# (defaults: "MD") +# +# +# +# Example Usage: +# +# :: +# +# enable_testing() +# find_package(GTest REQUIRED) +# include_directories(${GTEST_INCLUDE_DIRS}) +# +# +# +# :: +# +# add_executable(foo foo.cc) +# target_link_libraries(foo ${GTEST_BOTH_LIBRARIES}) +# +# +# +# :: +# +# add_test(AllTestsInFoo foo) +# +# +# +# +# +# If you would like each Google test to show up in CTest as a test you +# may use the following macro. NOTE: It will slow down your tests by +# running an executable for each test and test fixture. You will also +# have to rerun CMake after adding or removing tests or test fixtures. +# +# GTEST_ADD_TESTS(executable extra_args ARGN) +# +# :: +# +# executable = The path to the test executable +# extra_args = Pass a list of extra arguments to be passed to +# executable enclosed in quotes (or "" for none) +# ARGN = A list of source files to search for tests & test +# fixtures. Or AUTO to find them from executable target. +# +# +# +# :: +# +# Example: +# set(FooTestArgs --foo 1 --bar 2) +# add_executable(FooTest FooUnitTest.cc) +# GTEST_ADD_TESTS(FooTest "${FooTestArgs}" AUTO) + +#============================================================================= +# Copyright 2009 Kitware, Inc. +# Copyright 2009 Philip Lowman +# Copyright 2009 Daniel Blezek +# +# Distributed under the OSI-approved BSD License (the "License"); +# see accompanying file Copyright.txt for details. +# +# This software is distributed WITHOUT ANY WARRANTY; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# See the License for more information. +#============================================================================= +# (To distribute this file outside of CMake, substitute the full +# License text for the above reference.) +# +# Thanks to Daniel Blezek for the GTEST_ADD_TESTS code + +function(GTEST_ADD_TESTS executable extra_args) + if(NOT ARGN) + message(FATAL_ERROR "Missing ARGN: Read the documentation for GTEST_ADD_TESTS") + endif() + if(ARGN STREQUAL "AUTO") + # obtain sources used for building that executable + get_property(ARGN TARGET ${executable} PROPERTY SOURCES) + endif() + set(gtest_case_name_regex ".*\\( *([A-Za-z_0-9]+) *, *([A-Za-z_0-9]+) *\\).*") + set(gtest_test_type_regex "(TYPED_TEST|TEST_?[FP]?)") + foreach(source ${ARGN}) + file(READ "${source}" contents) + string(REGEX MATCHALL "${gtest_test_type_regex} *\\(([A-Za-z_0-9 ,]+)\\)" found_tests ${contents}) + foreach(hit ${found_tests}) + string(REGEX MATCH "${gtest_test_type_regex}" test_type ${hit}) + + # Parameterized tests have a different signature for the filter + if(${test_type} STREQUAL "TEST_P") + string(REGEX REPLACE ${gtest_case_name_regex} "*/\\1.\\2/*" test_name ${hit}) + elseif(${test_type} STREQUAL "TEST_F" OR ${test_type} STREQUAL "TEST") + string(REGEX REPLACE ${gtest_case_name_regex} "\\1.\\2" test_name ${hit}) + elseif(${test_type} STREQUAL "TYPED_TEST") + string(REGEX REPLACE ${gtest_case_name_regex} "\\1/*.\\2" test_name ${hit}) + else() + message(WARNING "Could not parse GTest ${hit} for adding to CTest.") + continue() + endif() + add_test(NAME ${test_name} COMMAND ${executable} --gtest_filter=${test_name} ${extra_args}) + endforeach() + endforeach() +endfunction() + +function(_gtest_append_debugs _endvar _library) + if(${_library} AND ${_library}_DEBUG) + set(_output optimized ${${_library}} debug ${${_library}_DEBUG}) + else() + set(_output ${${_library}}) + endif() + set(${_endvar} ${_output} PARENT_SCOPE) +endfunction() + +function(_gtest_find_library _name) + find_library(${_name} + NAMES ${ARGN} + HINTS + ENV GTEST_ROOT + ${GTEST_ROOT} + PATH_SUFFIXES ${_gtest_libpath_suffixes} + ) + mark_as_advanced(${_name}) +endfunction() + +# + +if(NOT DEFINED GTEST_MSVC_SEARCH) + set(GTEST_MSVC_SEARCH MD) +endif() + +set(_gtest_libpath_suffixes lib) +if(MSVC) + if(GTEST_MSVC_SEARCH STREQUAL "MD") + list(APPEND _gtest_libpath_suffixes + msvc/gtest-md/Debug + msvc/gtest-md/Release) + elseif(GTEST_MSVC_SEARCH STREQUAL "MT") + list(APPEND _gtest_libpath_suffixes + msvc/gtest/Debug + msvc/gtest/Release) + endif() +endif() + + +find_path(GTEST_INCLUDE_DIR gtest/gtest.h + HINTS + $ENV{GTEST_ROOT}/include + ${GTEST_ROOT}/include +) +mark_as_advanced(GTEST_INCLUDE_DIR) + +if(MSVC AND GTEST_MSVC_SEARCH STREQUAL "MD") + # The provided /MD project files for Google Test add -md suffixes to the + # library names. + _gtest_find_library(GTEST_LIBRARY gtest-md gtest) + _gtest_find_library(GTEST_LIBRARY_DEBUG gtest-mdd gtestd) + _gtest_find_library(GTEST_MAIN_LIBRARY gtest_main-md gtest_main) + _gtest_find_library(GTEST_MAIN_LIBRARY_DEBUG gtest_main-mdd gtest_maind) +else() + _gtest_find_library(GTEST_LIBRARY gtest) + _gtest_find_library(GTEST_LIBRARY_DEBUG gtestd) + _gtest_find_library(GTEST_MAIN_LIBRARY gtest_main) + _gtest_find_library(GTEST_MAIN_LIBRARY_DEBUG gtest_maind) +endif() + +include(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(GTest DEFAULT_MSG GTEST_LIBRARY GTEST_INCLUDE_DIR GTEST_MAIN_LIBRARY) + +if(GTEST_FOUND) + set(GTEST_INCLUDE_DIRS ${GTEST_INCLUDE_DIR}) + _gtest_append_debugs(GTEST_LIBRARIES GTEST_LIBRARY) + _gtest_append_debugs(GTEST_MAIN_LIBRARIES GTEST_MAIN_LIBRARY) + set(GTEST_BOTH_LIBRARIES ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES}) +endif() From 656357b96b9f76977511059d3391a4a1edf043ff Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 16 Jun 2015 17:31:10 -0400 Subject: [PATCH 040/412] Fix Superbuild variable GTEST_ROOT is not user editable when using the super build. And don't pass VAR list. Change-Id: I69ed8a8e6d5cdd5e5be7053f01ae48b1adc5dabf --- SuperBuild/SuperBuild.cmake | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 0a3338d01..dd3f70f7d 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -286,9 +286,7 @@ if ( BUILD_TESTING ) list(APPEND SimpleITK_VARS GTEST_LIBRARIES GTEST_INCLUDE_DIRS GTEST_MAIN_LIBRARIES) else() include(External_GTest) - set( GTEST_ROOT ${GTEST_ROOT} CACHE PATH "The root directory of the gtest install prefix" ) - mark_as_advanced(GTEST_ROOT) - list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES GTest) + set( GTEST_ROOT ${GTEST_ROOT} ) list(APPEND SimpleITK_VARS GTEST_ROOT) endif() endif() @@ -319,7 +317,9 @@ get_cmake_property( _varNames VARIABLES ) foreach (_varName ${_varNames}) if(_varName MATCHES "^SimpleITK_" OR _varName MATCHES "^SITK_" ) - if (NOT _varName MATCHES "^SITK_LANGUAGES_VARS") + if (NOT _varName MATCHES "^SITK_LANGUAGES_VARS" + AND + NOT _varName MATCHES "^SimpleITK_VARS") message( STATUS "Passing variable \"${_varName}=${${_varName}}\" to SimpleITK external project.") list(APPEND SimpleITK_VARS ${_varName}) endif() From 91edf0496449ef7898e3c5ef92504c53c2a285b7 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 16 Jun 2015 17:32:20 -0400 Subject: [PATCH 041/412] Install GTest with MSVC in expected directory The FindGTest expects GTest to be build with msvc found out of the build directory. With MSVC, the libraries are not copied for installation into the expected path. Change-Id: I038cbdfcd84e23322216eac8a6464b0468c27564 --- SuperBuild/External_GTest.cmake | 8 +++++++- SuperBuild/SuperBuild.cmake | 5 +++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/SuperBuild/External_GTest.cmake b/SuperBuild/External_GTest.cmake index 709d44aa8..e950ebe3e 100644 --- a/SuperBuild/External_GTest.cmake +++ b/SuperBuild/External_GTest.cmake @@ -22,6 +22,12 @@ set(GTEST_PATCH_COMMAND ${CMAKE_COMMAND} -E copy_if_different ${lua_source_dir}/CMakeLists.txt ) +set(${proj}_INSTALL_LIBRARY_DIR "/lib") +if( MSVC ) + set(${proj}_INSTALL_LIBRARY_DIR "/msvc/gtest") +endif() + + ExternalProject_Add(${proj} URL http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${GTEST_DOWNLOAD_SOURCE_HASH}&name=swig-${GTEST_TARGET_VERSION}.zip URL_MD5 ${GTEST_DOWNLOAD_SOURCE_HASH} @@ -34,7 +40,7 @@ ExternalProject_Add(${proj} -D BUILD_SHARED_LIBS:BOOL=OFF -D CMAKE_ARCHIVE_OUTPUT_DIRECTORY:PATH=/lib INSTALL_COMMAND - ${CMAKE_COMMAND} -E copy_directory /lib /lib + ${CMAKE_COMMAND} -E copy_directory /lib ${${proj}_INSTALL_LIBRARY_DIR} COMMAND ${CMAKE_COMMAND} -E copy_directory /include /include ) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index dd3f70f7d..f126ec6c1 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -288,6 +288,11 @@ if ( BUILD_TESTING ) include(External_GTest) set( GTEST_ROOT ${GTEST_ROOT} ) list(APPEND SimpleITK_VARS GTEST_ROOT) + if ( MSVC ) + set(GTEST_MSVC_SEARCH "MT") + list(APPEND SimpleITK_VARS GTEST_MSVC_SEARCH) + endif() + list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES GTest) endif() endif() From c07652d696265e3962bda81134594855b6fade37 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 17 Jun 2015 15:23:59 -0400 Subject: [PATCH 042/412] Install MSVC into lib directory with out prefix Since we are not using the VS project file the md/mt path option is not used, and so the libraries are installed directly into the lib directory. Change-Id: I5c8964a5035479bfc0f2abfcd1f1e1205cf7c63e --- SuperBuild/External_GTest.cmake | 10 +++++----- SuperBuild/SuperBuild.cmake | 4 ---- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/SuperBuild/External_GTest.cmake b/SuperBuild/External_GTest.cmake index e950ebe3e..160ca9101 100644 --- a/SuperBuild/External_GTest.cmake +++ b/SuperBuild/External_GTest.cmake @@ -22,12 +22,11 @@ set(GTEST_PATCH_COMMAND ${CMAKE_COMMAND} -E copy_if_different ${lua_source_dir}/CMakeLists.txt ) -set(${proj}_INSTALL_LIBRARY_DIR "/lib") -if( MSVC ) - set(${proj}_INSTALL_LIBRARY_DIR "/msvc/gtest") +set(${proj}_ARCHIVE_OUTPUT_DIRECTORY "/lib") +if (MSVC) + set(${proj}_ARCHIVE_OUTPUT_DIRECTORY "/lib/$") endif() - ExternalProject_Add(${proj} URL http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${GTEST_DOWNLOAD_SOURCE_HASH}&name=swig-${GTEST_TARGET_VERSION}.zip URL_MD5 ${GTEST_DOWNLOAD_SOURCE_HASH} @@ -37,10 +36,11 @@ ExternalProject_Add(${proj} --no-warn-unused-cli -C "${GTEST_binary_dir}/CMakeCacheInit.txt" ${ep_common_args} + -D gtest_force_shared_crt:BOOL=ON -D BUILD_SHARED_LIBS:BOOL=OFF -D CMAKE_ARCHIVE_OUTPUT_DIRECTORY:PATH=/lib INSTALL_COMMAND - ${CMAKE_COMMAND} -E copy_directory /lib ${${proj}_INSTALL_LIBRARY_DIR} + ${CMAKE_COMMAND} -E copy_directory ${${proj}_ARCHIVE_OUTPUT_DIRECTORY} /lib COMMAND ${CMAKE_COMMAND} -E copy_directory /include /include ) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index f126ec6c1..b8b947607 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -288,10 +288,6 @@ if ( BUILD_TESTING ) include(External_GTest) set( GTEST_ROOT ${GTEST_ROOT} ) list(APPEND SimpleITK_VARS GTEST_ROOT) - if ( MSVC ) - set(GTEST_MSVC_SEARCH "MT") - list(APPEND SimpleITK_VARS GTEST_MSVC_SEARCH) - endif() list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES GTest) endif() endif() From d587fcbebbeae0aa45f36e050580f2660cdf39dc Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 18 Jun 2015 11:21:12 -0400 Subject: [PATCH 043/412] Disable GTest using TR1::tuple with VS11 VS11 is limited with it's tuple depth by default. Command line definitions are added to the superbuild of GTest and the files which use gtest to not use this feature. Change-Id: I0065a924601b0ad38a3ce346c22e3943e787f2c1 --- SuperBuild/External_GTest.cmake | 17 ++++++++++++++++- Testing/Unit/CMakeLists.txt | 9 +++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/SuperBuild/External_GTest.cmake b/SuperBuild/External_GTest.cmake index 160ca9101..da70be52b 100644 --- a/SuperBuild/External_GTest.cmake +++ b/SuperBuild/External_GTest.cmake @@ -27,6 +27,21 @@ if (MSVC) set(${proj}_ARCHIVE_OUTPUT_DIRECTORY "/lib/$") endif() +set(ep_extra_args) +if(MSVC_VERSION == 1700) + # Tuples are limited by _VARIADIC_MAX in VS11. The variadic + # templates are not deep enough by default. We are not currently + # using the GTest features which require tuple, so just disable them + # and hope that upstream premanetly addresses the problem, with out + # required more CMake core for compiler issues. + set(ep_extra_args "${ep_extra_args} -D CMAKE_CXX_FLAGS=-DGTEST_HAS_TR1_TUPLE=0 ${CMAKE_CXX_FLAGS}" +endif() + +if(MSVC) + set(ep_extra_args "${ep_extra_args} -D gtest_force_shared_crt:BOOL=ON") +endif() + + ExternalProject_Add(${proj} URL http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${GTEST_DOWNLOAD_SOURCE_HASH}&name=swig-${GTEST_TARGET_VERSION}.zip URL_MD5 ${GTEST_DOWNLOAD_SOURCE_HASH} @@ -36,7 +51,7 @@ ExternalProject_Add(${proj} --no-warn-unused-cli -C "${GTEST_binary_dir}/CMakeCacheInit.txt" ${ep_common_args} - -D gtest_force_shared_crt:BOOL=ON + ${ep_extra_args} -D BUILD_SHARED_LIBS:BOOL=OFF -D CMAKE_ARCHIVE_OUTPUT_DIRECTORY:PATH=/lib INSTALL_COMMAND diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index 84c6c80c0..838a8142e 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -238,6 +238,15 @@ add_custom_target(WrappedGeneratedTests ALL DEPENDS ${WRAPPED_GENERATED_TEST_SOURCE} ) +if(MSVC_VERSION == 1700) + # Tuples are limited by _VARIADIC_MAX in VS11. The variadic + # templates are not deep enough by default. We are not currently + # using the GTest features which require tuple, so just disable them + # and hope that upstream premanetly addresses the problem, with out + # required more CMake core for compiler issues. + add_definition(-DGTEST_HAS_TR1_TUPLE=0 ) +endif() + # Add org.itk.simple.jar dependency if necessary if( WRAP_JAVA ) add_dependencies(WrappedGeneratedTests org_itk_simple_jar) From 97c120d8d786f5a0dcc7a2e697f43739a0ee9948 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 18 Jun 2015 11:31:37 -0400 Subject: [PATCH 044/412] Fix CMake syntactical errors in GTest Superbuild Change-Id: Idf2a8079cb497813d60c863cb31dfdbc8a1736b4 --- SuperBuild/External_GTest.cmake | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SuperBuild/External_GTest.cmake b/SuperBuild/External_GTest.cmake index da70be52b..c3ef31c88 100644 --- a/SuperBuild/External_GTest.cmake +++ b/SuperBuild/External_GTest.cmake @@ -28,13 +28,13 @@ if (MSVC) endif() set(ep_extra_args) -if(MSVC_VERSION == 1700) +if(MSVC_VERSION EQUAL 1700) # Tuples are limited by _VARIADIC_MAX in VS11. The variadic # templates are not deep enough by default. We are not currently # using the GTest features which require tuple, so just disable them # and hope that upstream premanetly addresses the problem, with out # required more CMake core for compiler issues. - set(ep_extra_args "${ep_extra_args} -D CMAKE_CXX_FLAGS=-DGTEST_HAS_TR1_TUPLE=0 ${CMAKE_CXX_FLAGS}" + set(ep_extra_args "${ep_extra_args} -D CMAKE_CXX_FLAGS=-DGTEST_HAS_TR1_TUPLE=0 ${CMAKE_CXX_FLAGS}") endif() if(MSVC) From 3e74f90bc09c74f014cf5f261dae2b4c972b1ad5 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 18 Jun 2015 11:49:08 -0400 Subject: [PATCH 045/412] Remove quotes around ep_extra_args Change-Id: I3a600d41f6d3ecc3023cd775586c2ff04f8c72a3 --- SuperBuild/External_GTest.cmake | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SuperBuild/External_GTest.cmake b/SuperBuild/External_GTest.cmake index c3ef31c88..9591218e9 100644 --- a/SuperBuild/External_GTest.cmake +++ b/SuperBuild/External_GTest.cmake @@ -34,11 +34,11 @@ if(MSVC_VERSION EQUAL 1700) # using the GTest features which require tuple, so just disable them # and hope that upstream premanetly addresses the problem, with out # required more CMake core for compiler issues. - set(ep_extra_args "${ep_extra_args} -D CMAKE_CXX_FLAGS=-DGTEST_HAS_TR1_TUPLE=0 ${CMAKE_CXX_FLAGS}") + set(ep_extra_args ${ep_extra_args} -D CMAKE_CXX_FLAGS=-DGTEST_HAS_TR1_TUPLE=0 ${CMAKE_CXX_FLAGS}) endif() if(MSVC) - set(ep_extra_args "${ep_extra_args} -D gtest_force_shared_crt:BOOL=ON") + set(ep_extra_args ${ep_extra_args} -D gtest_force_shared_crt:BOOL=ON) endif() From 464d82fd386c58151476dfaab04d28887592dff8 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 18 Jun 2015 14:41:39 -0400 Subject: [PATCH 046/412] Fix CMake equals syntax. Change-Id: I5d99a2e50c1b8abb6977545c912e961aa381e608 --- Testing/Unit/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index 838a8142e..0fcda4d81 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -238,7 +238,7 @@ add_custom_target(WrappedGeneratedTests ALL DEPENDS ${WRAPPED_GENERATED_TEST_SOURCE} ) -if(MSVC_VERSION == 1700) +if(MSVC_VERSION EQUAL 1700) # Tuples are limited by _VARIADIC_MAX in VS11. The variadic # templates are not deep enough by default. We are not currently # using the GTest features which require tuple, so just disable them From cf841734c2fa0678cad832d3ae172f44a8a07241 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 19 Jun 2015 07:35:17 -0400 Subject: [PATCH 047/412] More CMake fixes Careless incorrect CMake function name. Change-Id: I94990e22c720ff4c076ec3a367d96e7379b8d06b --- Testing/Unit/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index 0fcda4d81..34f2ea533 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -244,7 +244,7 @@ if(MSVC_VERSION EQUAL 1700) # using the GTest features which require tuple, so just disable them # and hope that upstream premanetly addresses the problem, with out # required more CMake core for compiler issues. - add_definition(-DGTEST_HAS_TR1_TUPLE=0 ) + add_definitions(-DGTEST_HAS_TR1_TUPLE=0 ) endif() # Add org.itk.simple.jar dependency if necessary From 1282d1a63b8aba417a57165185f41a85e809a6ef Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 23 Jun 2015 11:13:46 -0400 Subject: [PATCH 048/412] Add support to join 3d image series into 4d image Change-Id: If5c567ab0058e17ef8c34eedd8dea0c666ead6be --- .../json/JoinSeriesImageFilter.json | 2 +- Testing/Unit/sitkImage4DTests.cxx | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Code/BasicFilters/json/JoinSeriesImageFilter.json b/Code/BasicFilters/json/JoinSeriesImageFilter.json index 26f703ef9..78ad0305f 100644 --- a/Code/BasicFilters/json/JoinSeriesImageFilter.json +++ b/Code/BasicFilters/json/JoinSeriesImageFilter.json @@ -5,7 +5,7 @@ "number_of_inputs" : 1, "pixel_types" : "NonLabelPixelIDTypeList", "output_image_type" : "typename InputImageType::template Rebind::Type", - "custom_register" : "this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > ();", + "custom_register" : "this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > ();\n #ifdef SITK_4D_IMAGES\n this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > ();\n #endif", "members" : [ { "name" : "Origin", diff --git a/Testing/Unit/sitkImage4DTests.cxx b/Testing/Unit/sitkImage4DTests.cxx index ed8937991..cc25536be 100644 --- a/Testing/Unit/sitkImage4DTests.cxx +++ b/Testing/Unit/sitkImage4DTests.cxx @@ -32,6 +32,8 @@ #include "sitkRealAndImaginaryToComplexImageFilter.h" #include "sitkImportImageFilter.h" +#include "sitkJoinSeriesImageFilter.h" + #include #include "itkImage.h" @@ -536,3 +538,19 @@ TEST( IO, Image4D ) EXPECT_EQ ( sitk::Hash( vectorImage ), sitk::Hash( vectorImageRead ) ); } + + +TEST(Image4D, JoinSeriesImageFilter) +{ + std::vector size(3); + size[0] = 10; + size[1] = 11; + size[2] = 12; + + sitk::Image img = sitk::Image( size, sitk::sitkUInt8 ); + + sitk::Image out = sitk::JoinSeries(img, img, img); + + ASSERT_EQ ( out.GetDimension(), 4 ); + EXPECT_EQ ( out.GetSize()[3], 3 ); +} From 6605c48c001725ab045325e45aa351e328c33e8c Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 17 Jul 2015 10:11:06 -0400 Subject: [PATCH 049/412] Update ITK superbuild version to 4.8 release Change-Id: I74e731b70f4e3dba9b31a1196e4fad7cec5c527b --- SuperBuild/External_ITK.cmake | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 7fbd37d73..74537db30 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY git://itk.org/ITK.git) # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG 0ccdf6f19d36b812c77bfc4fa4ff9dfd6243ac66) # after v4.7.2 release +set(ITK_TAG_COMMAND GIT_TAG v4.8.0) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) @@ -90,5 +90,5 @@ ExternalProject_Add(${proj} ExternalProject_Get_Property(ITK install_dir) -set(ITK_DIR "${install_dir}/lib/cmake/ITK-4.7" ) -set(WrapITK_DIR "${install_dir}/lib/cmake/ITK-4.7/WrapITK") +set(ITK_DIR "${install_dir}/lib/cmake/ITK-4.8" ) +set(WrapITK_DIR "${install_dir}/lib/cmake/ITK-4.8/WrapITK") From 75cbe89d75f591d5fbe232735e68a35418b07296 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 17 Jul 2015 15:15:20 -0400 Subject: [PATCH 050/412] COMP: Fix JoinSeries with 4DImage test The type of GTest didn't match, the others of the class. Change-Id: I1f04764069bb1c9cc743e2c8cd861e0ebafccc19 --- Testing/Unit/sitkImage4DTests.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Testing/Unit/sitkImage4DTests.cxx b/Testing/Unit/sitkImage4DTests.cxx index cc25536be..40ee7889d 100644 --- a/Testing/Unit/sitkImage4DTests.cxx +++ b/Testing/Unit/sitkImage4DTests.cxx @@ -540,7 +540,7 @@ TEST( IO, Image4D ) } -TEST(Image4D, JoinSeriesImageFilter) +TEST_F(Image4D, JoinSeriesImageFilter) { std::vector size(3); size[0] = 10; From d890c6744bbec0cc7c91821f4276ee2f71b5f60b Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 17 Jul 2015 15:16:21 -0400 Subject: [PATCH 051/412] Add support to extract 3d image from 4d. Change-Id: I1c0dc886caaa47cd887b4e81fc2ba25aac62efed --- .../BasicFilters/json/ExtractImageFilter.json | 9 ++++---- Testing/Unit/sitkImage4DTests.cxx | 23 +++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/Code/BasicFilters/json/ExtractImageFilter.json b/Code/BasicFilters/json/ExtractImageFilter.json index 947c1185b..24634ac36 100644 --- a/Code/BasicFilters/json/ExtractImageFilter.json +++ b/Code/BasicFilters/json/ExtractImageFilter.json @@ -3,14 +3,15 @@ "template_code_filename" : "ImageFilter", "template_test_filename" : "ImageFilter", "number_of_inputs" : 1, - "doc" : "Extract image filter extracts a 2D image from a 2D or 3D image. If the same dimension output is required then the RegionOfInterestFilter should be used.", + "doc" : "Extract image filter extracts a 2D image from a 2D or 3D image and a 3D image from a 4D image. If the same dimension output is required then the RegionOfInterestFilter should be used.", "pixel_types" : "NonLabelPixelIDTypeList", - "filter_type" : "itk::ExtractImageFilter::Type >", + "filter_type" : "itk::ExtractImageFilter::Type >", + "custom_register" : " this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 4 > ();\n this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > ();\n this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > ();", "members" : [ { "name" : "Size", "type" : "unsigned int", - "default" : "std::vector(3, 1)", + "default" : "std::vector(4, 1)", "dim_vec" : 1, "itk_type" : "typename InputImageType::SizeType", "briefdescriptionSet" : "", @@ -22,7 +23,7 @@ { "name" : "Index", "type" : "int", - "default" : "std::vector(3, 0)", + "default" : "std::vector(4, 0)", "dim_vec" : 1, "itk_type" : "typename InputImageType::IndexType", "briefdescriptionSet" : "", diff --git a/Testing/Unit/sitkImage4DTests.cxx b/Testing/Unit/sitkImage4DTests.cxx index 40ee7889d..7846dd7cc 100644 --- a/Testing/Unit/sitkImage4DTests.cxx +++ b/Testing/Unit/sitkImage4DTests.cxx @@ -33,6 +33,7 @@ #include "sitkImportImageFilter.h" #include "sitkJoinSeriesImageFilter.h" +#include "sitkExtractImageFilter.h" #include @@ -554,3 +555,25 @@ TEST_F(Image4D, JoinSeriesImageFilter) ASSERT_EQ ( out.GetDimension(), 4 ); EXPECT_EQ ( out.GetSize()[3], 3 ); } + +TEST_F(Image4D, ExtractImageFilter) +{ + std::vector size(4); + size[0] = 10; + size[1] = 11; + size[2] = 12; + size[3] = 13; + + sitk::Image img = sitk::Image( size, sitk::sitkUInt8 ); + + std::vector extractSize(4); + extractSize[0] = 10; + extractSize[1] = 11; + extractSize[2] = 0; + extractSize[3] = 13; + + sitk::Image out = sitk::Extract(img, extractSize); + + ASSERT_EQ ( out.GetDimension(), 3 ); + EXPECT_EQ ( out.GetSize()[3], 13 ); +} From 42d7420021a9576ce45bc95124953fbfe5cffe98 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 20 Jul 2015 14:52:11 -0400 Subject: [PATCH 052/412] Require libraries when a wrapping for a language is enabled At the Superbuild level when wrapping for a language was enabled, the requirements for the language were not marked as required. Not when a language is enabled the cmake package is required. Change-Id: Ibc5e83fd1342b3330ca7196b183f6c4c09fa80fc --- CMake/sitkLanguageOptions.cmake | 47 +++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/CMake/sitkLanguageOptions.cmake b/CMake/sitkLanguageOptions.cmake index 623f9000e..42f95e1d7 100644 --- a/CMake/sitkLanguageOptions.cmake +++ b/CMake/sitkLanguageOptions.cmake @@ -12,7 +12,9 @@ # # Setup the option for each language # -if (NOT WRAP_LUA) +if (DEFINED WRAP_LUA AND WRAP_LUA) + set(_QUIET "REQUIRED") +else() set(_QUIET "QUIET") endif() if (CMAKE_VERSION VERSION_LESS "3") @@ -42,13 +44,16 @@ list( APPEND SITK_LANGUAGES_VARS ) -find_package ( PythonInterp QUIET) # If you're not using python or it's the first time, be quiet -if (NOT WRAP_PYTHON) +if (DEFINED WRAP_PYTHON AND WRAP_PYTHON) + set(_QUIET "REQUIRED") +else() set(_QUIET "QUIET") endif() +find_package ( PythonInterp ${_QUIET}) + find_package ( PythonLibs ${PYTHON_VERSION_STRING} EXACT ${_QUIET} ) if (PYTHON_VERSION_STRING VERSION_LESS 2.6) @@ -77,8 +82,14 @@ if(PYTHON_INCLUDE_DIR2) endif() option( WRAP_PYTHON "Wrap Python" ${WRAP_PYTHON_DEFAULT} ) -find_package ( Java COMPONENTS Development Runtime QUIET ) -find_package ( JNI QUIET ) +if (DEFINED WRAP_JAVA AND WRAP_JAVA) + set(_QUIET "REQUIRED") +else() + set(_QUIET "QUIET") +endif() + +find_package ( Java COMPONENTS Development Runtime ${_QUIET} ) +find_package ( JNI ${_QUIET} ) if ( ${JAVA_FOUND} AND ${JNI_FOUND} ) set( WRAP_JAVA_DEFAULT ON ) else ( ${JAVA_FOUND} AND ${JNI_FOUND} ) @@ -107,7 +118,14 @@ list( APPEND SITK_LANGUAGES_VARS ) option ( WRAP_JAVA "Wrap Java" ${WRAP_JAVA_DEFAULT} ) -find_package ( TCL QUIET ) + +if (DEFINED WRAP_TCL AND WRAP_TCL) + set(_QUIET "REQUIRED") +else() + set(_QUIET "QUIET") +endif() + +find_package ( TCL ${_QUIET} ) if ( ${TCL_FOUND} ) set ( WRAP_TCL_DEFAULT ON ) else ( ${TCL_FOUND} ) @@ -137,7 +155,14 @@ list( APPEND SITK_LANGUAGES_VARS RUBY_INCLUDE_PATH ) option ( WRAP_RUBY "Wrap Ruby" ${WRAP_RUBY_DEFAULT} ) -find_package( CSharp QUIET ) + +if (DEFINED WRAP_CSHARP AND WRAP_CSHARP) + set(_QUIET "REQUIRED") +else() + set(_QUIET "QUIET") +endif() + +find_package( CSharp ${_QUIET} ) if ( ${CSHARP_FOUND} AND NOT MINGW ) set ( WRAP_CSHARP_DEFAULT ON ) else () @@ -150,7 +175,13 @@ list( APPEND SITK_LANGUAGES_VARS ) option ( WRAP_CSHARP "Wrap C#" ${WRAP_CSHARP_DEFAULT} ) -find_package(R QUIET) +if (DEFINED WRAP_R AND WRAP_R) + set(_QUIET "REQUIRED") +else() + set(_QUIET "QUIET") +endif() + +find_package(R ${_QUIET}) if ( ${R_FOUND} AND NOT WIN32 ) set ( WRAP_R_DEFAULT ON ) else( ) From 8956f31ee189a5cd345eae7aa871b04a86565764 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 22 Jul 2015 15:14:13 -0400 Subject: [PATCH 053/412] Update shape statistics to always use int64_t for labelmap type. This reduces the permutations of instantiated filters and maintains compatibility with the exposed label index type. Change-Id: Iaf46dd852df78b5877629b7330b2d55d7c49febf --- Code/BasicFilters/json/LabelShapeStatisticsImageFilter.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/BasicFilters/json/LabelShapeStatisticsImageFilter.json b/Code/BasicFilters/json/LabelShapeStatisticsImageFilter.json index 8b9a18955..4ef1f55ed 100644 --- a/Code/BasicFilters/json/LabelShapeStatisticsImageFilter.json +++ b/Code/BasicFilters/json/LabelShapeStatisticsImageFilter.json @@ -6,7 +6,7 @@ "number_of_inputs" : 1, "doc" : "Docs", "pixel_types" : "IntegerPixelIDTypeList", - "filter_type" : "itk::LabelImageToShapeLabelMapFilter", + "filter_type" : "itk::LabelImageToShapeLabelMapFilter > >", "no_procedure" : true, "no_return_image" : true, "include_files" : [ From b7c0143fcbc089a396dbf3b8e73006902127b141 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 23 Jul 2015 15:45:59 -0400 Subject: [PATCH 054/412] Fix finding lua executable when not explicitly set. When the SITK_LUA_EXECUTABLE was not explicitly set, the executable was not search for. Remove the variable evaluation, to allow CMake to determine if the variable exists. This allows the initial value of SITK_LUA_EXECUTABLE to be set, when not explicitly set ( as the superbuild does ). Remove unconditional find to preserve the lua version used for the target for wrapping. Change-Id: I7040fecd8f78db020d8a6ce688fcfc62ca6b54c5 --- CMake/generate_filter_source.cmake | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/CMake/generate_filter_source.cmake b/CMake/generate_filter_source.cmake index 54f76c3e6..28eb147c2 100644 --- a/CMake/generate_filter_source.cmake +++ b/CMake/generate_filter_source.cmake @@ -1,7 +1,5 @@ -find_package( LuaInterp REQUIRED 5.1 ) - -if ( NOT ${SITK_LUA_EXECUTABLE} ) +if ( NOT SITK_LUA_EXECUTABLE ) find_package( LuaInterp REQUIRED 5.1 ) set( SITK_LUA_EXECUTABLE ${LUA_EXECUTABLE} CACHE PATH "Lua executable used for code generation." ) unset( LUA_EXECUTABLE CACHE ) From 185ec8e94f102e44c2d802b45ae130d22f00b6be Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 23 Jul 2015 15:48:00 -0400 Subject: [PATCH 055/412] Adding wrapping for LabelIntensityStatisticsImageFilter Wrap the itk filter LabelImageToStatisticsLabelMapFilter as LabelIntensityStatisticsImageFilter, giving the interface of the LabelStatisticsImageFilter to these statistics. Change-Id: I2f50e8e54d7888d92fd7ac10f2d5c4018a778cb2 --- .../LabelIntensityStatisticsImageFilter.json | 735 ++++++++++++++++++ 1 file changed, 735 insertions(+) create mode 100644 Code/BasicFilters/json/LabelIntensityStatisticsImageFilter.json diff --git a/Code/BasicFilters/json/LabelIntensityStatisticsImageFilter.json b/Code/BasicFilters/json/LabelIntensityStatisticsImageFilter.json new file mode 100644 index 000000000..67376e4c4 --- /dev/null +++ b/Code/BasicFilters/json/LabelIntensityStatisticsImageFilter.json @@ -0,0 +1,735 @@ +{ + "name" : "LabelIntensityStatisticsImageFilter", + "itk_name" : "LabelImageToStatisticsLabelMapFilter", + "template_code_filename" : "DualImageFilter", + "template_test_filename" : "ImageFilter", + "number_of_inputs" : 0, + "doc" : "Docs", + "pixel_types" : "IntegerPixelIDTypeList", + "pixel_types2" : "BasicPixelIDTypeList", + "filter_type" : "itk::LabelImageToStatisticsLabelMapFilter > >", + "no_procedure" : true, + "no_return_image" : true, + "include_files" : [], + "inputs" : [ + { + "name" : "Image", + "type" : "Image" + }, + { + "name" : "FeatureImage", + "type" : "Image", + "custom_itk_cast" : "filter->SetFeatureImage( this->CastImageToITK(*inFeatureImage) );" + } + ], + "members" : [ + { + "name" : "BackgroundValue", + "type" : "double", + "default" : "0", + "doc" : "", + "pixeltype" : "Output", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::NonpositiveMin() .", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::NonpositiveMin() ." + }, + { + "name" : "ComputeFeretDiameter", + "type" : "bool", + "default" : "false", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set/Get whether the maximum Feret diameter should be computed or not. The defaut value is false, because of the high computation time required.", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Set/Get whether the maximum Feret diameter should be computed or not. The defaut value is false, because of the high computation time required." + }, + { + "name" : "ComputePerimeter", + "type" : "bool", + "default" : "true", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set/Get whether the perimeter should be computed or not. The defaut value is false, because of the high computation time required.", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Set/Get whether the perimeter should be computed or not. The defaut value is false, because of the high computation time required." + }, + { + "name" : "NumberOfBins", + "type" : "uint32_t", + "default" : "128", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set/Get the number of bins in the histogram. Note that the histogram is used to compute the median value, and that this option may have an effect on the value of the median.", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Set/Get the number of bins in the histogram. Note that the histogram is used to compute the median value, and that this option may have an effect on the value of the median." + } + ], + "custom_methods" : [ + { + "name" : "HasLabel", + "doc" : "Does the specified label exist? Can only be called after a call a call to Update().", + "return_type" : "double", + "parameters" : [ + { + "type" : "int64_t", + "var_name" : "label" + } + ], + "body" : "return std::find(m_Labels.begin(),m_Labels.end(), label) != m_Labels.end();" + }, + { + "name" : "GetNumberOfLabels", + "doc" : "Return the number of labels after execution.", + "return_type" : "uint64_t", + "body" : "return m_Labels.size();" + } + ], + "measurements" : [ + { + "name" : "BoundingBox", + "type" : "std::vector", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "custom_cast" : "sitkITKImageRegionToSTL(value)", + "label_map" : true + }, + { + "name" : "Centroid", + "type" : "std::vector", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "custom_cast" : "sitkITKVectorToSTL(value)", + "label_map" : true + }, + { + "name" : "Elongation", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "EquivalentEllipsoidDiameter", + "type" : "std::vector", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "custom_cast" : "sitkITKVectorToSTL(value)", + "label_map" : true + }, + { + "name" : "EquivalentSphericalPerimeter", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "EquivalentSphericalRadius", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "FeretDiameter", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "Flatness", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "Labels", + "type" : "std::vector", + "custom_itk_cast" : "const std::vector tempLabels = filter->GetOutput()->GetLabels();\n this->m_Labels = std::vector(tempLabels.begin(), tempLabels.end());", + "default" : "std::vector()" + }, + { + "name" : "NumberOfPixels", + "type" : "uint64_t", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "NumberOfPixelsOnBorder", + "type" : "uint64_t", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "Perimeter", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "PerimeterOnBorder", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "PerimeterOnBorderRatio", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "PhysicalSize", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "PrincipalAxes", + "type" : "std::vector", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "custom_cast" : "std::vector(value[0], value[T::RowDimensions-1]+T::ColumnDimensions)", + "label_map" : true + }, + { + "name" : "PrincipalMoments", + "type" : "std::vector", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "custom_cast" : "sitkITKVectorToSTL(value)", + "label_map" : true + }, + { + "name" : "Roundness", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "CenterOfGravity", + "type" : "std::vector", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "custom_cast" : "sitkITKVectorToSTL(value)", + "label_map" : true + }, + { + "name" : "Kurtosis", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "Maximum", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "MaximumIndex", + "type" : "std::vector", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "custom_cast" : "sitkITKVectorToSTL(value)", + "label_map" : true + }, + { + "name" : "Mean", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "Median", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "Minimum", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "MinimumIndex", + "type" : "std::vector", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "custom_cast" : "sitkITKVectorToSTL(value)", + "label_map" : true + }, + { + "name" : "Skewness", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "StandardDeviation", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "Sum", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "Variance", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "WeightedElongation", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "WeightedFlatness", + "type" : "double", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "label_map" : true + }, + { + "name" : "WeightedPrincipalAxes", + "type" : "std::vector", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "custom_cast" : "std::vector(value[0], value[T::RowDimensions-1]+T::ColumnDimensions)", + "label_map" : true + }, + { + "name" : "WeightedPrincipalMoments", + "type" : "std::vector", + "no_print" : true, + "active" : true, + "parameters" : [ + { + "name" : "label", + "type" : "int64_t" + } + ], + "custom_cast" : "sitkITKVectorToSTL(value)", + "label_map" : true + } + ], + "tests" : [ + { + "tag" : "cthead1", + "description" : "cthead1 with defaults", + "settings" : [], + "inputs" : [ + "Input/2th_cthead1.mha", + "Input/cthead1.png" + ], + "measurements_results" : [ + { + "name" : "Elongation", + "value" : 1.1422985238962327, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + }, + { + "name" : "EquivalentSphericalPerimeter", + "value" : 194.29697897008242, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + }, + { + "name" : "EquivalentSphericalRadius", + "value" : 30.923324630910653, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + }, + { + "name" : "FeretDiameter", + "value" : 0, + "parameters" : [ + "1" + ] + }, + { + "name" : "Flatness", + "value" : 1.1422985238962327, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + }, + { + "name" : "NumberOfLabels", + "value" : "2u" + }, + { + "name" : "NumberOfPixels", + "value" : "24139u", + "parameters" : [ + "1" + ] + }, + { + "name" : "NumberOfPixelsOnBorder", + "value" : "0u", + "parameters" : [ + "1" + ] + }, + { + "name" : "Perimeter", + "value" : 1254.360759871071, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + }, + { + "name" : "PerimeterOnBorder", + "value" : 0, + "parameters" : [ + "1" + ] + }, + { + "name" : "PerimeterOnBorderRatio", + "value" : 0, + "parameters" : [ + "1" + ] + }, + { + "name" : "PhysicalSize", + "value" : 3004.1542777485397, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + }, + { + "name" : "Roundness", + "value" : 0.15489720755458994, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + }, + { + "name" : "Kurtosis", + "value" : 5.491040986144835, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + }, + { + "name" : "Maximum", + "value" : 199, + "parameters" : [ + "1" + ] + }, + { + "name" : "Mean", + "value" : 138.56282364638136, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + }, + { + "name" : "Mean", + "value" : 244.31961722488037, + "tolerance" : 1e-08, + "parameters" : [ + "2" + ] + }, + { + "name" : "Median", + "value" : 136.46484375, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + }, + { + "name" : "Minimum", + "value" : 100, + "parameters" : [ + "1" + ] + }, + { + "name" : "Skewness", + "value" : 1, + "tolerance" : 1.8728484943852783, + "parameters" : [ + "1" + ] + }, + { + "name" : "StandardDeviation", + "value" : 14.051474145970603, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + }, + { + "name" : "Sum", + "value" : 3344768, + "parameters" : [ + "1" + ] + }, + { + "name" : "Variance", + "value" : 197.44392567488032, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + }, + { + "name" : "WeightedElongation", + "value" : 1.1454453590786724, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + }, + { + "name" : "WeightedFlatness", + "value" : 1.1454453590786724, + "tolerance" : 1e-08, + "parameters" : [ + "1" + ] + } + ] + } + ], + "briefdescription" : "a convenient class to convert a label image to a label map and valuate the statistics attributes at once", + "detaileddescription" : "\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see StatisticsLabelObject , LabelStatisticsOpeningImageFilter , LabelStatisticsOpeningImageFilter" +} From a979b0191c2552651eb0ce18abcd6fc41ed2d185 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Tue, 28 Jul 2015 15:19:55 -0400 Subject: [PATCH 056/412] Fix leading space problem in doxy2swig.py The script doxy2swig.py has a method space_parse that outputs a space. We don't want this to happen at the beginning of a new line, so check that the previous character was not a newline. Change-Id: I45d67eaad0c3870b03d6456f89d1ffa4c70a74fd --- Utilities/Doxygen/doxy2swig.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Utilities/Doxygen/doxy2swig.py b/Utilities/Doxygen/doxy2swig.py index f37e49186..83a7ba4a7 100755 --- a/Utilities/Doxygen/doxy2swig.py +++ b/Utilities/Doxygen/doxy2swig.py @@ -24,8 +24,9 @@ # This version of the script originated from ITK/Wrapping/Generators/Doc/doxy2swig.py. # My mods: -# self.multi is always 1 (0 was cutting lines improperly) -# added self.java to enable output for JavaDocs +# self.multi is always 1 (0 was cutting lines improperly). +# added self.java to enable output for JavaDocs. +# space_parse doesn't output a space at the beginning of a new line. # # Dave Chen @@ -181,7 +182,11 @@ def generic_parse(self, node, pad=0): self.add_text('\n') def space_parse(self, node): - self.add_text(' ') + """ Only output a space if the last character outputed was not a new line. + I.e., don't allow a line to lead with a space. + """ + if len(self.pieces) and self.pieces[-1][-1] != '\n': + self.add_text(' ') self.generic_parse(node) do_ref = space_parse From 1710ac5464bd3960bdfaa689f865a900744a4c6d Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Wed, 29 Jul 2015 16:43:43 -0400 Subject: [PATCH 057/412] Updated space_parse with a noLeadingSpace flag There is now a flag that tells the space_parse method to enable or disable the omit a leading space option. Be default the flag is true, i.e. leading spaces are omitted. In the case of a "See" node, the flag is set to False before the nodes children are traversed. Afterwards, the flag is set back to True. The effect is that children of the See node do get a leading space, indenting them 1 space. Change-Id: I1d0a92c2231705d8d1e40a4b67acb9eff6b9737d --- Utilities/Doxygen/doxy2swig.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/Utilities/Doxygen/doxy2swig.py b/Utilities/Doxygen/doxy2swig.py index 83a7ba4a7..6ec25866f 100755 --- a/Utilities/Doxygen/doxy2swig.py +++ b/Utilities/Doxygen/doxy2swig.py @@ -24,9 +24,8 @@ # This version of the script originated from ITK/Wrapping/Generators/Doc/doxy2swig.py. # My mods: -# self.multi is always 1 (0 was cutting lines improperly). -# added self.java to enable output for JavaDocs. -# space_parse doesn't output a space at the beginning of a new line. +# self.multi is always 1 (0 was cutting lines improperly) +# added self.java to enable output for JavaDocs # # Dave Chen @@ -89,6 +88,13 @@ def __init__(self, src, javaFlag=0): 'basecompoundref') #self.generics = [] + """ flag to enable/disable printing a space in the space_parse method. + if True, space_parse will not print a space if it is at the start + of a new line. True by default. Only disabled for a node + with kind=="see". + """ + self.noLeadingSpace = True + def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. @@ -185,10 +191,14 @@ def space_parse(self, node): """ Only output a space if the last character outputed was not a new line. I.e., don't allow a line to lead with a space. """ - if len(self.pieces) and self.pieces[-1][-1] != '\n': - self.add_text(' ') + if self.noLeadingSpace: + if len(self.pieces) and self.pieces[-1][-1] != '\n': + self.add_text(' ') + else: + self.add_text(' ') self.generic_parse(node) + # The handlers for all these node types get mapped to a space do_ref = space_parse do_ulink = space_parse do_emphasis = space_parse @@ -326,7 +336,9 @@ def do_simplesect(self, node): elif kind == 'see': self.add_text('\n') self.add_text('See:') + self.noLeadingSpace = False self.generic_parse(node) + self.noLeadingSpace = True else: self.generic_parse(node) From 4c7f7f31333db2178b829f1d691297be69727682 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 30 Jul 2015 14:27:34 -0400 Subject: [PATCH 058/412] Change default of SimpleITK_PYTHON_THREADS to ON This will enable the default build of SimpleITK to unlock the GIL when entering SimpleITK Code. Change-Id: I3dfc295223f36f37ec3668cefe9d4539f6ff5b50 --- Wrapping/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index 1b6919c6a..45fc79b59 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -75,7 +75,7 @@ if ( WRAP_PYTHON ) find_package ( PythonInterp REQUIRED ) include_directories ( ${PYTHON_INCLUDE_DIR} ${SimpleITK_SOURCE_DIR}/Wrapping ) - option ( SimpleITK_PYTHON_THREADS "Enable threaded python usage by unlocking the GIL." OFF ) + option ( SimpleITK_PYTHON_THREADS "Enable threaded python usage by unlocking the GIL." ON ) mark_as_advanced( SimpleITK_PYTHON_THREADS ) option ( SimpleITK_PYTHON_WHEEL "Add building of python wheels to the dist target." OFF ) mark_as_advanced( SimpleITK_PYTHON_WHEEL ) From 7e0d2e25b8e4fa68a247f7c33ed1538cb3e2a076 Mon Sep 17 00:00:00 2001 From: Dave Chen Date: Thu, 30 Jul 2015 15:58:12 -0400 Subject: [PATCH 059/412] Regenerated the .i files JavaDoc.i and PythonDocstrings.i were regenerated with the new version of doxy2swig.py that eliminates the leading space problem. These leading spaces were causing problems with swig. --- Wrapping/JavaDoc.i | 364 +++++++++++++++++++----------------- Wrapping/PythonDocstrings.i | 353 +++++++++++++++++----------------- 2 files changed, 374 insertions(+), 343 deletions(-) diff --git a/Wrapping/JavaDoc.i b/Wrapping/JavaDoc.i index d5bbb5727..dd8f6e137 100644 --- a/Wrapping/JavaDoc.i +++ b/Wrapping/JavaDoc.i @@ -10,7 +10,7 @@ C++ includes: itkBitwiseNotFunctor.h %typemap(javaimports) itk::Functor::DivFloor "/** - Cast arguments to double, performs division then takes the floor. +Cast arguments to double, performs division then takes the floor. C++ includes: itkDivideFloorFunctor.h */" @@ -149,7 +149,7 @@ public "; %javamethodmodifiers itk::SliceImageFilter::GenerateOutputInformation "/** virtual void itk::SliceImageFilter< TInputImage, TOutputImage >::GenerateOutputInformation() - SliceImageFilter produces an image which is a different resolution and with a +SliceImageFilter produces an image which is a different resolution and with a different pixel spacing than its input image. See: ProcessObject::GenerateOutputInformaton() @@ -1157,7 +1157,7 @@ iterative relaxation process of an estimated ND surface. The surface is described implicitly as the zero level set of a volume $ \\\\phi $ and allowed to deform under curvature flow. A set of contraints is imposed on this movement as follows: - \\\\[ u_{i,j,k}^{n+1} = \\\\left\\\\{ \\\\begin{array}{ll} +\\\\[ u_{i,j,k}^{n+1} = \\\\left\\\\{ \\\\begin{array}{ll} \\\\mbox{max} (u_{i,j,k}^{n} + \\\\Delta t H_{i,j,k}^{n}, 0) & \\\\mbox{\\\\f$B_{i,j,k} = 1\\\\f$} \\\\\\\\ \\\\mbox{min} (u_{i,j,k}^{n} + \\\\Delta t H_{i,j,k}^{n}, 0) & @@ -1800,7 +1800,7 @@ public "; %typemap(javaimports) itk::simple::BSplineTransformInitializerFilter "/** - BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such +BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such that it has a physically consistent definition. It sets the transform domain origin, physical dimensions and direction from information obtained from the image. It also sets the mesh size if asked to do so @@ -2356,7 +2356,7 @@ public "; Labels the pixels on the border of the objects in a binary image. - BinaryContourImageFilter takes a binary image as input, where the pixels in the objects are +BinaryContourImageFilter takes a binary image as input, where the pixels in the objects are the pixels with a value equal to ForegroundValue. Only the pixels on the contours of the objects are kept. The pixels not on the border are changed to BackgroundValue. @@ -2364,7 +2364,7 @@ changed to BackgroundValue. The connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours. - http://hdl.handle.net/1926/1352 +http://hdl.handle.net/1926/1352 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -2516,7 +2516,7 @@ public "; Fast binary dilation. - BinaryDilateImageFilter is a binary dilation morphologic operation. This implementation is +BinaryDilateImageFilter is a binary dilation morphologic operation. This implementation is based on the papers: L.Vincent \"Morphological transformations of binary images with @@ -2698,7 +2698,7 @@ public "; Fast binary erosion. - BinaryErodeImageFilter is a binary erosion morphologic operation. This implementation is +BinaryErodeImageFilter is a binary erosion morphologic operation. This implementation is based on the papers: L.Vincent \"Morphological transformations of binary images with @@ -2881,7 +2881,7 @@ public "; Remove holes not connected to the boundary of the image. - BinaryFillholeImageFilter fills holes in a binary image. +BinaryFillholeImageFilter fills holes in a binary image. Geodesic morphology and the Fillhole algorithm is described in Chapter 6 of Pierre Soille's book \"Morphological Image Analysis: Principles @@ -3012,7 +3012,7 @@ public "; Remove the objects not connected to the boundary of the image. - BinaryGrindPeakImageFilter ginds peaks in a grayscale image. +BinaryGrindPeakImageFilter ginds peaks in a grayscale image. Geodesic morphology and the grind peak algorithm is described in Chapter 6 of Pierre Soille's book \"Morphological Image Analysis: @@ -3161,7 +3161,7 @@ Label the connected components in a binary image and produce a collection of label objects. - BinaryImageToLabelMapFilter labels the objects in a binary image. Each distinct object is +BinaryImageToLabelMapFilter labels the objects in a binary image. Each distinct object is assigned a unique label. The final object labels start with 1 and are consecutive. Objects that are reached earlier by a raster order scan have a lower label. @@ -3547,13 +3547,13 @@ public "; Denoise a binary image using min/max curvature flow. - BinaryMinMaxCurvatureFlowImageFilter implements a curvature driven image denosing algorithm. This filter +BinaryMinMaxCurvatureFlowImageFilter implements a curvature driven image denosing algorithm. This filter assumes that the image is essentially binary: consisting of two classes. Iso-brightness contours in the input image are viewed as a level set. The level set is then evolved using a curvature-based speed function: - \\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] +\\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] where $ F_{\\\\mbox{minmax}} = \\\\min(\\\\kappa,0) $ if $ \\\\mbox{Avg}_{\\\\mbox{stencil}}(x) $ is less than or equal to $ T_{thresold} $ and $ \\\\max(\\\\kappa,0) $ , otherwise. $ \\\\kappa $ is the mean curvature of the iso-brightness contour at point $ x $ . @@ -5269,7 +5269,7 @@ This class is parameterized over the type of the input image and the type of the output image. It is also parameterized by the operation to be applied, using a Functor style. - UnaryFunctorImageFilter allows the output dimension of the filter to be larger than the input +UnaryFunctorImageFilter allows the output dimension of the filter to be larger than the input dimension. Thus subclasses of the UnaryFunctorImageFilter (like the CastImageFilter ) can be used to promote a 2D image to a 3D image, etc. @@ -5966,7 +5966,7 @@ public "; %typemap(javaimports) itk::simple::CenteredTransformInitializerFilter "/** - CenteredTransformInitializerFilter is a helper class intended to initialize the center of rotation and +CenteredTransformInitializerFilter is a helper class intended to initialize the center of rotation and the translation of Transforms having the center of rotation among their parameters. @@ -5993,12 +5993,7 @@ passes as the initial translation to the transform. This second approach assumes that the moments of the anatomical objects are similar for both images and hence the best initial guess for registration is to superimpose both mass centers. Note that this -assumption will probably not hold in multi-modality registration. - - -See: - itk::CenteredTransformInitializer - +assumption will probably not hold in multi-modality registration. \\\\sa itk::CenteredTransformInitializer C++ includes: sitkCenteredTransformInitializerFilter.h */" @@ -6086,7 +6081,7 @@ public "; %typemap(javaimports) itk::simple::CenteredVersorTransformInitializerFilter "/** - CenteredVersorTransformInitializerFilter is a helper class intended to initialize the center of rotation, +CenteredVersorTransformInitializerFilter is a helper class intended to initialize the center of rotation, versor, and translation of the VersorRigid3DTransform. @@ -6370,7 +6365,7 @@ public "; Combines two images in a checkerboard pattern. - CheckerBoardImageFilter takes two input images that must have the same dimension, size, +CheckerBoardImageFilter takes two input images that must have the same dimension, size, origin and spacing and produces an output image of the same size by combinining the pixels from the two input images in a checkerboard pattern. This filter is commonly used for visually comparing two @@ -7287,10 +7282,10 @@ public "; %typemap(javaimports) itk::simple::ComposeImageFilter "/** - ComposeImageFilter combine several scalar images into a multicomponent image. +ComposeImageFilter combine several scalar images into a multicomponent image. - ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . +ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . Inputs and Usage All input images are expected to have the same template parameters @@ -7624,7 +7619,7 @@ public "; Label the objects in a binary image. - ConnectedComponentImageFilter labels the objects in a binary image (non-zero pixels are considered +ConnectedComponentImageFilter labels the objects in a binary image (non-zero pixels are considered to be objects, zero-valued pixels are considered to be background). Each distinct object is assigned a unique label. The filter experiments with some improvements to the existing implementation, and @@ -7710,6 +7705,18 @@ Name of this class */ public "; +%javamethodmodifiers itk::simple::ConnectedComponentImageFilter::GetObjectCount "/** +uint32_t itk::simple::ConnectedComponentImageFilter::GetObjectCount() const + +After the filter is executed, holds the number of connected +components. + +This is a measurement. Its value is updated in the Execute methods, so +the value will only be valid after an execution. + +*/ +public "; + %javamethodmodifiers itk::simple::ConnectedComponentImageFilter::SetFullyConnected "/** Self& itk::simple::ConnectedComponentImageFilter::SetFullyConnected(bool FullyConnected) @@ -7744,7 +7751,7 @@ Label pixels that are connected to a seed and lie within a range of values. - ConnectedThresholdImageFilter labels pixels with ReplaceValue that are connected to an initial Seed +ConnectedThresholdImageFilter labels pixels with ReplaceValue that are connected to an initial Seed AND lie within a Lower and Upper threshold range. See: itk::simple::ConnectedThreshold for the procedural interface @@ -7919,7 +7926,7 @@ public "; Increase the image size by padding with a constant value. - ConstantPadImageFilter changes the output image region. If the output image region is larger +ConstantPadImageFilter changes the output image region. If the output image region is larger than the input image region, the extra pixels are filled in by a constant value. The output image region must be specified. @@ -8253,7 +8260,7 @@ public "; Decrease the image size by cropping the image by an itk::Size at both the upper and lower bounds of the largest possible region. - CropImageFilter changes the image boundary of an image by removing pixels outside the +CropImageFilter changes the image boundary of an image by removing pixels outside the target region. The target region is not specified in advance, but calculated in BeforeThreadedGenerateData() . @@ -8501,12 +8508,12 @@ public "; Denoise an image using curvature driven flow. - CurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- +CurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- brightness contours in the grayscale input image are viewed as a level set. The level set is then evolved using a curvature-based speed function: - \\\\[ I_t = \\\\kappa |\\\\nabla I| \\\\] where $ \\\\kappa $ is the curvature. +\\\\[ I_t = \\\\kappa |\\\\nabla I| \\\\] where $ \\\\kappa $ is the curvature. The advantage of this approach is that sharp boundaries are preserved with smoothing occurring only within a region. However, it should be @@ -8933,7 +8940,7 @@ public "; Deformably register two images using the demons algorithm. - DemonsRegistrationFilter implements the demons deformable algorithm that register two images +DemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the displacement field which will map a moving image onto a fixed image. @@ -9502,7 +9509,7 @@ See T. Vercauteren, X. Pennec, A. Perchant and N. Ayache, \"Non- parametric Diffeomorphic Image Registration with the Demons Algorithm\", Proc. of MICCAI 2007. - DiffeomorphicDemonsRegistrationFilter implements the demons deformable algorithm that register two images +DiffeomorphicDemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the deformation field which will map a moving image onto a fixed image. @@ -10724,6 +10731,18 @@ public "; %javamethodmodifiers itk::simple::DisplacementFieldTransform::DisplacementFieldTransform "/** itk::simple::DisplacementFieldTransform::DisplacementFieldTransform(Image &) + +Consume an image to construct a displacement field transform. + + + +WARNING: +The input displacement image is transferred to the constructed +transform object. The input image is modified to be a default +constructed Image object. +Image must be of sitkVectorFloat64 pixel type with the number of components +equal to the image dimension. + */ public "; @@ -10741,7 +10760,7 @@ public "; Image itk::simple::DisplacementFieldTransform::GetDisplacementField() const Todo -The returned image is should not directly modify the internal +The returned image should not directly modify the internal displacement field. @@ -11989,7 +12008,7 @@ public "; Expand the size of an image by an integer factor in each dimension. - ExpandImageFilter increases the size of an image by an integer factor in each dimension +ExpandImageFilter increases the size of an image by an integer factor in each dimension using a interpolation method. The output image size in each dimension is given by: @@ -12140,10 +12159,10 @@ Decrease the image size by cropping the image to the selected region bounds. - ExtractImageFilter changes the image boundary of an image by removing pixels outside the +ExtractImageFilter changes the image boundary of an image by removing pixels outside the target region. The target region must be specified. - ExtractImageFilter also collapses dimensions so that the input image may have more +ExtractImageFilter also collapses dimensions so that the input image may have more dimensions than the output image (i.e. 4-D input image to a 3-D output image). To specify what dimensions to collapse, the ExtractionRegion must be specified. For any dimension dim where @@ -12195,7 +12214,8 @@ Crop an image by specifying the region to keep See: itk::simple::Extract for the procedural interface - itk::ExtractImageFilter for the Doxygen on the original ITK class. + itk::ExtractImageFilter. The image is flipped across axes for which array[i] is true. @@ -14071,7 +14091,7 @@ public "; Generate an n-dimensional image of a Gabor filter. - GaborImageSource generates an image of either the real (i.e. symmetric) or complex +GaborImageSource generates an image of either the real (i.e. symmetric) or complex (i.e. antisymmetric) part of the Gabor filter with the orientation directed along the x-axis. The GaborKernelFunction is used to evaluate the contribution along the x-axis whereas a non- normalized 1-D Gaussian envelope provides the contribution in each of @@ -14243,7 +14263,7 @@ public "; Generate an n-dimensional image of a Gaussian. - GaussianImageSource generates an image of a Gaussian. m_Normalized determines whether or +GaussianImageSource generates an image of a Gaussian. m_Normalized determines whether or not the Gaussian is normalized (whether or not the sum over infinite space is 1.0) When creating an image, it is preferable tonotnormalize the Gaussian m_Scale scales the output of the Gaussian to span a range @@ -14556,7 +14576,7 @@ edge potential map. General characteristics of an edge potential map is that it has values close to zero in regions near the edges and values close to one inside the shape itself. Typically, the edge potential map is compute from the image gradient, for example: - \\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] +\\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] where $ I $ is image intensity and $ (\\\\nabla * G) $ is the derivative of Gaussian operator. @@ -15949,7 +15969,7 @@ public "; Remove local minima not connected to the boundary of the image. - GrayscaleFillholeImageFilter fills holes in a grayscale image. Holes are local minima in the +GrayscaleFillholeImageFilter fills holes in a grayscale image. Holes are local minima in the grayscale topography that are not connected to boundaries of the image. Gray level values adjacent to a hole are extrapolated across the hole. @@ -16397,7 +16417,7 @@ public "; Remove local maxima not connected to the boundary of the image. - GrayscaleGrindPeakImageFilter removes peaks in a grayscale image. Peaks are local maxima in the +GrayscaleGrindPeakImageFilter removes peaks in a grayscale image. Peaks are local maxima in the grayscale topography that are not connected to boundaries of the image. Gray level values adjacent to a peak are extrapolated through the peak. @@ -17114,7 +17134,7 @@ public "; Generate an n-dimensional image of a grid. - GridImageSource generates an image of a grid. From the abstract... \"Certain classes +GridImageSource generates an image of a grid. From the abstract... \"Certain classes of images find disparate use amongst members of the ITK community for such purposes as visualization, simulation, testing, etc. Currently there exists two derived classes from the ImageSource class used for @@ -17298,7 +17318,7 @@ Identify local minima whose depth below the baseline is greater than h. - HConcaveImageFilter extract local minima that are more than h intensity units below the +HConcaveImageFilter extract local minima that are more than h intensity units below the (local) background. This has the effect of extracting objects that are darker than the background by at least h intensity units. @@ -17436,7 +17456,7 @@ Identify local maxima whose height above the baseline is greater than h. - HConvexImageFilter extract local maxima that are more than h intensity units above the +HConvexImageFilter extract local maxima that are more than h intensity units above the (local) background. This has the effect of extracting objects that are brighter than background by at least h intensity units. @@ -17573,7 +17593,7 @@ public "; Suppress local maxima whose height above the baseline is less than h. - HMaximaImageFilter suppresses local maxima that are less than h intensity units above +HMaximaImageFilter suppresses local maxima that are less than h intensity units above the (local) background. This has the effect of smoothing over the \"high\" parts of the noise in the image without smoothing over large changes in intensity (region boundaries). See the HMinimaImageFilter to suppress the local minima whose depth is less than h intensity @@ -17684,7 +17704,7 @@ public "; Suppress local minima whose depth below the baseline is less than h. - HMinimaImageFilter suppresses local minima that are less than h intensity units below +HMinimaImageFilter suppresses local minima that are less than h intensity units below the (local) background. This has the effect of smoothing over the \"low\" parts of the noise in the image without smoothing over large changes in intensity (region boundaries). See the HMaximaImageFilter to suppress the local maxima whose height is less than h intensity @@ -17988,7 +18008,7 @@ Computes the Hausdorff distance between the set of non-zero pixels of two images. - HausdorffDistanceImageFilter computes the distance between the set non-zero pixels of two images +HausdorffDistanceImageFilter computes the distance between the set non-zero pixels of two images using the following formula: \\\\[ H(A,B) = \\\\max(h(A,B),h(B,A)) \\\\] where \\\\[ h(A,B) = \\\\max_{a \\\\in A} \\\\min_{b \\\\in B} \\\\| a - b\\\\| \\\\] is the directed Hausdorff distance and $A$ and $B$ are respectively the set of non-zero pixels in the first and second input images. @@ -18092,7 +18112,7 @@ Normalize the grayscale values between two images by histogram matching. - HistogramMatchingImageFilter normalizes the grayscale values of a source image based on the +HistogramMatchingImageFilter normalizes the grayscale values of a source image based on the grayscale values of a reference image. This filter uses a histogram matching technique where the histograms of the two images are matched only at a specified number of quantile values. @@ -18106,7 +18126,7 @@ grayscale values are smaller than the mean grayscale value. ThresholdAtMeanInten The source image can be set via either SetInput() or SetSourceImage() . The reference image can be set via SetReferenceImage() . - SetNumberOfHistogramLevels() sets the number of bins used when creating histograms of the source +SetNumberOfHistogramLevels() sets the number of bins used when creating histograms of the source and reference images. SetNumberOfMatchPoints() governs the number of quantile values to be matched. This filter assumes that both the source and reference are of the same @@ -18579,7 +18599,7 @@ public "; %javamethodmodifiers itk::simple::Image::TransformContinuousIndexToPhysicalPoint "/** std::vector< double > itk::simple::Image::TransformContinuousIndexToPhysicalPoint(const std::vector< double > &index) const - Transform continuous index to physical point +Transform continuous index to physical point */ public "; @@ -18587,7 +18607,7 @@ public "; %javamethodmodifiers itk::simple::Image::TransformIndexToPhysicalPoint "/** std::vector< double > itk::simple::Image::TransformIndexToPhysicalPoint(const std::vector< int64_t > &index) const - Transform index to physical point +Transform index to physical point */ public "; @@ -18595,7 +18615,7 @@ public "; %javamethodmodifiers itk::simple::Image::TransformPhysicalPointToContinuousIndex "/** std::vector< double > itk::simple::Image::TransformPhysicalPointToContinuousIndex(const std::vector< double > &point) const - Transform physical point to continuous index +Transform physical point to continuous index */ public "; @@ -18603,7 +18623,7 @@ public "; %javamethodmodifiers itk::simple::Image::TransformPhysicalPointToIndex "/** std::vector< int64_t > itk::simple::Image::TransformPhysicalPointToIndex(const std::vector< double > &point) const - Transform physical point to index +Transform physical point to index */ public "; @@ -18942,6 +18962,7 @@ Self& itk::simple::ImageRegistrationMethod::SetMetricAsDemons(double intensityDi Use demons image metric. + See: itk::DemonsImageToImageMetricv4 @@ -19145,9 +19166,8 @@ public "; %javamethodmodifiers itk::simple::ImageRegistrationMethod::SetOptimizerAsLBFGSB "/** Self& itk::simple::ImageRegistrationMethod::SetOptimizerAsLBFGSB(double gradientConvergenceTolerance=1e-5, unsigned int -maximumNumberOfIterations=500, unsigned int -maximumNumberOfCorrections=5, unsigned int -maximumNumberOfFunctionEvaluations=2000, double +numberOfIterations=500, unsigned int maximumNumberOfCorrections=5, +unsigned int maximumNumberOfFunctionEvaluations=2000, double costFunctionConvergenceFactor=1e+7, double lowerBound=std::numeric_limits< double >::min(), double upperBound=std::numeric_limits< double >::max(), bool trace=false) @@ -19524,7 +19544,7 @@ are mapped to a constant. Values over the interval are mapped to another constant. - IntensityWindowingImageFilter applies pixel-wise a linear transformation to the intensity values of +IntensityWindowingImageFilter applies pixel-wise a linear transformation to the intensity values of input image pixels. The linear transformation is defined by the user in terms of the minimum and maximum values that the output image should have and the lower and upper limits of the intensity window of @@ -19539,7 +19559,7 @@ Wiki Examples: All Examples - IntensityWindowingImageFilter +IntensityWindowingImageFilter See: RescaleIntensityImageFilter @@ -20020,7 +20040,7 @@ public "; Computes the inverse of a displacement field. - InverseDisplacementFieldImageFilter takes a displacement field as input and computes the displacement +InverseDisplacementFieldImageFilter takes a displacement field as input and computes the displacement field that is its inverse. If the input displacement field was mapping coordinates from a space A into a space B, the output of this filter will map coordinates from the space B into the space A. @@ -20409,7 +20429,7 @@ public "; Invert the intensity of an image. - InvertIntensityImageFilter inverts intensity of pixels by subtracting pixel value to a maximum +InvertIntensityImageFilter inverts intensity of pixels by subtracting pixel value to a maximum value. The maximum value can be set with SetMaximum and defaults the maximum of input pixel type. This filter can be used to invert, for example, a binary image, a distance map, etc. @@ -20807,7 +20827,7 @@ public "; Label pixels that are connected to one set of seeds but not another. - IsolatedConnectedImageFilter finds the optimal threshold to separate two regions. It has two +IsolatedConnectedImageFilter finds the optimal threshold to separate two regions. It has two modes, one to separate dark regions surrounded by bright regions by automatically finding a minimum isolating upper threshold, and another to separate bright regions surrounded by dark regions by automatically @@ -21061,7 +21081,7 @@ public "; Isolate watershed basins using two seeds. - IsolatedWatershedImageFilter labels pixels with ReplaceValue1 that are in the same watershed basin +IsolatedWatershedImageFilter labels pixels with ReplaceValue1 that are in the same watershed basin as Seed1 AND NOT the same as Seed2. The filter adjusts the waterlevel until the two seeds are not in different basins. The user supplies a Watershed threshold. The algorithm uses a binary search to adjust the @@ -21613,7 +21633,7 @@ public "; Labels the pixels on the border of the objects in a labeled image. - LabelContourImageFilter takes a labeled image as input, where the pixels in the objects are +LabelContourImageFilter takes a labeled image as input, where the pixels in the objects are the pixels with a value different of the BackgroundValue. Only the pixels on the contours of the objects are kept. The pixels not on the border are changed to BackgroundValue. The labels of the object are @@ -21622,7 +21642,7 @@ the same in the input and in the output image. The connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours. - http://hdl.handle.net/1926/1352 +http://hdl.handle.net/1926/1352 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -21755,7 +21775,7 @@ public "; convert a labeled image to a label collection image - LabelImageToLabelMapFilter converts a label image to a label collection image. The labels are +LabelImageToLabelMapFilter converts a label image to a label collection image. The labels are the same in the input and the output image. @@ -22051,7 +22071,7 @@ public "; Mask and image with a LabelMap . - LabelMapMaskImageFilter mask the content of an input image according to the content of the +LabelMapMaskImageFilter mask the content of an input image according to the content of the input LabelMap . The masked pixel of the input image are set to the BackgroundValue. LabelMapMaskImageFilter can keep the input image for one label only, with Negated = false (the default) or it can mask the input image for a single label, when Negated equals true. In Both cases, the label is set with SetLabel() . @@ -22350,7 +22370,7 @@ public "; Convert a LabelMap to a binary image. - LabelMapToBinaryImageFilter to a binary image. All the objects in the image are used as +LabelMapToBinaryImageFilter to a binary image. All the objects in the image are used as foreground. The background values of the original binary image can be restored by passing this image to the filter with the SetBackgroundImage() method. @@ -22463,7 +22483,7 @@ public "; Converts a LabelMap to a labeled image. - LabelMapToBinaryImageFilter to a label image. +LabelMapToBinaryImageFilter to a label image. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -22859,7 +22879,7 @@ valuates the shape attribute at once. This implementation was taken from the Insight Journal paper: - http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -23213,7 +23233,7 @@ Given an intensity image and a label map, compute min, max, variance and mean of the pixels associated with each label or segment. - LabelStatisticsImageFilter computes the minimum, maximum, sum, mean, median, variance and sigma +LabelStatisticsImageFilter computes the minimum, maximum, sum, mean, median, variance and sigma of regions of an intensity image, where the regions are defined via a label map (a second input). The label image should be integral type. The filter needs all of its input image. It behaves as a filter with @@ -23558,7 +23578,7 @@ public "; Make sure that the objects are not overlapping. - AttributeUniqueLabelMapFilter search the overlapping zones in the overlapping objects and keeps +AttributeUniqueLabelMapFilter search the overlapping zones in the overlapping objects and keeps only a single object on all the pixels of the image. The object to keep is selected according to their label. @@ -25972,14 +25992,14 @@ calculated and the one that gives the largest number of pixels is chosen. Since these both default to 0, if a user only sets one, the other is ignored. - Image size: fixedImage and movingImage need not be the same size, but +Image size: fixedImage and movingImage need not be the same size, but fixedMask must be the same size as fixedImage, and movingMask must be the same size as movingImage. Furthermore, whereas some algorithms require that the \"template\" be smaller than the \"image\" because of errors in the regions where the two are not fully overlapping, this filter has no such restriction. - Image spacing: Since the computations are done in the pixel domain, all +Image spacing: Since the computations are done in the pixel domain, all input images must have the same spacing. Outputs; The output is an image of RealPixelType that is the masked @@ -26896,7 +26916,7 @@ Merges several Label Maps. This filter takes one or more input Label Map and merges them. - SetMethod() can be used to change how the filter manage the labels from the +SetMethod() can be used to change how the filter manage the labels from the different label maps. KEEP (0): MergeLabelMapFilter do its best to keep the label unchanged, but if a label is already used in a previous label map, a new label is assigned. AGGREGATE (1): If the same label is found several times in the label maps, the label @@ -27048,12 +27068,12 @@ public "; Denoise an image using min/max curvature flow. - MinMaxCurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- +MinMaxCurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- brightness contours in the grayscale input image are viewed as a level set. The level set is then evolved using a curvature-based speed function: - \\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] +\\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] where $ F_{\\\\mbox{minmax}} = \\\\max(\\\\kappa,0) $ if $ \\\\mbox{Avg}_{\\\\mbox{stencil}}(x) $ is less than or equal to $ T_{thresold} $ and $ \\\\min(\\\\kappa,0) $ , otherwise. $ \\\\kappa $ is the mean curvature of the iso-brightness contour at point $ x $ . @@ -27455,7 +27475,7 @@ Increase the image size by padding with replicants of the input image value. - MirrorPadImageFilter changes the image bounds of an image. Any added pixels are filled in +MirrorPadImageFilter changes the image bounds of an image. Any added pixels are filled in with a mirrored replica of the input image. For instance, if the output image needs a pixel that istwo pixels to the left of the LargestPossibleRegionof the input image, the value assigned will be @@ -28839,7 +28859,7 @@ Label pixels that are connected to a seed and lie within a neighborhood. - NeighborhoodConnectedImageFilter labels pixels with ReplaceValue that are connected to an initial Seed +NeighborhoodConnectedImageFilter labels pixels with ReplaceValue that are connected to an initial Seed AND whose neighbors all lie within a Lower and Upper threshold range. See: itk::simple::NeighborhoodConnected for the procedural interface @@ -29156,7 +29176,7 @@ C++ includes: sitkNonCopyable.h Normalize an image by setting its mean to zero and variance to one. - NormalizeImageFilter shifts and scales an image so that the pixels in the image have a +NormalizeImageFilter shifts and scales an image so that the pixels in the image have a zero mean and unit variance. This filter uses StatisticsImageFilter to compute the mean and variance of the input and then applies ShiftScaleImageFilter to shift and scale the pixels. NB: since this filter normalizes the data to lie within -1 to 1, @@ -30291,7 +30311,7 @@ public "; Paste an image into another image. - PasteImageFilter allows you to take a section of one image and paste into another +PasteImageFilter allows you to take a section of one image and paste into another image. The SetDestinationIndex() method prescribes where in the first input to start pasting data from the second input. The SetSourceRegion method prescribes the section of the second image to paste into the first. If the output requested @@ -31964,10 +31984,10 @@ public "; %typemap(javaimports) itk::simple::RealAndImaginaryToComplexImageFilter "/** - ComposeImageFilter combine several scalar images into a multicomponent image. +ComposeImageFilter combine several scalar images into a multicomponent image. - ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . +ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . Inputs and Usage All input images are expected to have the same template parameters @@ -32398,10 +32418,10 @@ Base class for computing IIR convolution with an approximation of a Gaussian kernel. - \\\\[ \\\\frac{ 1 }{ \\\\sigma \\\\sqrt{ 2 \\\\pi } } \\\\exp{ +\\\\[ \\\\frac{ 1 }{ \\\\sigma \\\\sqrt{ 2 \\\\pi } } \\\\exp{ \\\\left( - \\\\frac{x^2}{ 2 \\\\sigma^2 } \\\\right) } \\\\] - RecursiveGaussianImageFilter is the base class for recursive filters that approximate convolution +RecursiveGaussianImageFilter is the base class for recursive filters that approximate convolution with the Gaussian kernel. This class implements the recursive filtering method proposed by R.Deriche in IEEE-PAMI Vol.12, No.1, January 1990, pp 78-87, \"Fast Algorithms for Low-Level Vision\" @@ -32540,7 +32560,7 @@ Let \\\\[ L(x; t) = g(x; t) \\\\ast f(x) \\\\] be the scale-space representation Then the normalized derivative operator for normalized coordinates across scale is: - \\\\[ \\\\partial_\\\\xi = \\\\sqrt{t} \\\\partial_x \\\\] +\\\\[ \\\\partial_\\\\xi = \\\\sqrt{t} \\\\partial_x \\\\] The resulting scaling factor is \\\\[ \\\\sigma^N \\\\] where N is the order of the derivative. @@ -32746,7 +32766,7 @@ Wiki Examples: All Examples - RegionalMaximaImageFilter +RegionalMaximaImageFilter See: itk::simple::RegionalMaxima for the procedural interface @@ -32924,7 +32944,7 @@ a minima or not. The SetFlatIsMinima() method let the user choose which behavior This class was contribtued to the Insight Journal by Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. http://hdl.handle.net/1926/153 - RegionalMaximaImageFilter MathematicalMorphologyImageFilters +RegionalMaximaImageFilter MathematicalMorphologyImageFilters See: @@ -32936,7 +32956,7 @@ Wiki Examples: All Examples - RegionalMinimaImageFilter +RegionalMinimaImageFilter See: itk::simple::RegionalMinima for the procedural interface @@ -33106,7 +33126,7 @@ Relabel the components in an image such that consecutive labels are used. - RelabelComponentImageFilter remaps the labels associated with the objects in an image (as from +RelabelComponentImageFilter remaps the labels associated with the objects in an image (as from the output of ConnectedComponentImageFilter ) such that the label numbers are consecutive with no gaps between the label numbers used. By default, the relabeling will also sort the labels based on the size of the object: the largest object will have @@ -33117,7 +33137,7 @@ can be disabled using SetSortByObjectSize. Label #0 is assumed to be the background and is left unaltered by the relabeling. - RelabelComponentImageFilter is typically used on the output of the ConnectedComponentImageFilter for those applications that want to extract the largest object or the +RelabelComponentImageFilter is typically used on the output of the ConnectedComponentImageFilter for those applications that want to extract the largest object or the \"k\" largest objects. Any particular object can be extracted from the relabeled output using a BinaryThresholdImageFilter . A group of objects can be extracted from the relabled output using a ThresholdImageFilter . @@ -33133,7 +33153,7 @@ will be only those remaining. The GetOriginalNumberOfObjects method can be called to find out how many objects were present before the small ones were discarded. - RelabelComponentImageFilter can be run as an \"in place\" filter, where it will overwrite its +RelabelComponentImageFilter can be run as an \"in place\" filter, where it will overwrite its output. The default is run out of place (or generate a separate output). \"In place\" operation can be controlled via methods in the superclass, InPlaceImageFilter::InPlaceOn() and @@ -33527,7 +33547,7 @@ public "; Resample an image via a coordinate transform. - ResampleImageFilter resamples an existing image through some coordinate transform, +ResampleImageFilter resamples an existing image through some coordinate transform, interpolating via some image function. The class is templated over the types of the input and output images. @@ -33790,7 +33810,7 @@ public "; Applies a linear transformation to the intensity levels of the input Image . - RescaleIntensityImageFilter applies pixel-wise a linear transformation to the intensity values of +RescaleIntensityImageFilter applies pixel-wise a linear transformation to the intensity values of input image pixels. The linear transformation is defined by the user in terms of the minimum and maximum values that the output image should have. @@ -33798,7 +33818,7 @@ should have. The following equation gives the mapping of the intensity values - \\\\[ outputPixel = ( inputPixel - inputMin) \\\\cdot +\\\\[ outputPixel = ( inputPixel - inputMin) \\\\cdot \\\\frac{(outputMax - outputMin )}{(inputMax - inputMin)} + outputMin \\\\] All computations are performed in the precison of the input pixel's @@ -35625,7 +35645,7 @@ edge potential map. General characteristics of an edge potential map is that it has values close to zero in regions near the edges and values close to one inside the shape itself. Typically, the edge potential map is compute from the image gradient, for example: - \\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] +\\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] where $ I $ is image intensity and $ (\\\\nabla * G) $ is the derivative of Gaussian operator. @@ -35822,7 +35842,7 @@ public "; Shift and scale the pixels in an image. - ShiftScaleImageFilter shifts the input pixel by Shift (default 0.0) and then scales the +ShiftScaleImageFilter shifts the input pixel by Shift (default 0.0) and then scales the pixel by Scale (default 1.0). All computattions are performed in the precison of the input pixel's RealType. Before assigning the computed value to the output pixel, the value is clamped at the NonpositiveMin @@ -36023,7 +36043,7 @@ public "; Reduce the size of an image by an integer factor in each dimension. - ShrinkImageFilter reduces the size of an image by an integer factor in each dimension. +ShrinkImageFilter reduces the size of an image by an integer factor in each dimension. The algorithm implemented is a simple subsample. The output image size in each dimension is given by: @@ -36140,7 +36160,7 @@ Computes the sigmoid function pixel-wise. A linear transformation is applied first on the argument of the sigmoid fuction. The resulting total transfrom is given by - \\\\[ f(x) = (Max-Min) \\\\cdot \\\\frac{1}{\\\\left(1+e^{- \\\\frac{ +\\\\[ f(x) = (Max-Min) \\\\cdot \\\\frac{1}{\\\\left(1+e^{- \\\\frac{ x - \\\\beta }{\\\\alpha}}\\\\right)} + Min \\\\] Every output pixel is equal to f(x). Where x is the intensity of the @@ -36852,7 +36872,7 @@ Measures the similarity between the set of non-zero pixels of two images. - SimilarityIndexImageFilter measures the similarity between the set non-zero pixels of two images +SimilarityIndexImageFilter measures the similarity between the set non-zero pixels of two images using the following formula: \\\\[ S = \\\\frac{2 | A \\\\cap B |}{|A| + |B|} \\\\] where $A$ and $B$ are respectively the set of non-zero pixels in the first and second input images. Operator $|\\\\cdot|$ represents the size of a set and $\\\\cap$ represents the intersection of two sets. @@ -37435,7 +37455,7 @@ Wiki Examples: All Examples - SobelEdgeDetectionImageFilter +SobelEdgeDetectionImageFilter See: itk::simple::SobelEdgeDetection for the procedural interface @@ -37907,7 +37927,7 @@ public "; Compute min. max, variance and mean of an Image . - StatisticsImageFilter computes the minimum, maximum, sum, mean, variance sigma of an image. +StatisticsImageFilter computes the minimum, maximum, sum, mean, variance sigma of an image. The filter needs all of its input image. It behaves as a filter with an input and output. Thus it can be inserted in a pipline with other filters and the statistics will only be recomputed if a downstream @@ -38246,7 +38266,7 @@ Switzerland. based on a variation of the DemonsRegistrationFilter . The basic mo along with the modification for avoiding large deformations when gradients have small values. - SymmetricForcesDemonsRegistrationFilter implements the demons deformable algorithm that register two images +SymmetricForcesDemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the deformation field which will map a moving image onto a fixed image. @@ -38862,7 +38882,7 @@ Set image values to a user-specified value if they are below, above, or between simple threshold values. - ThresholdImageFilter sets image values to a user-specified \"outside\" value (by default, +ThresholdImageFilter sets image values to a user-specified \"outside\" value (by default, \"black\") if the image values are below, above, or between simple threshold values. @@ -40409,7 +40429,7 @@ Wiki Examples: All Examples - ValuedRegionalMaximaImageFilter +ValuedRegionalMaximaImageFilter See: itk::simple::ValuedRegionalMaxima for the procedural interface @@ -40529,7 +40549,7 @@ Wiki Examples: All Examples - ValuedRegionalMinimaImageFilter +ValuedRegionalMinimaImageFilter See: itk::simple::ValuedRegionalMinima for the procedural interface @@ -41128,7 +41148,7 @@ public "; %typemap(javaimports) itk::simple::Version "/** - Version info for SimpleITK. +Version info for SimpleITK. C++ includes: sitkVersion.h */" @@ -41866,7 +41886,7 @@ public "; Warps an image using an input displacement field. - WarpImageFilter warps an existing image with respect to a given displacement field. +WarpImageFilter warps an existing image with respect to a given displacement field. A displacement field is represented as a image whose pixel type is some vector type with at least N elements, where N is the dimension of @@ -41881,7 +41901,7 @@ Each vector in the displacement field represent the distance between a geometric point in the input space and a point in the output space such that: - \\\\[ p_{in} = p_{out} + d \\\\] +\\\\[ p_{in} = p_{out} + d \\\\] Typically the mapped position does not correspond to an integer pixel position in the input image. Interpolation via an image function is @@ -42399,7 +42419,7 @@ Increase the image size by padding with replicants of the input image value. - WrapPadImageFilter changes the image bounds of an image. Added pixels are filled in with +WrapPadImageFilter changes the image bounds of an image. Added pixels are filled in with a wrapped replica of the input image. For instance, if the output image needs a pixel that istwo pixels to the left of the LargestPossibleRegionof the input image, the value assigned will be @@ -43657,7 +43677,7 @@ public "; Image itk::simple::BinaryClosingByReconstruction(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, double foregroundValue=1.0, bool fullyConnected=false) - itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface +itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryClosingByReconstructionImageFilter in order to support a fully functional API @@ -43669,7 +43689,7 @@ Image itk::simple::BinaryClosingByReconstruction(const Image &, const std::vecto kernel=sitkBall, double foregroundValue=1.0, bool fullyConnected=false) - itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface +itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryClosingByReconstructionImageFilter in order to support a fully functional API @@ -43698,7 +43718,7 @@ Image itk::simple::BinaryDilate(const Image &, uint32_t radius=1, KernelEnum ker backgroundValue=0.0, double foregroundValue=1.0, bool boundaryToForeground=false) - itk::simple::BinaryDilateImageFilter Functional Interface +itk::simple::BinaryDilateImageFilter Functional Interface This function directly calls the execute method of BinaryDilateImageFilter in order to support a fully functional API @@ -43710,7 +43730,7 @@ Image itk::simple::BinaryDilate(const Image &, const std::vector< uint32_t > vec kernel=sitkBall, double backgroundValue=0.0, double foregroundValue=1.0, bool boundaryToForeground=false) - itk::simple::BinaryDilateImageFilter Functional Interface +itk::simple::BinaryDilateImageFilter Functional Interface This function directly calls the execute method of BinaryDilateImageFilter in order to support a fully functional API @@ -43722,7 +43742,7 @@ Image itk::simple::BinaryErode(const Image &, uint32_t radius=1, KernelEnum kern backgroundValue=0.0, double foregroundValue=1.0, bool boundaryToForeground=true) - itk::simple::BinaryErodeImageFilter Functional Interface +itk::simple::BinaryErodeImageFilter Functional Interface This function directly calls the execute method of BinaryErodeImageFilter in order to support a fully functional API @@ -43734,7 +43754,7 @@ Image itk::simple::BinaryErode(const Image &, const std::vector< uint32_t > vect kernel=sitkBall, double backgroundValue=0.0, double foregroundValue=1.0, bool boundaryToForeground=true) - itk::simple::BinaryErodeImageFilter Functional Interface +itk::simple::BinaryErodeImageFilter Functional Interface This function directly calls the execute method of BinaryErodeImageFilter in order to support a fully functional API @@ -43849,7 +43869,7 @@ public "; Image itk::simple::BinaryMorphologicalClosing(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, double foregroundValue=1.0, bool safeBorder=true) - itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface +itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalClosingImageFilter in order to support a fully functional API @@ -43860,7 +43880,7 @@ public "; Image itk::simple::BinaryMorphologicalClosing(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, double foregroundValue=1.0, bool safeBorder=true) - itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface +itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalClosingImageFilter in order to support a fully functional API @@ -43871,7 +43891,7 @@ public "; Image itk::simple::BinaryMorphologicalOpening(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, double backgroundValue=0.0, double foregroundValue=1.0) - itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface +itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalOpeningImageFilter in order to support a fully functional API @@ -43883,7 +43903,7 @@ Image itk::simple::BinaryMorphologicalOpening(const Image &, const std::vector< kernel=sitkBall, double backgroundValue=0.0, double foregroundValue=1.0) - itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface +itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalOpeningImageFilter in order to support a fully functional API @@ -43913,7 +43933,7 @@ Image itk::simple::BinaryOpeningByReconstruction(const Image &, uint32_t radius= foregroundValue=1.0, double backgroundValue=0.0, bool fullyConnected=false) - itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface +itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryOpeningByReconstructionImageFilter in order to support a fully functional API @@ -43925,7 +43945,7 @@ Image itk::simple::BinaryOpeningByReconstruction(const Image &, const std::vecto kernel=sitkBall, double foregroundValue=1.0, double backgroundValue=0.0, bool fullyConnected=false) - itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface +itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryOpeningByReconstructionImageFilter in order to support a fully functional API @@ -44088,7 +44108,7 @@ public "; Image itk::simple::BlackTopHat(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::BlackTopHatImageFilter Functional Interface +itk::simple::BlackTopHatImageFilter Functional Interface This function directly calls the execute method of BlackTopHatImageFilter in order to support a fully functional API @@ -44099,7 +44119,7 @@ public "; Image itk::simple::BlackTopHat(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::BlackTopHatImageFilter Functional Interface +itk::simple::BlackTopHatImageFilter Functional Interface This function directly calls the execute method of BlackTopHatImageFilter in order to support a fully functional API @@ -44163,7 +44183,7 @@ BSplineTransform itk::simple::BSplineTransformInitializer(const Image &image1, c &transformDomainMeshSize=std::vector< uint32_t >(3, 1u), unsigned int order=3u) - BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such +BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such that it has a physically consistent definition. It sets the transform domain origin, physical dimensions and direction from information obtained from the image. It also sets the mesh size if asked to do so @@ -44211,7 +44231,7 @@ Transform itk::simple::CenteredTransformInitializer(const Image &fixedImage, con &transform, CenteredTransformInitializerFilter::OperationModeType oper ationMode=itk::simple::CenteredTransformInitializerFilter::MOMENTS) - CenteredTransformInitializer is a helper class intended to initialize the center of rotation and +CenteredTransformInitializer is a helper class intended to initialize the center of rotation and the translation of Transforms having the center of rotation among their parameters. @@ -44230,7 +44250,7 @@ public "; Transform itk::simple::CenteredVersorTransformInitializer(const Image &fixedImage, const Image &movingImage, const Transform &transform, bool computeRotation=false) - CenteredVersorTransformInitializer is a helper class intended to initialize the center of rotation, +CenteredVersorTransformInitializer is a helper class intended to initialize the center of rotation, versor, and translation of the VersorRigid3DTransform. @@ -44321,7 +44341,7 @@ public "; Image itk::simple::ClosingByReconstruction(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, bool fullyConnected=false, bool preserveIntensities=false) - itk::simple::ClosingByReconstructionImageFilter Functional Interface +itk::simple::ClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of ClosingByReconstructionImageFilter in order to support a fully functional API @@ -44333,7 +44353,7 @@ Image itk::simple::ClosingByReconstruction(const Image &, const std::vector< uin kernel=sitkBall, bool fullyConnected=false, bool preserveIntensities=false) - itk::simple::ClosingByReconstructionImageFilter Functional Interface +itk::simple::ClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of ClosingByReconstructionImageFilter in order to support a fully functional API @@ -44430,7 +44450,7 @@ Image itk::simple::ConfidenceConnected(const Image &image1, const std::vector< s &seedList, unsigned int numberOfIterations=4u, double multiplier=4.5, unsigned int initialNeighborhoodRadius=1u, uint8_t replaceValue=1u) - itk::simple::ConfidenceConnectedImageFilter Functional Interface +itk::simple::ConfidenceConnectedImageFilter Functional Interface This function directly calls the execute method of ConfidenceConnectedImageFilter in order to support a fully functional API @@ -44459,7 +44479,7 @@ Image itk::simple::ConnectedThreshold(const Image &image1, const std::vector< st ConnectedThresholdImageFilter::ConnectivityType connectivity=itk::simp le::ConnectedThresholdImageFilter::FaceConnectivity) - itk::simple::ConnectedThresholdImageFilter Functional Interface +itk::simple::ConnectedThresholdImageFilter Functional Interface This function directly calls the execute method of ConnectedThresholdImageFilter in order to support a fully functional API @@ -44550,7 +44570,7 @@ Image itk::simple::CurvatureAnisotropicDiffusion(const Image &image1, double tim conductanceParameter=3, unsigned int conductanceScalingUpdateInterval=1u, uint32_t numberOfIterations=5u) - itk::simple::CurvatureAnisotropicDiffusionImageFilter Procedural Interface +itk::simple::CurvatureAnisotropicDiffusionImageFilter Procedural Interface This function directly calls the execute method of CurvatureAnisotropicDiffusionImageFilter in order to support a procedural API @@ -44638,7 +44658,7 @@ public "; Image itk::simple::DilateObjectMorphology(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, double objectValue=1) - itk::simple::DilateObjectMorphologyImageFilter Functional Interface +itk::simple::DilateObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of DilateObjectMorphologyImageFilter in order to support a fully functional API @@ -44649,7 +44669,7 @@ public "; Image itk::simple::DilateObjectMorphology(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, double objectValue=1) - itk::simple::DilateObjectMorphologyImageFilter Functional Interface +itk::simple::DilateObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of DilateObjectMorphologyImageFilter in order to support a fully functional API @@ -44869,7 +44889,7 @@ public "; Image itk::simple::ErodeObjectMorphology(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, double objectValue=1, double backgroundValue=0) - itk::simple::ErodeObjectMorphologyImageFilter Functional Interface +itk::simple::ErodeObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of ErodeObjectMorphologyImageFilter in order to support a fully functional API @@ -44880,7 +44900,7 @@ public "; Image itk::simple::ErodeObjectMorphology(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, double objectValue=1, double backgroundValue=0) - itk::simple::ErodeObjectMorphologyImageFilter Functional Interface +itk::simple::ErodeObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of ErodeObjectMorphologyImageFilter in order to support a fully functional API @@ -44939,8 +44959,8 @@ public "; %javamethodmodifiers itk::simple::Extract "/** Image itk::simple::Extract(const Image &image1, const std::vector< unsigned int > -&size=std::vector< unsigned int >(3, 1), const std::vector< int > -&index=std::vector< int >(3, 0), +&size=std::vector< unsigned int >(4, 1), const std::vector< int > +&index=std::vector< int >(4, 0), ExtractImageFilter::DirectionCollapseToStrategyType directionCollapseT oStrategy=itk::simple::ExtractImageFilter::DIRECTIONCOLLAPSETOGUESS) @@ -45001,7 +45021,7 @@ stoppingValue=std::numeric_limits< float >::max()/2.0, FastMarchingBaseImageFilter::TopologyCheckType topologyCheck=itk::simple::FastMarchingBaseImageFilter::Nothing) - itk::simple::FastMarchingBaseImageFilter Functional Interface +itk::simple::FastMarchingBaseImageFilter Functional Interface This function directly calls the execute method of FastMarchingBaseImageFilter in order to support a fully functional API @@ -45235,7 +45255,7 @@ Image itk::simple::GradientAnisotropicDiffusion(const Image &image1, double time conductanceParameter=3, unsigned int conductanceScalingUpdateInterval=1u, uint32_t numberOfIterations=5u) - itk::simple::GradientAnisotropicDiffusionImageFilter Procedural Interface +itk::simple::GradientAnisotropicDiffusionImageFilter Procedural Interface This function directly calls the execute method of GradientAnisotropicDiffusionImageFilter in order to support a procedural API @@ -45339,7 +45359,7 @@ public "; %javamethodmodifiers itk::simple::GrayscaleDilate "/** Image itk::simple::GrayscaleDilate(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall) - itk::simple::GrayscaleDilateImageFilter Functional Interface +itk::simple::GrayscaleDilateImageFilter Functional Interface This function directly calls the execute method of GrayscaleDilateImageFilter in order to support a fully functional API @@ -45350,7 +45370,7 @@ public "; Image itk::simple::GrayscaleDilate(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall) - itk::simple::GrayscaleDilateImageFilter Functional Interface +itk::simple::GrayscaleDilateImageFilter Functional Interface This function directly calls the execute method of GrayscaleDilateImageFilter in order to support a fully functional API @@ -45360,7 +45380,7 @@ public "; %javamethodmodifiers itk::simple::GrayscaleErode "/** Image itk::simple::GrayscaleErode(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall) - itk::simple::GrayscaleErodeImageFilter Functional Interface +itk::simple::GrayscaleErodeImageFilter Functional Interface This function directly calls the execute method of GrayscaleErodeImageFilter in order to support a fully functional API @@ -45371,7 +45391,7 @@ public "; Image itk::simple::GrayscaleErode(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall) - itk::simple::GrayscaleErodeImageFilter Functional Interface +itk::simple::GrayscaleErodeImageFilter Functional Interface This function directly calls the execute method of GrayscaleErodeImageFilter in order to support a fully functional API @@ -45448,7 +45468,7 @@ public "; Image itk::simple::GrayscaleMorphologicalClosing(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalClosingImageFilter in order to support a fully functional API @@ -45459,7 +45479,7 @@ public "; Image itk::simple::GrayscaleMorphologicalClosing(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalClosingImageFilter in order to support a fully functional API @@ -45470,7 +45490,7 @@ public "; Image itk::simple::GrayscaleMorphologicalOpening(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalOpeningImageFilter in order to support a fully functional API @@ -45481,7 +45501,7 @@ public "; Image itk::simple::GrayscaleMorphologicalOpening(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalOpeningImageFilter in order to support a fully functional API @@ -46286,7 +46306,7 @@ public "; %javamethodmodifiers itk::simple::Laplacian "/** Image itk::simple::Laplacian(const Image &image1, bool useImageSpacing=true) - itk::simple::LaplacianImageFilter Procedural Interface +itk::simple::LaplacianImageFilter Procedural Interface This function directly calls the execute method of LaplacianImageFilter in order to support a procedural API @@ -46830,7 +46850,7 @@ public "; %javamethodmodifiers itk::simple::MorphologicalGradient "/** Image itk::simple::MorphologicalGradient(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall) - itk::simple::MorphologicalGradientImageFilter Functional Interface +itk::simple::MorphologicalGradientImageFilter Functional Interface This function directly calls the execute method of MorphologicalGradientImageFilter in order to support a fully functional API @@ -46841,7 +46861,7 @@ public "; Image itk::simple::MorphologicalGradient(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall) - itk::simple::MorphologicalGradientImageFilter Functional Interface +itk::simple::MorphologicalGradientImageFilter Functional Interface This function directly calls the execute method of MorphologicalGradientImageFilter in order to support a fully functional API @@ -46936,7 +46956,7 @@ Image itk::simple::NeighborhoodConnected(const Image &image1, const std::vector< int > &radius=std::vector< unsigned int >(3, 1), double replaceValue=1) - itk::simple::NeighborhoodConnectedImageFilter Functional Interface +itk::simple::NeighborhoodConnectedImageFilter Functional Interface This function directly calls the execute method of NeighborhoodConnectedImageFilter in order to support a fully functional API @@ -47059,7 +47079,7 @@ public "; Image itk::simple::OpeningByReconstruction(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, bool fullyConnected=false, bool preserveIntensities=false) - itk::simple::OpeningByReconstructionImageFilter Functional Interface +itk::simple::OpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of OpeningByReconstructionImageFilter in order to support a fully functional API @@ -47071,7 +47091,7 @@ Image itk::simple::OpeningByReconstruction(const Image &, const std::vector< uin kernel=sitkBall, bool fullyConnected=false, bool preserveIntensities=false) - itk::simple::OpeningByReconstructionImageFilter Functional Interface +itk::simple::OpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of OpeningByReconstructionImageFilter in order to support a fully functional API @@ -47174,7 +47194,7 @@ patchRadius=4u, uint32_t numberOfIterations=1u, uint32_t numberOfSamplePatches=200u, double sampleVariance=400.0, double noiseSigma=0.0, double noiseModelFidelityWeight=0.0) - itk::simple::PatchBasedDenoisingImageFilter Procedural Interface +itk::simple::PatchBasedDenoisingImageFilter Procedural Interface This function directly calls the execute method of PatchBasedDenoisingImageFilter in order to support a procedural API @@ -47319,7 +47339,7 @@ public "; %javamethodmodifiers itk::simple::RealAndImaginaryToComplex "/** Image itk::simple::RealAndImaginaryToComplex(const Image &image1, const Image &image2) - ComposeImageFilter combine several scalar images into a multicomponent image. +ComposeImageFilter combine several scalar images into a multicomponent image. This function directly calls the execute method of RealAndImaginaryToComplexImageFilter in order to support a procedural API @@ -47752,14 +47772,10 @@ The user can also select applications specifically for color images or environment variables. SITK_SHOW_COMMAND, SITK_SHOW_COLOR_COMMAND and SITK_SHOW_3D_COMMAND -allow the following tokens in their strings. - - - \"%a\" for the ImageJ application +allow the following tokens in their strings.\\\\li \\\\c \"%a\" for the ImageJ application \\\\li \\\\c \"%f\" +for SimpleITK's temporary image file - \"%f\" for SimpleITK's temporary image file - For example, the default SITK_SHOW_COMMAND string on Linux systems -is: +For example, the default SITK_SHOW_COMMAND string on Linux systems is: After token substitution it may become: @@ -47825,7 +47841,7 @@ public "; Image itk::simple::SignedDanielssonDistanceMap(const Image &image1, bool insideIsPositive=false, bool squaredDistance=false, bool useImageSpacing=false) - itk::simple::SignedDanielssonDistanceMapImageFilter Procedural Interface +itk::simple::SignedDanielssonDistanceMapImageFilter Procedural Interface This function directly calls the execute method of SignedDanielssonDistanceMapImageFilter in order to support a procedural API @@ -47960,7 +47976,7 @@ int32_t >(3, 0), const std::vector< int32_t > &stop=std::vector< int32_t >(3, std::numeric_limits< int32_t >::max()), const std::vector< int > &step=std::vector< int >(3, 1)) - itk::simple::SliceImageFilter Procedural Interface +itk::simple::SliceImageFilter Procedural Interface This function directly calls the execute method of SliceImageFilter in order to support a procedural API @@ -48395,7 +48411,7 @@ Image itk::simple::VectorConfidenceConnected(const Image &image1, const std::vec &seedList, unsigned int numberOfIterations=4u, double multiplier=4.5, unsigned int initialNeighborhoodRadius=1u, uint8_t replaceValue=1u) - itk::simple::VectorConfidenceConnectedImageFilter Functional Interface +itk::simple::VectorConfidenceConnectedImageFilter Functional Interface This function directly calls the execute method of VectorConfidenceConnectedImageFilter in order to support a fully functional API @@ -48541,7 +48557,7 @@ public "; Image itk::simple::WhiteTopHat(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::WhiteTopHatImageFilter Functional Interface +itk::simple::WhiteTopHatImageFilter Functional Interface This function directly calls the execute method of WhiteTopHatImageFilter in order to support a fully functional API @@ -48552,7 +48568,7 @@ public "; Image itk::simple::WhiteTopHat(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::WhiteTopHatImageFilter Functional Interface +itk::simple::WhiteTopHatImageFilter Functional Interface This function directly calls the execute method of WhiteTopHatImageFilter in order to support a fully functional API diff --git a/Wrapping/PythonDocstrings.i b/Wrapping/PythonDocstrings.i index c2fe9cec4..c5a29e079 100644 --- a/Wrapping/PythonDocstrings.i +++ b/Wrapping/PythonDocstrings.i @@ -10,7 +10,7 @@ C++ includes: itkBitwiseNotFunctor.h %feature("docstring") itk::Functor::DivFloor " - Cast arguments to double, performs division then takes the floor. +Cast arguments to double, performs division then takes the floor. C++ includes: itkDivideFloorFunctor.h "; @@ -124,7 +124,7 @@ C++ includes: itkSliceImageFilter.h %feature("docstring") itk::SliceImageFilter::GenerateOutputInformation " - SliceImageFilter produces an image which is a different resolution and with a +SliceImageFilter produces an image which is a different resolution and with a different pixel spacing than its input image. See: ProcessObject::GenerateOutputInformaton() @@ -937,7 +937,7 @@ iterative relaxation process of an estimated ND surface. The surface is described implicitly as the zero level set of a volume $ \\\\phi $ and allowed to deform under curvature flow. A set of contraints is imposed on this movement as follows: - \\\\[ u_{i,j,k}^{n+1} = \\\\left\\\\{ \\\\begin{array}{ll} +\\\\[ u_{i,j,k}^{n+1} = \\\\left\\\\{ \\\\begin{array}{ll} \\\\mbox{max} (u_{i,j,k}^{n} + \\\\Delta t H_{i,j,k}^{n}, 0) & \\\\mbox{\\\\f$B_{i,j,k} = 1\\\\f$} \\\\\\\\ \\\\mbox{min} (u_{i,j,k}^{n} + \\\\Delta t H_{i,j,k}^{n}, 0) & @@ -1473,7 +1473,7 @@ parameters fixed parameter %feature("docstring") itk::simple::BSplineTransformInitializerFilter " - BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such +BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such that it has a physically consistent definition. It sets the transform domain origin, physical dimensions and direction from information obtained from the image. It also sets the mesh size if asked to do so @@ -1928,7 +1928,7 @@ Destructor Labels the pixels on the border of the objects in a binary image. - BinaryContourImageFilter takes a binary image as input, where the pixels in the objects are +BinaryContourImageFilter takes a binary image as input, where the pixels in the objects are the pixels with a value equal to ForegroundValue. Only the pixels on the contours of the objects are kept. The pixels not on the border are changed to BackgroundValue. @@ -1936,7 +1936,7 @@ changed to BackgroundValue. The connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours. - http://hdl.handle.net/1926/1352 +http://hdl.handle.net/1926/1352 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -2059,7 +2059,7 @@ Destructor Fast binary dilation. - BinaryDilateImageFilter is a binary dilation morphologic operation. This implementation is +BinaryDilateImageFilter is a binary dilation morphologic operation. This implementation is based on the papers: L.Vincent \"Morphological transformations of binary images with @@ -2200,7 +2200,7 @@ Destructor Fast binary erosion. - BinaryErodeImageFilter is a binary erosion morphologic operation. This implementation is +BinaryErodeImageFilter is a binary erosion morphologic operation. This implementation is based on the papers: L.Vincent \"Morphological transformations of binary images with @@ -2342,7 +2342,7 @@ Destructor Remove holes not connected to the boundary of the image. - BinaryFillholeImageFilter fills holes in a binary image. +BinaryFillholeImageFilter fills holes in a binary image. Geodesic morphology and the Fillhole algorithm is described in Chapter 6 of Pierre Soille's book \"Morphological Image Analysis: Principles @@ -2449,7 +2449,7 @@ Destructor Remove the objects not connected to the boundary of the image. - BinaryGrindPeakImageFilter ginds peaks in a grayscale image. +BinaryGrindPeakImageFilter ginds peaks in a grayscale image. Geodesic morphology and the grind peak algorithm is described in Chapter 6 of Pierre Soille's book \"Morphological Image Analysis: @@ -2569,7 +2569,7 @@ Label the connected components in a binary image and produce a collection of label objects. - BinaryImageToLabelMapFilter labels the objects in a binary image. Each distinct object is +BinaryImageToLabelMapFilter labels the objects in a binary image. Each distinct object is assigned a unique label. The final object labels start with 1 and are consecutive. Objects that are reached earlier by a raster order scan have a lower label. @@ -2889,13 +2889,13 @@ Destructor Denoise a binary image using min/max curvature flow. - BinaryMinMaxCurvatureFlowImageFilter implements a curvature driven image denosing algorithm. This filter +BinaryMinMaxCurvatureFlowImageFilter implements a curvature driven image denosing algorithm. This filter assumes that the image is essentially binary: consisting of two classes. Iso-brightness contours in the input image are viewed as a level set. The level set is then evolved using a curvature-based speed function: - \\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] +\\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] where $ F_{\\\\mbox{minmax}} = \\\\min(\\\\kappa,0) $ if $ \\\\mbox{Avg}_{\\\\mbox{stencil}}(x) $ is less than or equal to $ T_{thresold} $ and $ \\\\max(\\\\kappa,0) $ , otherwise. $ \\\\kappa $ is the mean curvature of the iso-brightness contour at point $ x $ . @@ -4286,7 +4286,7 @@ This class is parameterized over the type of the input image and the type of the output image. It is also parameterized by the operation to be applied, using a Functor style. - UnaryFunctorImageFilter allows the output dimension of the filter to be larger than the input +UnaryFunctorImageFilter allows the output dimension of the filter to be larger than the input dimension. Thus subclasses of the UnaryFunctorImageFilter (like the CastImageFilter ) can be used to promote a 2D image to a 3D image, etc. @@ -4847,7 +4847,7 @@ Set/Get the output pixel type %feature("docstring") itk::simple::CenteredTransformInitializerFilter " - CenteredTransformInitializerFilter is a helper class intended to initialize the center of rotation and +CenteredTransformInitializerFilter is a helper class intended to initialize the center of rotation and the translation of Transforms having the center of rotation among their parameters. @@ -4874,12 +4874,7 @@ passes as the initial translation to the transform. This second approach assumes that the moments of the anatomical objects are similar for both images and hence the best initial guess for registration is to superimpose both mass centers. Note that this -assumption will probably not hold in multi-modality registration. - - -See: - itk::CenteredTransformInitializer - +assumption will probably not hold in multi-modality registration. \\\\sa itk::CenteredTransformInitializer C++ includes: sitkCenteredTransformInitializerFilter.h "; @@ -4944,7 +4939,7 @@ Destructor %feature("docstring") itk::simple::CenteredVersorTransformInitializerFilter " - CenteredVersorTransformInitializerFilter is a helper class intended to initialize the center of rotation, +CenteredVersorTransformInitializerFilter is a helper class intended to initialize the center of rotation, versor, and translation of the VersorRigid3DTransform. @@ -5174,7 +5169,7 @@ Destructor Combines two images in a checkerboard pattern. - CheckerBoardImageFilter takes two input images that must have the same dimension, size, +CheckerBoardImageFilter takes two input images that must have the same dimension, size, origin and spacing and produces an output image of the same size by combinining the pixels from the two input images in a checkerboard pattern. This filter is commonly used for visually comparing two @@ -5906,10 +5901,10 @@ Destructor %feature("docstring") itk::simple::ComposeImageFilter " - ComposeImageFilter combine several scalar images into a multicomponent image. +ComposeImageFilter combine several scalar images into a multicomponent image. - ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . +ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . Inputs and Usage All input images are expected to have the same template parameters @@ -6177,7 +6172,7 @@ Destructor Label the objects in a binary image. - ConnectedComponentImageFilter labels the objects in a binary image (non-zero pixels are considered +ConnectedComponentImageFilter labels the objects in a binary image (non-zero pixels are considered to be objects, zero-valued pixels are considered to be background). Each distinct object is assigned a unique label. The filter experiments with some improvements to the existing implementation, and @@ -6249,6 +6244,16 @@ Name of this class "; +%feature("docstring") itk::simple::ConnectedComponentImageFilter::GetObjectCount " + +After the filter is executed, holds the number of connected +components. + +This is a measurement. Its value is updated in the Execute methods, so +the value will only be valid after an execution. + +"; + %feature("docstring") itk::simple::ConnectedComponentImageFilter::SetFullyConnected " Set/Get whether the connected components are defined strictly by face @@ -6277,7 +6282,7 @@ Label pixels that are connected to a seed and lie within a range of values. - ConnectedThresholdImageFilter labels pixels with ReplaceValue that are connected to an initial Seed +ConnectedThresholdImageFilter labels pixels with ReplaceValue that are connected to an initial Seed AND lie within a Lower and Upper threshold range. See: itk::simple::ConnectedThreshold for the procedural interface @@ -6412,7 +6417,7 @@ Destructor Increase the image size by padding with a constant value. - ConstantPadImageFilter changes the output image region. If the output image region is larger +ConstantPadImageFilter changes the output image region. If the output image region is larger than the input image region, the extra pixels are filled in by a constant value. The output image region must be specified. @@ -6680,7 +6685,7 @@ Destructor Decrease the image size by cropping the image by an itk::Size at both the upper and lower bounds of the largest possible region. - CropImageFilter changes the image boundary of an image by removing pixels outside the +CropImageFilter changes the image boundary of an image by removing pixels outside the target region. The target region is not specified in advance, but calculated in BeforeThreadedGenerateData() . @@ -6874,12 +6879,12 @@ Destructor Denoise an image using curvature driven flow. - CurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- +CurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- brightness contours in the grayscale input image are viewed as a level set. The level set is then evolved using a curvature-based speed function: - \\\\[ I_t = \\\\kappa |\\\\nabla I| \\\\] where $ \\\\kappa $ is the curvature. +\\\\[ I_t = \\\\kappa |\\\\nabla I| \\\\] where $ \\\\kappa $ is the curvature. The advantage of this approach is that sharp boundaries are preserved with smoothing occurring only within a region. However, it should be @@ -7231,7 +7236,7 @@ Destructor Deformably register two images using the demons algorithm. - DemonsRegistrationFilter implements the demons deformable algorithm that register two images +DemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the displacement field which will map a moving image onto a fixed image. @@ -7671,7 +7676,7 @@ See T. Vercauteren, X. Pennec, A. Perchant and N. Ayache, \"Non- parametric Diffeomorphic Image Registration with the Demons Algorithm\", Proc. of MICCAI 2007. - DiffeomorphicDemonsRegistrationFilter implements the demons deformable algorithm that register two images +DiffeomorphicDemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the deformation field which will map a moving image onto a fixed image. @@ -8640,6 +8645,18 @@ C++ includes: sitkDisplacementFieldTransform.h "; %feature("docstring") itk::simple::DisplacementFieldTransform::DisplacementFieldTransform " + +Consume an image to construct a displacement field transform. + + + +WARNING: +The input displacement image is transferred to the constructed +transform object. The input image is modified to be a default +constructed Image object. +Image must be of sitkVectorFloat64 pixel type with the number of components +equal to the image dimension. + "; %feature("docstring") itk::simple::DisplacementFieldTransform::DisplacementFieldTransform " @@ -8651,7 +8668,7 @@ C++ includes: sitkDisplacementFieldTransform.h %feature("docstring") itk::simple::DisplacementFieldTransform::GetDisplacementField " Todo -The returned image is should not directly modify the internal +The returned image should not directly modify the internal displacement field. @@ -9630,7 +9647,7 @@ Destructor Expand the size of an image by an integer factor in each dimension. - ExpandImageFilter increases the size of an image by an integer factor in each dimension +ExpandImageFilter increases the size of an image by an integer factor in each dimension using a interpolation method. The output image size in each dimension is given by: @@ -9756,10 +9773,10 @@ Decrease the image size by cropping the image to the selected region bounds. - ExtractImageFilter changes the image boundary of an image by removing pixels outside the +ExtractImageFilter changes the image boundary of an image by removing pixels outside the target region. The target region must be specified. - ExtractImageFilter also collapses dimensions so that the input image may have more +ExtractImageFilter also collapses dimensions so that the input image may have more dimensions than the output image (i.e. 4-D input image to a 3-D output image). To specify what dimensions to collapse, the ExtractionRegion must be specified. For any dimension dim where @@ -9811,7 +9828,8 @@ Crop an image by specifying the region to keep See: itk::simple::Extract for the procedural interface - itk::ExtractImageFilter for the Doxygen on the original ITK class. + itk::ExtractImageFilter. The image is flipped across axes for which array[i] is true. @@ -11311,7 +11329,7 @@ it's valid when Execute is called with the clientData. Generate an n-dimensional image of a Gabor filter. - GaborImageSource generates an image of either the real (i.e. symmetric) or complex +GaborImageSource generates an image of either the real (i.e. symmetric) or complex (i.e. antisymmetric) part of the Gabor filter with the orientation directed along the x-axis. The GaborKernelFunction is used to evaluate the contribution along the x-axis whereas a non- normalized 1-D Gaussian envelope provides the contribution in each of @@ -11432,7 +11450,7 @@ Destructor Generate an n-dimensional image of a Gaussian. - GaussianImageSource generates an image of a Gaussian. m_Normalized determines whether or +GaussianImageSource generates an image of a Gaussian. m_Normalized determines whether or not the Gaussian is normalized (whether or not the sum over infinite space is 1.0) When creating an image, it is preferable tonotnormalize the Gaussian m_Scale scales the output of the Gaussian to span a range @@ -11667,7 +11685,7 @@ edge potential map. General characteristics of an edge potential map is that it has values close to zero in regions near the edges and values close to one inside the shape itself. Typically, the edge potential map is compute from the image gradient, for example: - \\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] +\\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] where $ I $ is image intensity and $ (\\\\nabla * G) $ is the derivative of Gaussian operator. @@ -12782,7 +12800,7 @@ Destructor Remove local minima not connected to the boundary of the image. - GrayscaleFillholeImageFilter fills holes in a grayscale image. Holes are local minima in the +GrayscaleFillholeImageFilter fills holes in a grayscale image. Holes are local minima in the grayscale topography that are not connected to boundaries of the image. Gray level values adjacent to a hole are extrapolated across the hole. @@ -13152,7 +13170,7 @@ Destructor Remove local maxima not connected to the boundary of the image. - GrayscaleGrindPeakImageFilter removes peaks in a grayscale image. Peaks are local maxima in the +GrayscaleGrindPeakImageFilter removes peaks in a grayscale image. Peaks are local maxima in the grayscale topography that are not connected to boundaries of the image. Gray level values adjacent to a peak are extrapolated through the peak. @@ -13723,7 +13741,7 @@ Destructor Generate an n-dimensional image of a grid. - GridImageSource generates an image of a grid. From the abstract... \"Certain classes +GridImageSource generates an image of a grid. From the abstract... \"Certain classes of images find disparate use amongst members of the ITK community for such purposes as visualization, simulation, testing, etc. Currently there exists two derived classes from the ImageSource class used for @@ -13853,7 +13871,7 @@ Identify local minima whose depth below the baseline is greater than h. - HConcaveImageFilter extract local minima that are more than h intensity units below the +HConcaveImageFilter extract local minima that are more than h intensity units below the (local) background. This has the effect of extracting objects that are darker than the background by at least h intensity units. @@ -13967,7 +13985,7 @@ Identify local maxima whose height above the baseline is greater than h. - HConvexImageFilter extract local maxima that are more than h intensity units above the +HConvexImageFilter extract local maxima that are more than h intensity units above the (local) background. This has the effect of extracting objects that are brighter than background by at least h intensity units. @@ -14080,7 +14098,7 @@ Destructor Suppress local maxima whose height above the baseline is less than h. - HMaximaImageFilter suppresses local maxima that are less than h intensity units above +HMaximaImageFilter suppresses local maxima that are less than h intensity units above the (local) background. This has the effect of smoothing over the \"high\" parts of the noise in the image without smoothing over large changes in intensity (region boundaries). See the HMinimaImageFilter to suppress the local minima whose depth is less than h intensity @@ -14175,7 +14193,7 @@ Destructor Suppress local minima whose depth below the baseline is less than h. - HMinimaImageFilter suppresses local minima that are less than h intensity units below +HMinimaImageFilter suppresses local minima that are less than h intensity units below the (local) background. This has the effect of smoothing over the \"low\" parts of the noise in the image without smoothing over large changes in intensity (region boundaries). See the HMaximaImageFilter to suppress the local maxima whose height is less than h intensity @@ -14423,7 +14441,7 @@ Computes the Hausdorff distance between the set of non-zero pixels of two images. - HausdorffDistanceImageFilter computes the distance between the set non-zero pixels of two images +HausdorffDistanceImageFilter computes the distance between the set non-zero pixels of two images using the following formula: \\\\[ H(A,B) = \\\\max(h(A,B),h(B,A)) \\\\] where \\\\[ h(A,B) = \\\\max_{a \\\\in A} \\\\min_{b \\\\in B} \\\\| a - b\\\\| \\\\] is the directed Hausdorff distance and $A$ and $B$ are respectively the set of non-zero pixels in the first and second input images. @@ -14513,7 +14531,7 @@ Normalize the grayscale values between two images by histogram matching. - HistogramMatchingImageFilter normalizes the grayscale values of a source image based on the +HistogramMatchingImageFilter normalizes the grayscale values of a source image based on the grayscale values of a reference image. This filter uses a histogram matching technique where the histograms of the two images are matched only at a specified number of quantile values. @@ -14527,7 +14545,7 @@ grayscale values are smaller than the mean grayscale value. ThresholdAtMeanInten The source image can be set via either SetInput() or SetSourceImage() . The reference image can be set via SetReferenceImage() . - SetNumberOfHistogramLevels() sets the number of bins used when creating histograms of the source +SetNumberOfHistogramLevels() sets the number of bins used when creating histograms of the source and reference images. SetNumberOfMatchPoints() governs the number of quantile values to be matched. This filter assumes that both the source and reference are of the same @@ -14890,25 +14908,25 @@ make sure that coping actually happens to the itk::Image pointed to is only poin %feature("docstring") itk::simple::Image::TransformContinuousIndexToPhysicalPoint " - Transform continuous index to physical point +Transform continuous index to physical point "; %feature("docstring") itk::simple::Image::TransformIndexToPhysicalPoint " - Transform index to physical point +Transform index to physical point "; %feature("docstring") itk::simple::Image::TransformPhysicalPointToContinuousIndex " - Transform physical point to continuous index +Transform physical point to continuous index "; %feature("docstring") itk::simple::Image::TransformPhysicalPointToIndex " - Transform physical point to index +Transform physical point to index "; @@ -15179,6 +15197,7 @@ See: Use demons image metric. + See: itk::DemonsImageToImageMetricv4 @@ -15623,7 +15642,7 @@ are mapped to a constant. Values over the interval are mapped to another constant. - IntensityWindowingImageFilter applies pixel-wise a linear transformation to the intensity values of +IntensityWindowingImageFilter applies pixel-wise a linear transformation to the intensity values of input image pixels. The linear transformation is defined by the user in terms of the minimum and maximum values that the output image should have and the lower and upper limits of the intensity window of @@ -15638,7 +15657,7 @@ Wiki Examples: All Examples - IntensityWindowingImageFilter +IntensityWindowingImageFilter See: RescaleIntensityImageFilter @@ -16008,7 +16027,7 @@ Destructor Computes the inverse of a displacement field. - InverseDisplacementFieldImageFilter takes a displacement field as input and computes the displacement +InverseDisplacementFieldImageFilter takes a displacement field as input and computes the displacement field that is its inverse. If the input displacement field was mapping coordinates from a space A into a space B, the output of this filter will map coordinates from the space B into the space A. @@ -16317,7 +16336,7 @@ Destructor Invert the intensity of an image. - InvertIntensityImageFilter inverts intensity of pixels by subtracting pixel value to a maximum +InvertIntensityImageFilter inverts intensity of pixels by subtracting pixel value to a maximum value. The maximum value can be set with SetMaximum and defaults the maximum of input pixel type. This filter can be used to invert, for example, a binary image, a distance map, etc. @@ -16634,7 +16653,7 @@ Destructor Label pixels that are connected to one set of seeds but not another. - IsolatedConnectedImageFilter finds the optimal threshold to separate two regions. It has two +IsolatedConnectedImageFilter finds the optimal threshold to separate two regions. It has two modes, one to separate dark regions surrounded by bright regions by automatically finding a minimum isolating upper threshold, and another to separate bright regions surrounded by dark regions by automatically @@ -16837,7 +16856,7 @@ Destructor Isolate watershed basins using two seeds. - IsolatedWatershedImageFilter labels pixels with ReplaceValue1 that are in the same watershed basin +IsolatedWatershedImageFilter labels pixels with ReplaceValue1 that are in the same watershed basin as Seed1 AND NOT the same as Seed2. The filter adjusts the waterlevel until the two seeds are not in different basins. The user supplies a Watershed threshold. The algorithm uses a binary search to adjust the @@ -17255,7 +17274,7 @@ Destructor Labels the pixels on the border of the objects in a labeled image. - LabelContourImageFilter takes a labeled image as input, where the pixels in the objects are +LabelContourImageFilter takes a labeled image as input, where the pixels in the objects are the pixels with a value different of the BackgroundValue. Only the pixels on the contours of the objects are kept. The pixels not on the border are changed to BackgroundValue. The labels of the object are @@ -17264,7 +17283,7 @@ the same in the input and in the output image. The connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours. - http://hdl.handle.net/1926/1352 +http://hdl.handle.net/1926/1352 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -17373,7 +17392,7 @@ Destructor convert a labeled image to a label collection image - LabelImageToLabelMapFilter converts a label image to a label collection image. The labels are +LabelImageToLabelMapFilter converts a label image to a label collection image. The labels are the same in the input and the output image. @@ -17611,7 +17630,7 @@ Destructor Mask and image with a LabelMap . - LabelMapMaskImageFilter mask the content of an input image according to the content of the +LabelMapMaskImageFilter mask the content of an input image according to the content of the input LabelMap . The masked pixel of the input image are set to the BackgroundValue. LabelMapMaskImageFilter can keep the input image for one label only, with Negated = false (the default) or it can mask the input image for a single label, when Negated equals true. In Both cases, the label is set with SetLabel() . @@ -17850,7 +17869,7 @@ Destructor Convert a LabelMap to a binary image. - LabelMapToBinaryImageFilter to a binary image. All the objects in the image are used as +LabelMapToBinaryImageFilter to a binary image. All the objects in the image are used as foreground. The background values of the original binary image can be restored by passing this image to the filter with the SetBackgroundImage() method. @@ -17943,7 +17962,7 @@ Destructor Converts a LabelMap to a labeled image. - LabelMapToBinaryImageFilter to a label image. +LabelMapToBinaryImageFilter to a label image. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -18274,7 +18293,7 @@ valuates the shape attribute at once. This implementation was taken from the Insight Journal paper: - http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -18555,7 +18574,7 @@ Given an intensity image and a label map, compute min, max, variance and mean of the pixels associated with each label or segment. - LabelStatisticsImageFilter computes the minimum, maximum, sum, mean, median, variance and sigma +LabelStatisticsImageFilter computes the minimum, maximum, sum, mean, median, variance and sigma of regions of an intensity image, where the regions are defined via a label map (a second input). The label image should be integral type. The filter needs all of its input image. It behaves as a filter with @@ -18840,7 +18859,7 @@ Destructor Make sure that the objects are not overlapping. - AttributeUniqueLabelMapFilter search the overlapping zones in the overlapping objects and keeps +AttributeUniqueLabelMapFilter search the overlapping zones in the overlapping objects and keeps only a single object on all the pixels of the image. The object to keep is selected according to their label. @@ -20785,14 +20804,14 @@ calculated and the one that gives the largest number of pixels is chosen. Since these both default to 0, if a user only sets one, the other is ignored. - Image size: fixedImage and movingImage need not be the same size, but +Image size: fixedImage and movingImage need not be the same size, but fixedMask must be the same size as fixedImage, and movingMask must be the same size as movingImage. Furthermore, whereas some algorithms require that the \"template\" be smaller than the \"image\" because of errors in the regions where the two are not fully overlapping, this filter has no such restriction. - Image spacing: Since the computations are done in the pixel domain, all +Image spacing: Since the computations are done in the pixel domain, all input images must have the same spacing. Outputs; The output is an image of RealPixelType that is the masked @@ -21543,7 +21562,7 @@ Merges several Label Maps. This filter takes one or more input Label Map and merges them. - SetMethod() can be used to change how the filter manage the labels from the +SetMethod() can be used to change how the filter manage the labels from the different label maps. KEEP (0): MergeLabelMapFilter do its best to keep the label unchanged, but if a label is already used in a previous label map, a new label is assigned. AGGREGATE (1): If the same label is found several times in the label maps, the label @@ -21651,12 +21670,12 @@ Destructor Denoise an image using min/max curvature flow. - MinMaxCurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- +MinMaxCurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- brightness contours in the grayscale input image are viewed as a level set. The level set is then evolved using a curvature-based speed function: - \\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] +\\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] where $ F_{\\\\mbox{minmax}} = \\\\max(\\\\kappa,0) $ if $ \\\\mbox{Avg}_{\\\\mbox{stencil}}(x) $ is less than or equal to $ T_{thresold} $ and $ \\\\min(\\\\kappa,0) $ , otherwise. $ \\\\kappa $ is the mean curvature of the iso-brightness contour at point $ x $ . @@ -21989,7 +22008,7 @@ Increase the image size by padding with replicants of the input image value. - MirrorPadImageFilter changes the image bounds of an image. Any added pixels are filled in +MirrorPadImageFilter changes the image bounds of an image. Any added pixels are filled in with a mirrored replica of the input image. For instance, if the output image needs a pixel that istwo pixels to the left of the LargestPossibleRegionof the input image, the value assigned will be @@ -23105,7 +23124,7 @@ Label pixels that are connected to a seed and lie within a neighborhood. - NeighborhoodConnectedImageFilter labels pixels with ReplaceValue that are connected to an initial Seed +NeighborhoodConnectedImageFilter labels pixels with ReplaceValue that are connected to an initial Seed AND whose neighbors all lie within a Lower and Upper threshold range. See: itk::simple::NeighborhoodConnected for the procedural interface @@ -23362,7 +23381,7 @@ C++ includes: sitkNonCopyable.h Normalize an image by setting its mean to zero and variance to one. - NormalizeImageFilter shifts and scales an image so that the pixels in the image have a +NormalizeImageFilter shifts and scales an image so that the pixels in the image have a zero mean and unit variance. This filter uses StatisticsImageFilter to compute the mean and variance of the input and then applies ShiftScaleImageFilter to shift and scale the pixels. NB: since this filter normalizes the data to lie within -1 to 1, @@ -24286,7 +24305,7 @@ Destructor Paste an image into another image. - PasteImageFilter allows you to take a section of one image and paste into another +PasteImageFilter allows you to take a section of one image and paste into another image. The SetDestinationIndex() method prescribes where in the first input to start pasting data from the second input. The SetSourceRegion method prescribes the section of the second image to paste into the first. If the output requested @@ -25520,10 +25539,10 @@ Destructor %feature("docstring") itk::simple::RealAndImaginaryToComplexImageFilter " - ComposeImageFilter combine several scalar images into a multicomponent image. +ComposeImageFilter combine several scalar images into a multicomponent image. - ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . +ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . Inputs and Usage All input images are expected to have the same template parameters @@ -25876,10 +25895,10 @@ Base class for computing IIR convolution with an approximation of a Gaussian kernel. - \\\\[ \\\\frac{ 1 }{ \\\\sigma \\\\sqrt{ 2 \\\\pi } } \\\\exp{ +\\\\[ \\\\frac{ 1 }{ \\\\sigma \\\\sqrt{ 2 \\\\pi } } \\\\exp{ \\\\left( - \\\\frac{x^2}{ 2 \\\\sigma^2 } \\\\right) } \\\\] - RecursiveGaussianImageFilter is the base class for recursive filters that approximate convolution +RecursiveGaussianImageFilter is the base class for recursive filters that approximate convolution with the Gaussian kernel. This class implements the recursive filtering method proposed by R.Deriche in IEEE-PAMI Vol.12, No.1, January 1990, pp 78-87, \"Fast Algorithms for Low-Level Vision\" @@ -25994,7 +26013,7 @@ Let \\\\[ L(x; t) = g(x; t) \\\\ast f(x) \\\\] be the scale-space representation Then the normalized derivative operator for normalized coordinates across scale is: - \\\\[ \\\\partial_\\\\xi = \\\\sqrt{t} \\\\partial_x \\\\] +\\\\[ \\\\partial_\\\\xi = \\\\sqrt{t} \\\\partial_x \\\\] The resulting scaling factor is \\\\[ \\\\sigma^N \\\\] where N is the order of the derivative. @@ -26170,7 +26189,7 @@ Wiki Examples: All Examples - RegionalMaximaImageFilter +RegionalMaximaImageFilter See: itk::simple::RegionalMaxima for the procedural interface @@ -26311,7 +26330,7 @@ a minima or not. The SetFlatIsMinima() method let the user choose which behavior This class was contribtued to the Insight Journal by Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. http://hdl.handle.net/1926/153 - RegionalMaximaImageFilter MathematicalMorphologyImageFilters +RegionalMaximaImageFilter MathematicalMorphologyImageFilters See: @@ -26323,7 +26342,7 @@ Wiki Examples: All Examples - RegionalMinimaImageFilter +RegionalMinimaImageFilter See: itk::simple::RegionalMinima for the procedural interface @@ -26456,7 +26475,7 @@ Relabel the components in an image such that consecutive labels are used. - RelabelComponentImageFilter remaps the labels associated with the objects in an image (as from +RelabelComponentImageFilter remaps the labels associated with the objects in an image (as from the output of ConnectedComponentImageFilter ) such that the label numbers are consecutive with no gaps between the label numbers used. By default, the relabeling will also sort the labels based on the size of the object: the largest object will have @@ -26467,7 +26486,7 @@ can be disabled using SetSortByObjectSize. Label #0 is assumed to be the background and is left unaltered by the relabeling. - RelabelComponentImageFilter is typically used on the output of the ConnectedComponentImageFilter for those applications that want to extract the largest object or the +RelabelComponentImageFilter is typically used on the output of the ConnectedComponentImageFilter for those applications that want to extract the largest object or the \"k\" largest objects. Any particular object can be extracted from the relabeled output using a BinaryThresholdImageFilter . A group of objects can be extracted from the relabled output using a ThresholdImageFilter . @@ -26483,7 +26502,7 @@ will be only those remaining. The GetOriginalNumberOfObjects method can be called to find out how many objects were present before the small ones were discarded. - RelabelComponentImageFilter can be run as an \"in place\" filter, where it will overwrite its +RelabelComponentImageFilter can be run as an \"in place\" filter, where it will overwrite its output. The default is run out of place (or generate a separate output). \"In place\" operation can be controlled via methods in the superclass, InPlaceImageFilter::InPlaceOn() and @@ -26796,7 +26815,7 @@ Destructor Resample an image via a coordinate transform. - ResampleImageFilter resamples an existing image through some coordinate transform, +ResampleImageFilter resamples an existing image through some coordinate transform, interpolating via some image function. The class is templated over the types of the input and output images. @@ -27009,7 +27028,7 @@ Destructor Applies a linear transformation to the intensity levels of the input Image . - RescaleIntensityImageFilter applies pixel-wise a linear transformation to the intensity values of +RescaleIntensityImageFilter applies pixel-wise a linear transformation to the intensity values of input image pixels. The linear transformation is defined by the user in terms of the minimum and maximum values that the output image should have. @@ -27017,7 +27036,7 @@ should have. The following equation gives the mapping of the intensity values - \\\\[ outputPixel = ( inputPixel - inputMin) \\\\cdot +\\\\[ outputPixel = ( inputPixel - inputMin) \\\\cdot \\\\frac{(outputMax - outputMin )}{(inputMax - inputMin)} + outputMin \\\\] All computations are performed in the precison of the input pixel's @@ -28415,7 +28434,7 @@ edge potential map. General characteristics of an edge potential map is that it has values close to zero in regions near the edges and values close to one inside the shape itself. Typically, the edge potential map is compute from the image gradient, for example: - \\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] +\\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] where $ I $ is image intensity and $ (\\\\nabla * G) $ is the derivative of Gaussian operator. @@ -28570,7 +28589,7 @@ Destructor Shift and scale the pixels in an image. - ShiftScaleImageFilter shifts the input pixel by Shift (default 0.0) and then scales the +ShiftScaleImageFilter shifts the input pixel by Shift (default 0.0) and then scales the pixel by Scale (default 1.0). All computattions are performed in the precison of the input pixel's RealType. Before assigning the computed value to the output pixel, the value is clamped at the NonpositiveMin @@ -28731,7 +28750,7 @@ Destructor Reduce the size of an image by an integer factor in each dimension. - ShrinkImageFilter reduces the size of an image by an integer factor in each dimension. +ShrinkImageFilter reduces the size of an image by an integer factor in each dimension. The algorithm implemented is a simple subsample. The output image size in each dimension is given by: @@ -28829,7 +28848,7 @@ Computes the sigmoid function pixel-wise. A linear transformation is applied first on the argument of the sigmoid fuction. The resulting total transfrom is given by - \\\\[ f(x) = (Max-Min) \\\\cdot \\\\frac{1}{\\\\left(1+e^{- \\\\frac{ +\\\\[ f(x) = (Max-Min) \\\\cdot \\\\frac{1}{\\\\left(1+e^{- \\\\frac{ x - \\\\beta }{\\\\alpha}}\\\\right)} + Min \\\\] Every output pixel is equal to f(x). Where x is the intensity of the @@ -29364,7 +29383,7 @@ Measures the similarity between the set of non-zero pixels of two images. - SimilarityIndexImageFilter measures the similarity between the set non-zero pixels of two images +SimilarityIndexImageFilter measures the similarity between the set non-zero pixels of two images using the following formula: \\\\[ S = \\\\frac{2 | A \\\\cap B |}{|A| + |B|} \\\\] where $A$ and $B$ are respectively the set of non-zero pixels in the first and second input images. Operator $|\\\\cdot|$ represents the size of a set and $\\\\cap$ represents the intersection of two sets. @@ -29838,7 +29857,7 @@ Wiki Examples: All Examples - SobelEdgeDetectionImageFilter +SobelEdgeDetectionImageFilter See: itk::simple::SobelEdgeDetection for the procedural interface @@ -30230,7 +30249,7 @@ Destructor Compute min. max, variance and mean of an Image . - StatisticsImageFilter computes the minimum, maximum, sum, mean, variance sigma of an image. +StatisticsImageFilter computes the minimum, maximum, sum, mean, variance sigma of an image. The filter needs all of its input image. It behaves as a filter with an input and output. Thus it can be inserted in a pipline with other filters and the statistics will only be recomputed if a downstream @@ -30517,7 +30536,7 @@ Switzerland. based on a variation of the DemonsRegistrationFilter . The basic mo along with the modification for avoiding large deformations when gradients have small values. - SymmetricForcesDemonsRegistrationFilter implements the demons deformable algorithm that register two images +SymmetricForcesDemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the deformation field which will map a moving image onto a fixed image. @@ -31003,7 +31022,7 @@ Set image values to a user-specified value if they are below, above, or between simple threshold values. - ThresholdImageFilter sets image values to a user-specified \"outside\" value (by default, +ThresholdImageFilter sets image values to a user-specified \"outside\" value (by default, \"black\") if the image values are below, above, or between simple threshold values. @@ -32222,7 +32241,7 @@ Wiki Examples: All Examples - ValuedRegionalMaximaImageFilter +ValuedRegionalMaximaImageFilter See: itk::simple::ValuedRegionalMaxima for the procedural interface @@ -32320,7 +32339,7 @@ Wiki Examples: All Examples - ValuedRegionalMinimaImageFilter +ValuedRegionalMinimaImageFilter See: itk::simple::ValuedRegionalMinima for the procedural interface @@ -32798,7 +32817,7 @@ Destructor %feature("docstring") itk::simple::Version " - Version info for SimpleITK. +Version info for SimpleITK. C++ includes: sitkVersion.h "; @@ -33370,7 +33389,7 @@ Destructor Warps an image using an input displacement field. - WarpImageFilter warps an existing image with respect to a given displacement field. +WarpImageFilter warps an existing image with respect to a given displacement field. A displacement field is represented as a image whose pixel type is some vector type with at least N elements, where N is the dimension of @@ -33385,7 +33404,7 @@ Each vector in the displacement field represent the distance between a geometric point in the input space and a point in the output space such that: - \\\\[ p_{in} = p_{out} + d \\\\] +\\\\[ p_{in} = p_{out} + d \\\\] Typically the mapped position does not correspond to an integer pixel position in the input image. Interpolation via an image function is @@ -33794,7 +33813,7 @@ Increase the image size by padding with replicants of the input image value. - WrapPadImageFilter changes the image bounds of an image. Added pixels are filled in with +WrapPadImageFilter changes the image bounds of an image. Added pixels are filled in with a wrapped replica of the input image. For instance, if the output image needs a pixel that istwo pixels to the left of the LargestPossibleRegionof the input image, the value assigned will be @@ -34832,7 +34851,7 @@ See: %feature("docstring") itk::simple::BinaryClosingByReconstruction " - itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface +itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryClosingByReconstructionImageFilter in order to support a fully functional API @@ -34840,7 +34859,7 @@ This function directly calls the execute method of BinaryClosingByReconstruction %feature("docstring") itk::simple::BinaryClosingByReconstruction " - itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface +itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryClosingByReconstructionImageFilter in order to support a fully functional API @@ -34862,7 +34881,7 @@ See: %feature("docstring") itk::simple::BinaryDilate " - itk::simple::BinaryDilateImageFilter Functional Interface +itk::simple::BinaryDilateImageFilter Functional Interface This function directly calls the execute method of BinaryDilateImageFilter in order to support a fully functional API @@ -34870,7 +34889,7 @@ This function directly calls the execute method of BinaryDilateImageFilter in or %feature("docstring") itk::simple::BinaryDilate " - itk::simple::BinaryDilateImageFilter Functional Interface +itk::simple::BinaryDilateImageFilter Functional Interface This function directly calls the execute method of BinaryDilateImageFilter in order to support a fully functional API @@ -34878,7 +34897,7 @@ This function directly calls the execute method of BinaryDilateImageFilter in or %feature("docstring") itk::simple::BinaryErode " - itk::simple::BinaryErodeImageFilter Functional Interface +itk::simple::BinaryErodeImageFilter Functional Interface This function directly calls the execute method of BinaryErodeImageFilter in order to support a fully functional API @@ -34886,7 +34905,7 @@ This function directly calls the execute method of BinaryErodeImageFilter in ord %feature("docstring") itk::simple::BinaryErode " - itk::simple::BinaryErodeImageFilter Functional Interface +itk::simple::BinaryErodeImageFilter Functional Interface This function directly calls the execute method of BinaryErodeImageFilter in order to support a fully functional API @@ -34980,7 +34999,7 @@ See: %feature("docstring") itk::simple::BinaryMorphologicalClosing " - itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface +itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalClosingImageFilter in order to support a fully functional API @@ -34988,7 +35007,7 @@ This function directly calls the execute method of BinaryMorphologicalClosingIma %feature("docstring") itk::simple::BinaryMorphologicalClosing " - itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface +itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalClosingImageFilter in order to support a fully functional API @@ -34996,7 +35015,7 @@ This function directly calls the execute method of BinaryMorphologicalClosingIma %feature("docstring") itk::simple::BinaryMorphologicalOpening " - itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface +itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalOpeningImageFilter in order to support a fully functional API @@ -35004,7 +35023,7 @@ This function directly calls the execute method of BinaryMorphologicalOpeningIma %feature("docstring") itk::simple::BinaryMorphologicalOpening " - itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface +itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalOpeningImageFilter in order to support a fully functional API @@ -35027,7 +35046,7 @@ See: %feature("docstring") itk::simple::BinaryOpeningByReconstruction " - itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface +itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryOpeningByReconstructionImageFilter in order to support a fully functional API @@ -35035,7 +35054,7 @@ This function directly calls the execute method of BinaryOpeningByReconstruction %feature("docstring") itk::simple::BinaryOpeningByReconstruction " - itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface +itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryOpeningByReconstructionImageFilter in order to support a fully functional API @@ -35170,7 +35189,7 @@ See: %feature("docstring") itk::simple::BlackTopHat " - itk::simple::BlackTopHatImageFilter Functional Interface +itk::simple::BlackTopHatImageFilter Functional Interface This function directly calls the execute method of BlackTopHatImageFilter in order to support a fully functional API @@ -35178,7 +35197,7 @@ This function directly calls the execute method of BlackTopHatImageFilter in ord %feature("docstring") itk::simple::BlackTopHat " - itk::simple::BlackTopHatImageFilter Functional Interface +itk::simple::BlackTopHatImageFilter Functional Interface This function directly calls the execute method of BlackTopHatImageFilter in order to support a fully functional API @@ -35230,7 +35249,7 @@ See: %feature("docstring") itk::simple::BSplineTransformInitializer " - BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such +BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such that it has a physically consistent definition. It sets the transform domain origin, physical dimensions and direction from information obtained from the image. It also sets the mesh size if asked to do so @@ -35267,7 +35286,7 @@ See: %feature("docstring") itk::simple::CenteredTransformInitializer " - CenteredTransformInitializer is a helper class intended to initialize the center of rotation and +CenteredTransformInitializer is a helper class intended to initialize the center of rotation and the translation of Transforms having the center of rotation among their parameters. @@ -35283,7 +35302,7 @@ See: %feature("docstring") itk::simple::CenteredVersorTransformInitializer " - CenteredVersorTransformInitializer is a helper class intended to initialize the center of rotation, +CenteredVersorTransformInitializer is a helper class intended to initialize the center of rotation, versor, and translation of the VersorRigid3DTransform. @@ -35357,7 +35376,7 @@ See: %feature("docstring") itk::simple::ClosingByReconstruction " - itk::simple::ClosingByReconstructionImageFilter Functional Interface +itk::simple::ClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of ClosingByReconstructionImageFilter in order to support a fully functional API @@ -35365,7 +35384,7 @@ This function directly calls the execute method of ClosingByReconstructionImageF %feature("docstring") itk::simple::ClosingByReconstruction " - itk::simple::ClosingByReconstructionImageFilter Functional Interface +itk::simple::ClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of ClosingByReconstructionImageFilter in order to support a fully functional API @@ -35444,7 +35463,7 @@ See: %feature("docstring") itk::simple::ConfidenceConnected " - itk::simple::ConfidenceConnectedImageFilter Functional Interface +itk::simple::ConfidenceConnectedImageFilter Functional Interface This function directly calls the execute method of ConfidenceConnectedImageFilter in order to support a fully functional API @@ -35466,7 +35485,7 @@ See: %feature("docstring") itk::simple::ConnectedThreshold " - itk::simple::ConnectedThresholdImageFilter Functional Interface +itk::simple::ConnectedThresholdImageFilter Functional Interface This function directly calls the execute method of ConnectedThresholdImageFilter in order to support a fully functional API @@ -35533,7 +35552,7 @@ See: %feature("docstring") itk::simple::CurvatureAnisotropicDiffusion " - itk::simple::CurvatureAnisotropicDiffusionImageFilter Procedural Interface +itk::simple::CurvatureAnisotropicDiffusionImageFilter Procedural Interface This function directly calls the execute method of CurvatureAnisotropicDiffusionImageFilter in order to support a procedural API @@ -35606,7 +35625,7 @@ See: %feature("docstring") itk::simple::DilateObjectMorphology " - itk::simple::DilateObjectMorphologyImageFilter Functional Interface +itk::simple::DilateObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of DilateObjectMorphologyImageFilter in order to support a fully functional API @@ -35614,7 +35633,7 @@ This function directly calls the execute method of DilateObjectMorphologyImageFi %feature("docstring") itk::simple::DilateObjectMorphology " - itk::simple::DilateObjectMorphologyImageFilter Functional Interface +itk::simple::DilateObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of DilateObjectMorphologyImageFilter in order to support a fully functional API @@ -35785,7 +35804,7 @@ See: %feature("docstring") itk::simple::ErodeObjectMorphology " - itk::simple::ErodeObjectMorphologyImageFilter Functional Interface +itk::simple::ErodeObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of ErodeObjectMorphologyImageFilter in order to support a fully functional API @@ -35793,7 +35812,7 @@ This function directly calls the execute method of ErodeObjectMorphologyImageFil %feature("docstring") itk::simple::ErodeObjectMorphology " - itk::simple::ErodeObjectMorphologyImageFilter Functional Interface +itk::simple::ErodeObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of ErodeObjectMorphologyImageFilter in order to support a fully functional API @@ -35886,7 +35905,7 @@ See: %feature("docstring") itk::simple::FastMarchingBase " - itk::simple::FastMarchingBaseImageFilter Functional Interface +itk::simple::FastMarchingBaseImageFilter Functional Interface This function directly calls the execute method of FastMarchingBaseImageFilter in order to support a fully functional API @@ -36055,7 +36074,7 @@ See: %feature("docstring") itk::simple::GradientAnisotropicDiffusion " - itk::simple::GradientAnisotropicDiffusionImageFilter Procedural Interface +itk::simple::GradientAnisotropicDiffusionImageFilter Procedural Interface This function directly calls the execute method of GradientAnisotropicDiffusionImageFilter in order to support a procedural API @@ -36143,7 +36162,7 @@ See: %feature("docstring") itk::simple::GrayscaleDilate " - itk::simple::GrayscaleDilateImageFilter Functional Interface +itk::simple::GrayscaleDilateImageFilter Functional Interface This function directly calls the execute method of GrayscaleDilateImageFilter in order to support a fully functional API @@ -36151,7 +36170,7 @@ This function directly calls the execute method of GrayscaleDilateImageFilter in %feature("docstring") itk::simple::GrayscaleDilate " - itk::simple::GrayscaleDilateImageFilter Functional Interface +itk::simple::GrayscaleDilateImageFilter Functional Interface This function directly calls the execute method of GrayscaleDilateImageFilter in order to support a fully functional API @@ -36159,7 +36178,7 @@ This function directly calls the execute method of GrayscaleDilateImageFilter in %feature("docstring") itk::simple::GrayscaleErode " - itk::simple::GrayscaleErodeImageFilter Functional Interface +itk::simple::GrayscaleErodeImageFilter Functional Interface This function directly calls the execute method of GrayscaleErodeImageFilter in order to support a fully functional API @@ -36167,7 +36186,7 @@ This function directly calls the execute method of GrayscaleErodeImageFilter in %feature("docstring") itk::simple::GrayscaleErode " - itk::simple::GrayscaleErodeImageFilter Functional Interface +itk::simple::GrayscaleErodeImageFilter Functional Interface This function directly calls the execute method of GrayscaleErodeImageFilter in order to support a fully functional API @@ -36231,7 +36250,7 @@ See: %feature("docstring") itk::simple::GrayscaleMorphologicalClosing " - itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalClosingImageFilter in order to support a fully functional API @@ -36239,7 +36258,7 @@ This function directly calls the execute method of GrayscaleMorphologicalClosing %feature("docstring") itk::simple::GrayscaleMorphologicalClosing " - itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalClosingImageFilter in order to support a fully functional API @@ -36247,7 +36266,7 @@ This function directly calls the execute method of GrayscaleMorphologicalClosing %feature("docstring") itk::simple::GrayscaleMorphologicalOpening " - itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalOpeningImageFilter in order to support a fully functional API @@ -36255,7 +36274,7 @@ This function directly calls the execute method of GrayscaleMorphologicalOpening %feature("docstring") itk::simple::GrayscaleMorphologicalOpening " - itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalOpeningImageFilter in order to support a fully functional API @@ -36836,7 +36855,7 @@ See: %feature("docstring") itk::simple::Laplacian " - itk::simple::LaplacianImageFilter Procedural Interface +itk::simple::LaplacianImageFilter Procedural Interface This function directly calls the execute method of LaplacianImageFilter in order to support a procedural API @@ -37267,7 +37286,7 @@ See: %feature("docstring") itk::simple::MorphologicalGradient " - itk::simple::MorphologicalGradientImageFilter Functional Interface +itk::simple::MorphologicalGradientImageFilter Functional Interface This function directly calls the execute method of MorphologicalGradientImageFilter in order to support a fully functional API @@ -37275,7 +37294,7 @@ This function directly calls the execute method of MorphologicalGradientImageFil %feature("docstring") itk::simple::MorphologicalGradient " - itk::simple::MorphologicalGradientImageFilter Functional Interface +itk::simple::MorphologicalGradientImageFilter Functional Interface This function directly calls the execute method of MorphologicalGradientImageFilter in order to support a fully functional API @@ -37345,7 +37364,7 @@ See: %feature("docstring") itk::simple::NeighborhoodConnected " - itk::simple::NeighborhoodConnectedImageFilter Functional Interface +itk::simple::NeighborhoodConnectedImageFilter Functional Interface This function directly calls the execute method of NeighborhoodConnectedImageFilter in order to support a fully functional API @@ -37445,7 +37464,7 @@ See: %feature("docstring") itk::simple::OpeningByReconstruction " - itk::simple::OpeningByReconstructionImageFilter Functional Interface +itk::simple::OpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of OpeningByReconstructionImageFilter in order to support a fully functional API @@ -37453,7 +37472,7 @@ This function directly calls the execute method of OpeningByReconstructionImageF %feature("docstring") itk::simple::OpeningByReconstruction " - itk::simple::OpeningByReconstructionImageFilter Functional Interface +itk::simple::OpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of OpeningByReconstructionImageFilter in order to support a fully functional API @@ -37526,7 +37545,7 @@ See: %feature("docstring") itk::simple::PatchBasedDenoising " - itk::simple::PatchBasedDenoisingImageFilter Procedural Interface +itk::simple::PatchBasedDenoisingImageFilter Procedural Interface This function directly calls the execute method of PatchBasedDenoisingImageFilter in order to support a procedural API @@ -37629,7 +37648,7 @@ See: %feature("docstring") itk::simple::RealAndImaginaryToComplex " - ComposeImageFilter combine several scalar images into a multicomponent image. +ComposeImageFilter combine several scalar images into a multicomponent image. This function directly calls the execute method of RealAndImaginaryToComplexImageFilter in order to support a procedural API @@ -37973,14 +37992,10 @@ The user can also select applications specifically for color images or environment variables. SITK_SHOW_COMMAND, SITK_SHOW_COLOR_COMMAND and SITK_SHOW_3D_COMMAND -allow the following tokens in their strings. - - - \"%a\" for the ImageJ application +allow the following tokens in their strings.\\\\li \\\\c \"%a\" for the ImageJ application \\\\li \\\\c \"%f\" +for SimpleITK's temporary image file - \"%f\" for SimpleITK's temporary image file - For example, the default SITK_SHOW_COMMAND string on Linux systems -is: +For example, the default SITK_SHOW_COMMAND string on Linux systems is: After token substitution it may become: @@ -38037,7 +38052,7 @@ See: %feature("docstring") itk::simple::SignedDanielssonDistanceMap " - itk::simple::SignedDanielssonDistanceMapImageFilter Procedural Interface +itk::simple::SignedDanielssonDistanceMapImageFilter Procedural Interface This function directly calls the execute method of SignedDanielssonDistanceMapImageFilter in order to support a procedural API @@ -38143,7 +38158,7 @@ generated. %feature("docstring") itk::simple::Slice " - itk::simple::SliceImageFilter Procedural Interface +itk::simple::SliceImageFilter Procedural Interface This function directly calls the execute method of SliceImageFilter in order to support a procedural API @@ -38497,7 +38512,7 @@ See: %feature("docstring") itk::simple::VectorConfidenceConnected " - itk::simple::VectorConfidenceConnectedImageFilter Functional Interface +itk::simple::VectorConfidenceConnectedImageFilter Functional Interface This function directly calls the execute method of VectorConfidenceConnectedImageFilter in order to support a fully functional API @@ -38610,7 +38625,7 @@ See: %feature("docstring") itk::simple::WhiteTopHat " - itk::simple::WhiteTopHatImageFilter Functional Interface +itk::simple::WhiteTopHatImageFilter Functional Interface This function directly calls the execute method of WhiteTopHatImageFilter in order to support a fully functional API @@ -38618,7 +38633,7 @@ This function directly calls the execute method of WhiteTopHatImageFilter in ord %feature("docstring") itk::simple::WhiteTopHat " - itk::simple::WhiteTopHatImageFilter Functional Interface +itk::simple::WhiteTopHatImageFilter Functional Interface This function directly calls the execute method of WhiteTopHatImageFilter in order to support a fully functional API From 43e5b600cb8fec8cef4180a3805906692b9e7a78 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 4 Aug 2015 09:35:47 -0400 Subject: [PATCH 060/412] Update SWIG to 3.0.7 Change-Id: I19a8e159c890a930aba1fad2b60789903a13ba1e --- SuperBuild/External_Swig.cmake | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SuperBuild/External_Swig.cmake b/SuperBuild/External_Swig.cmake index 9fb0b3f01..d52968b81 100644 --- a/SuperBuild/External_Swig.cmake +++ b/SuperBuild/External_Swig.cmake @@ -12,9 +12,9 @@ endif() if(NOT SWIG_DIR) - set(SWIG_TARGET_VERSION 3.0.5) - set(SWIG_DOWNLOAD_SOURCE_HASH "dcb9638324461b9baba8e044fe59031d") - set(SWIG_DOWNLOAD_WIN_HASH "fd2e050f29e2a00b2348f5f7d3476490") + set(SWIG_TARGET_VERSION 3.0.7) + set(SWIG_DOWNLOAD_SOURCE_HASH "7fff46c84b8c630ede5b0f0827e3d90a") + set(SWIG_DOWNLOAD_WIN_HASH "d8b5a9ce49c819cc1bfc1e797b85ba7a") if(WIN32) From 358bb14941693ab34eb0f31ba789a2392861622e Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 4 Aug 2015 09:55:03 -0400 Subject: [PATCH 061/412] Address warnings with signed integer comparison Change-Id: I18e02c71531c600bee04b69c5c8786dc77ee8f2d --- Code/BasicFilters/json/LabelIntensityStatisticsImageFilter.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/BasicFilters/json/LabelIntensityStatisticsImageFilter.json b/Code/BasicFilters/json/LabelIntensityStatisticsImageFilter.json index 67376e4c4..9dcf6a998 100644 --- a/Code/BasicFilters/json/LabelIntensityStatisticsImageFilter.json +++ b/Code/BasicFilters/json/LabelIntensityStatisticsImageFilter.json @@ -55,7 +55,7 @@ { "name" : "NumberOfBins", "type" : "uint32_t", - "default" : "128", + "default" : "128u", "briefdescriptionSet" : "", "detaileddescriptionSet" : "Set/Get the number of bins in the histogram. Note that the histogram is used to compute the median value, and that this option may have an effect on the value of the median.", "briefdescriptionGet" : "", From 50b85c2d4d96c824c47089069b164f34ea77f416 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 6 Aug 2015 09:42:39 -0400 Subject: [PATCH 062/412] Updating ITK v4.8 along release branch 192495a BUG: Removed an unguarded print statement. 6c3baad BUG: Initialize mutex for 32 bit AtomicInt. b13509d DOC: Expanded TreeContainer Example e29bf9a BUG: LBFGSB was printing messages even with debug switched off. d38900a COMP: Changing the order of HDF5 library components 11c73b6 BUG: Implement UpdateLargestPossibleRegion for ImageToVTKImageFilter. 5f6353e BUG: Missing ITKIOMINC_EXPORT on __Private() Change-Id: I901c6249d17ca14d05a477c6275b344621930048 --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 74537db30..899d7dac8 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY git://itk.org/ITK.git) # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG v4.8.0) +set(ITK_TAG_COMMAND GIT_TAG 059fd61a4629034d65ab9d7e0a44f928481f0f12 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 97b3d175d1ab74ae8f5dc88dcb055e555c9464a1 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 14 Aug 2015 09:47:19 -0400 Subject: [PATCH 063/412] Do not pass unneeded language arguments on the command line Only pass language CMake variable to the SimpleITK sub-superbuild project when the language is enabled. Change-Id: I65154c132b6cf0ea28a44a1e48dfd2180dd65bfc --- CMake/sitkLanguageOptions.cmake | 161 +++++++++++++++++++------------- 1 file changed, 95 insertions(+), 66 deletions(-) diff --git a/CMake/sitkLanguageOptions.cmake b/CMake/sitkLanguageOptions.cmake index 42f95e1d7..c45071a6e 100644 --- a/CMake/sitkLanguageOptions.cmake +++ b/CMake/sitkLanguageOptions.cmake @@ -36,12 +36,14 @@ mark_as_advanced( LUA_ADDITIONAL_LIBRARIES ) option ( WRAP_LUA "Wrap Lua" ${WRAP_LUA_DEFAULT} ) -list( APPEND SITK_LANGUAGES_VARS - LUA_LIBRARIES - LUA_INCLUDE_DIR - LUA_VERSION_STRING - LUA_ADDITIONAL_LIBRARIES - ) +if ( WRAP_LUA ) + list( APPEND SITK_LANGUAGES_VARS + LUA_LIBRARIES + LUA_INCLUDE_DIR + LUA_VERSION_STRING + LUA_ADDITIONAL_LIBRARIES + ) +endif() @@ -66,21 +68,26 @@ if ( PYTHONLIBS_FOUND AND PYTHONINTERP_FOUND else() set( WRAP_PYTHON_DEFAULT OFF ) endif() -list( APPEND SITK_LANGUAGES_VARS - PYTHON_DEBUG_LIBRARY - PYTHON_EXECUTABLE - PYTHON_LIBRARY - PYTHON_INCLUDE_DIR -# PYTHON_INCLUDE_PATH ( deprecated ) - ) -# Debian "jessie" has this additional variable required to match -# python versions. -if(PYTHON_INCLUDE_DIR2) + +option( WRAP_PYTHON "Wrap Python" ${WRAP_PYTHON_DEFAULT} ) + +if ( WRAP_PYTHON ) list( APPEND SITK_LANGUAGES_VARS - PYTHON_INCLUDE_DIR2 + PYTHON_DEBUG_LIBRARY + PYTHON_EXECUTABLE + PYTHON_LIBRARY + PYTHON_INCLUDE_DIR + # PYTHON_INCLUDE_PATH ( deprecated ) ) -endif() -option( WRAP_PYTHON "Wrap Python" ${WRAP_PYTHON_DEFAULT} ) +# Debian "jessie" has this additional variable required to match +# python versions. + if(PYTHON_INCLUDE_DIR2) + list( APPEND SITK_LANGUAGES_VARS + PYTHON_INCLUDE_DIR2 + ) + endif() +endif () + if (DEFINED WRAP_JAVA AND WRAP_JAVA) set(_QUIET "REQUIRED") @@ -95,29 +102,32 @@ if ( ${JAVA_FOUND} AND ${JNI_FOUND} ) else ( ${JAVA_FOUND} AND ${JNI_FOUND} ) set( WRAP_JAVA_DEFAULT OFF ) endif ( ${JAVA_FOUND} AND ${JNI_FOUND} ) -list( APPEND SITK_LANGUAGES_VARS - Java_JAVA_EXECUTABLE - Java_JAVAC_EXECUTABLE - Java_JAR_EXECUTABLE - Java_VERSION_STRING - Java_VERSION_MAJOR - Java_VERSION_MINOR - Java_VERSION_PATCH - Java_VERSION_TWEAK - Java_VERSION - Java_INCLUDE_DIRS - Java_LIBRARIES - JNI_INCLUDE_DIRS - JNI_LIBRARIES - JAVA_AWT_LIBRARY - JAVA_JVM_LIBRARY - JAVA_INCLUDE_PATH - JAVA_INCLUDE_PATH2 - JAVA_AWT_INCLUDE_PATH - - ) + option ( WRAP_JAVA "Wrap Java" ${WRAP_JAVA_DEFAULT} ) +if ( WRAP_JAVA ) + list( APPEND SITK_LANGUAGES_VARS + Java_JAVA_EXECUTABLE + Java_JAVAC_EXECUTABLE + Java_JAR_EXECUTABLE + Java_VERSION_STRING + Java_VERSION_MAJOR + Java_VERSION_MINOR + Java_VERSION_PATCH + Java_VERSION_TWEAK + Java_VERSION + Java_INCLUDE_DIRS + Java_LIBRARIES + JNI_INCLUDE_DIRS + JNI_LIBRARIES + JAVA_AWT_LIBRARY + JAVA_JVM_LIBRARY + JAVA_INCLUDE_PATH + JAVA_INCLUDE_PATH2 + JAVA_AWT_INCLUDE_PATH + ) +endif() + if (DEFINED WRAP_TCL AND WRAP_TCL) set(_QUIET "REQUIRED") @@ -131,30 +141,41 @@ if ( ${TCL_FOUND} ) else ( ${TCL_FOUND} ) set ( WRAP_TCL_DEFAULT OFF ) endif ( ${TCL_FOUND} ) -list( APPEND SITK_LANGUAGES_VARS - TCL_LIBRARY - TCL_INCLUDE_PATH - TCL_TCLSH - TK_LIBRARY - TK_INCLUDE_PATH - TK_WISH ) + option ( WRAP_TCL "Wrap Tcl" ${WRAP_TCL_DEFAULT} ) +if ( WRAP_TCL ) + list( APPEND SITK_LANGUAGES_VARS + TCL_LIBRARY + TCL_INCLUDE_PATH + TCL_TCLSH + TK_LIBRARY + TK_INCLUDE_PATH + TK_WISH + ) +endif() + + find_package ( Ruby QUIET ) if ( ${RUBY_FOUND} ) set ( WRAP_RUBY_DEFAULT ON ) else ( ${RUBY_FOUND} ) set ( WRAP_RUBY_DEFAULT OFF ) endif ( ${RUBY_FOUND} ) -list( APPEND SITK_LANGUAGES_VARS - RUBY_EXECUTABLE - RUBY_INCLUDE_DIRS - RUBY_LIBRARY - RUBY_VERSION - RUBY_FOUND - RUBY_INCLUDE_PATH ) + option ( WRAP_RUBY "Wrap Ruby" ${WRAP_RUBY_DEFAULT} ) +if ( WRAP_RUBY ) + list( APPEND SITK_LANGUAGES_VARS + RUBY_EXECUTABLE + RUBY_INCLUDE_DIRS + RUBY_LIBRARY + RUBY_VERSION + RUBY_FOUND + RUBY_INCLUDE_PATH + ) +endif() + if (DEFINED WRAP_CSHARP AND WRAP_CSHARP) set(_QUIET "REQUIRED") @@ -168,13 +189,18 @@ if ( ${CSHARP_FOUND} AND NOT MINGW ) else () set ( WRAP_CSHARP_DEFAULT OFF ) endif () -list( APPEND SITK_LANGUAGES_VARS - CSHARP_COMPILER - CSHARP_INTERPRETER - CSHARP_PLATFORM -) + option ( WRAP_CSHARP "Wrap C#" ${WRAP_CSHARP_DEFAULT} ) +if ( WRAP_CSHARP ) + list( APPEND SITK_LANGUAGES_VARS + CSHARP_COMPILER + CSHARP_INTERPRETER + CSHARP_PLATFORM + ) +endif() + + if (DEFINED WRAP_R AND WRAP_R) set(_QUIET "REQUIRED") else() @@ -188,15 +214,18 @@ else( ) set ( WRAP_R_DEFAULT OFF ) endif( ) - -list( APPEND SITK_LANGUAGES_VARS - R_INCLUDE_DIR - R_LIBRARIES - R_LIBRARY_BASE - R_COMMAND - RSCRIPT_EXECUTABLE ) option ( WRAP_R "Wrap R" ${WRAP_R_DEFAULT} ) +if ( WRAP_R ) + list( APPEND SITK_LANGUAGES_VARS + R_INCLUDE_DIR + R_LIBRARIES + R_LIBRARY_BASE + R_COMMAND + RSCRIPT_EXECUTABLE ) +endif() + + if( WIN32 ) mark_as_advanced( WRAP_R ) endif() From 775e97809f4e92a76db39294f0b1eb0de349ac43 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Sat, 29 Aug 2015 01:33:34 +0800 Subject: [PATCH 064/412] add CastImageFilter to support output writing Covert the real output image back to the original pixel type , to make writing easier, as many file formats don 't support real pixels. Contributed-by: yajun Change-Id: I0cb901897fd64b10ddf7b5c7927154c153a4473f --- Examples/SimpleGaussian.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Examples/SimpleGaussian.cs b/Examples/SimpleGaussian.cs index be7db1b0a..664fc753d 100644 --- a/Examples/SimpleGaussian.cs +++ b/Examples/SimpleGaussian.cs @@ -34,12 +34,19 @@ static void Main(string[] args) { // Execute Gaussian smoothing filter SmoothingRecursiveGaussianImageFilter gaussian = new SmoothingRecursiveGaussianImageFilter(); gaussian.SetSigma(Double.Parse(args[1])); - image = gaussian.Execute(image); + Image blurredImage = gaussian.Execute(image); + + // Covert the real output image back to the original pixel type , to + // make writing easier , as many file formats don 't support real + // pixels . + CastImageFilter castFilter = new CastImageFilter(); + castFilter.SetOutputPixelType(image.GetPixelIDValue()); + Image destImage = castFilter.Execute(blurredImage); // Write output image ImageFileWriter writer = new ImageFileWriter(); writer.SetFileName(args[2]); - writer.Execute(image); + writer.Execute(destImage); } catch (Exception ex) { Console.WriteLine(ex); From a5a40687ce683bffa27d1788ab9dc3fbcfdd6580 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Thu, 27 Aug 2015 09:55:01 -0400 Subject: [PATCH 065/412] Rewrite Show to support Fiji Now the Show function will first search for Fiji. If it finds Fiji, the image will be written out as MetaIO (.mha) and Fiji launched. If not, the function will search for ImageJ (v1). For ImageJ 1, the image is written out as Nifti (.nii). Note that Fiji is ImageJ plus a collection of plugins. ImageJ with no I/O plugins does not support MetaIO or Nifti. ImageJ v1 did come with a Nifti plugin. ImageJ v2 has no plugins, while Fiji comes with MetaIO support. Change-Id: I53022464d5a1bb994af8de6ad88a4c862fe6651a --- Code/IO/src/sitkShow.cxx | 194 ++++++++++++++++++++++++--------------- 1 file changed, 121 insertions(+), 73 deletions(-) diff --git a/Code/IO/src/sitkShow.cxx b/Code/IO/src/sitkShow.cxx index f456b3918..c5426b330 100644 --- a/Code/IO/src/sitkShow.cxx +++ b/Code/IO/src/sitkShow.cxx @@ -44,26 +44,35 @@ namespace itk // time to wait in milli-seconds before we check if the process is OK const unsigned int ProcessDelay = 500; +#define IMAGEJ_OPEN_MACRO "\'open(\"%f\"); rename(\"%t\"); \'" +#define NIFTI_COLOR_MACRO "\'run(\"Make Composite\", \"display=Composite\");\'" + #if defined(_WIN32) - static std::string ShowImageCommand = "%a -o %f -eval \"rename(\'%t\'); \""; - static std::string ShowColorImageCommand = "%a -eval " - "\"open(\'%f\'); run(\'Make Composite\', \'display=Composite\'); rename(\'%t\'); \""; + const static char * ShowImageCommand = "%a -eval " IMAGEJ_OPEN_MACRO; + const static char * ShowColorImageCommand = "%a -eval " IMAGEJ_OPEN_MACRO " -eval " NIFTI_COLOR_MACRO; #elif defined(__APPLE__) // The "-n" flag tells OSX to launch a new instance of ImageJ, even if one is already running. // We do this because otherwise the macro command line argument is not correctly passed to // a previously running instance of ImageJ. - static std::string ShowImageCommand = "open -a %a -n --args -eval " - "\'open(\"%f\"); rename(\"%t\"); \'"; - static std::string ShowColorImageCommand = "open -a %a -n --args -eval " - "\'open(\"%f\"); run(\"Make Composite\", \"display=Composite\"); rename(\"%t\"); \'"; + const static char * ShowImageCommand = "open -a %a -n --args -eval " IMAGEJ_OPEN_MACRO; + const static char * ShowColorImageCommand = "open -a %a -n --args -eval " IMAGEJ_OPEN_MACRO " -eval " NIFTI_COLOR_MACRO; #else // linux and other systems - static std::string ShowImageCommand = "%a -e \'open(\"%f\"); rename(\"%t\"); \'"; - static std::string ShowColorImageCommand = "%a -e " - "\'open(\"%f\"); run(\"Make Composite\", \"display=Composite\"); rename(\"%t\"); \'"; + const static char * ShowImageCommand = "%a -e " IMAGEJ_OPEN_MACRO; + + const static char * ShowColorImageCommand = "%a -e " IMAGEJ_OPEN_MACRO " -e " NIFTI_COLOR_MACRO; +#endif + + + // For Fiji, we only need 2 commands, not 6. We don't need a separate command for color images. + // Also the linux version uses the "-eval" flag instead of "-e". +#if defined(__APPLE__) + const static char * FijiShowCommand = "open -a %a -n --args -eval " IMAGEJ_OPEN_MACRO; +#else + const static char * FijiShowCommand = "%a -eval " IMAGEJ_OPEN_MACRO; #endif @@ -246,10 +255,19 @@ namespace itk } // - static std::string FormatFileName ( std::string TempDirectory, std::string name ) + static std::string FormatFileName ( std::string TempDirectory, std::string name, const bool metaioDefault=false ) { std::string TempFile = TempDirectory; - std::string Extension = ".nii"; + std::string Extension; + + if (metaioDefault) + { + Extension = ".mha"; + } + else + { + Extension = ".nii"; + } itksys::SystemTools::GetEnv ( "SITK_SHOW_EXTENSION", Extension ); @@ -310,7 +328,7 @@ namespace itk // // - static std::string BuildFullFileName(const std::string name) + static std::string BuildFullFileName(const std::string name, const bool metaioDefault=false) { std::string TempDirectory; @@ -327,13 +345,13 @@ namespace itk #else TempDirectory = "/tmp/"; #endif - return FormatFileName ( TempDirectory, name ); + return FormatFileName ( TempDirectory, name, metaioDefault ); } // // - static std::string FindApplication(const std::string name) + static std::string FindApplication(const std::string directory = "", const std::string name = "" ) { std::vector paths; @@ -344,17 +362,17 @@ namespace itk std::string ProgramFiles; if ( itksys::SystemTools::GetEnv ( "PROGRAMFILES", ProgramFiles ) ) { - paths.push_back ( ProgramFiles + "\\ImageJ\\" ); + paths.push_back ( ProgramFiles + "\\" + directory + "\\"); } if ( itksys::SystemTools::GetEnv ( "PROGRAMFILES(x86)", ProgramFiles ) ) { - paths.push_back ( ProgramFiles + "\\ImageJ\\" ); + paths.push_back ( ProgramFiles + "\\" + directory + "\\"); } if ( itksys::SystemTools::GetEnv ( "PROGRAMW6432", ProgramFiles ) ) { - paths.push_back ( ProgramFiles + "\\ImageJ\\" ); + paths.push_back ( ProgramFiles + "\\" + directory + "\\"); } @@ -364,18 +382,24 @@ namespace itk #elif defined(__APPLE__) // Common places on the Mac to look - paths.push_back("/Applications"); - paths.push_back("/Applications/ImageJ"); - paths.push_back("/Developer"); - paths.push_back("/opt/ImageJ"); - paths.push_back("/usr/local/ImageJ"); + paths.push_back( "/Applications" ); + paths.push_back( "/Applications/" + directory ); + paths.push_back( "/Developer" ); + paths.push_back( "/opt/" + directory ); + paths.push_back( "/usr/local/" + directory ); +#ifndef NDEBUG + std::cout << paths << std::endl; ExecutableName = itksys::SystemTools::FindDirectory( name.c_str(), paths ); + std::cout << "Result: " << ExecutableName << std::endl; +#endif #else // linux and other systems - ExecutableName = itksys::SystemTools::FindFile ( name.c_str() ); + paths.push_back( "/opt/" + directory ); + paths.push_back( "/usr/local/" + directory ); + ExecutableName = itksys::SystemTools::FindFile ( name.c_str(), paths ); #endif @@ -486,12 +510,6 @@ namespace itk std::vector CommandLine; - TempFile = BuildFullFileName(title); - //std::cout << "Full file name:\t" << TempFile << std::endl; - - // write out the image - WriteImage ( image, TempFile ); - bool colorFlag = false; @@ -503,7 +521,63 @@ namespace itk - // check for user-defined environment variables + + // Find the ImageJ executable + // + +#if defined(_WIN32) + + // Windows + ExecutableName = FindApplication("Fiji.app", "ImageJ-win64.exe"); + if (!ExecutableName.length()) + { + ExecutableName = FindApplication("Fiji.app", "ImageJ-win32.exe"); + } + if (!ExecutableName.length()) + { + ExecutableName = FindApplication("ImageJ", "ImageJ.exe"); + } + +#elif defined(__APPLE__) + + ExecutableName = FindApplication("", "Fiji.app"); + if (!ExecutableName.length()) + { + ExecutableName = FindApplication( "ImageJ", "ImageJ64.app" ); + } + if (!ExecutableName.length()) + { + ExecutableName = FindApplication( "ImageJ", "ImageJ.app" ); + } + +#else + + // Linux and other systems + ExecutableName = FindApplication("Fiji.app", "ImageJ-linux64"); + if (!ExecutableName.length()) + { + ExecutableName = FindApplication("Fiji.app", "ImageJ-linux32"); + } + if (!ExecutableName.length()) + { + ExecutableName = FindApplication("ImageJ", "imagej"); + } + if (!ExecutableName.length()) + { + ExecutableName = FindApplication("imagej"); + } +#endif + + bool fijiFlag = ExecutableName.find("Fiji.app") != std::string::npos; + + TempFile = BuildFullFileName(title, fijiFlag); + //std::cout << "Full file name:\t" << TempFile << std::endl; + + // write out the image + WriteImage ( image, TempFile ); + + + // check for user-defined environment variables for the command string // if (colorFlag) { @@ -514,7 +588,14 @@ namespace itk } if (!Command.length()) { - Command = ShowColorImageCommand; + if (fijiFlag) + { + Command = FijiShowCommand; + } + else + { + Command = ShowColorImageCommand; + } } } else @@ -522,7 +603,14 @@ namespace itk itksys::SystemTools::GetEnv ( "SITK_SHOW_COMMAND", Command ); if (!Command.length()) { - Command = ShowImageCommand; + if (fijiFlag) + { + Command = FijiShowCommand; + } + else + { + Command = ShowImageCommand; + } } } itksys::SystemTools::GetEnv ( "SITK_SHOW_3D_COMMAND", Command3D ); @@ -537,46 +625,6 @@ namespace itk } - // Find the ImageJ executable - // - -#if defined(_WIN32) - - // Windows - ExecutableName = FindApplication("ImageJ.exe"); - -#elif defined(__APPLE__) - -# if defined(__x86_64__) - - // Mac 64-bit - ExecutableName = FindApplication( "ImageJ64.app" ); - if (!ExecutableName.length()) - { - ExecutableName = "ImageJ64.app"; - } - -# else - - // Mac 32-bit - ExecutableName = FindApplication( "ImageJ.app" ); - if (!ExecutableName.length()) - { - ExecutableName = "ImageJ.app"; - } -# endif // __x86_64__ - -#else - - // Linux and other systems - ExecutableName = FindApplication("ImageJ"); - if (!ExecutableName.length()) - { - ExecutableName = FindApplication("imagej"); - } -#endif - - // Replace the string tokens and split the command string into seperate words. CommandLine = ConvertCommand(Command, ExecutableName, TempFile, title); From 5a795e4ebc8b306a41363c7ee182bc82f27ad820 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 10 Sep 2015 16:00:27 -0400 Subject: [PATCH 066/412] Do not force CMAKE_INSTALL_PREFIX if already set. Allow the user to override CMAKE_INSTALL_PREFIX on the initial configuration while still setting the correct initial default. Change-Id: I8c56acfb8aec4e55e0a2a62ae7ce115b7c6f74e7 --- SuperBuild/CMakeLists.txt | 14 ++++++++++++++ SuperBuild/SuperBuild.cmake | 4 ---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/SuperBuild/CMakeLists.txt b/SuperBuild/CMakeLists.txt index 566b63d7c..4b7045ead 100644 --- a/SuperBuild/CMakeLists.txt +++ b/SuperBuild/CMakeLists.txt @@ -1,3 +1,17 @@ + +#----------------------------------------------------------------------------- +# Override defaults set in initial "project" call, allow user to +# override from command line +#----------------------------------------------------------------------------- + + +# SimpleITK Addition: install to the common library +# directory, so that all libs/include etc ends up +# in one common tree +if( NOT DEFINED CMAKE_INSTALL_PREFIX ) + set(CMAKE_INSTALL_PREFIX ${CMAKE_CURRENT_BINARY_DIR} CACHE PATH "Where all the prerequisite libraries go") +endif() + cmake_minimum_required ( VERSION 2.8.4 ) project ( SuperBuildSimpleITK ) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index cf76ef807..b359c9d52 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -62,10 +62,6 @@ include(VariableList) # Prerequisites #------------------------------------------------------------------------------ # -# SimpleITK Addition: install to the common library -# directory, so that all libs/include etc ends up -# in one common tree -set(CMAKE_INSTALL_PREFIX ${CMAKE_CURRENT_BINARY_DIR} CACHE PATH "Where all the prerequisite libraries go" FORCE) # Compute -G arg for configuring external projects with the same CMake generator: if(CMAKE_EXTRA_GENERATOR) From 7bc697b591c52fc5fcf0e6d55edf4bc252be6ea1 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 10 Sep 2015 16:00:38 -0400 Subject: [PATCH 067/412] Don't pass SITK_REQUIRED_ITK_MODULES in Superbuild Change-Id: I26e003d9945fd1b5e22d1c3d1bc2ef6b50ab4f28 --- sitkCheckForITKModuleDependencies.cmake | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sitkCheckForITKModuleDependencies.cmake b/sitkCheckForITKModuleDependencies.cmake index 439e06ca7..784531732 100644 --- a/sitkCheckForITKModuleDependencies.cmake +++ b/sitkCheckForITKModuleDependencies.cmake @@ -14,7 +14,7 @@ # is dependent on most of the IO modules so we only need to force 'review on' to # ensure that we have the 'IO on' too. # -list(APPEND SITK_REQUIRED_ITK_MODULES +list(APPEND _SITK_REQUIRED_ITK_MODULES ITKAnisotropicSmoothing ITKAntiAlias ITKBiasCorrection @@ -58,9 +58,9 @@ list(APPEND SITK_REQUIRED_ITK_MODULES ITKWatersheds ) -foreach(itkDependency ${SITK_REQUIRED_ITK_MODULES}) +foreach(itkDependency ${_SITK_REQUIRED_ITK_MODULES}) list(FIND ITK_MODULES_ENABLED ${itkDependency} ITKDependency_FOUND) if(ITKDependency_FOUND EQUAL -1) message(FATAL_ERROR "SimpleITK requires that the ${itkDependency} module be turned on in ITK") endif() -endforeach(itkDependency) +endforeach() From 865cfa46f3a6d453fc9fca202877c9aa95243d69 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 10 Sep 2015 16:21:37 -0400 Subject: [PATCH 068/412] Move CMake file to CMake directory Change-Id: I7d69ae605ffd899ff3432d463bd6e9095180bdbf --- .../sitkCheckForITKModuleDependencies.cmake | 0 CMakeLists.txt | 2 +- SuperBuild/SuperBuild.cmake | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) rename sitkCheckForITKModuleDependencies.cmake => CMake/sitkCheckForITKModuleDependencies.cmake (100%) diff --git a/sitkCheckForITKModuleDependencies.cmake b/CMake/sitkCheckForITKModuleDependencies.cmake similarity index 100% rename from sitkCheckForITKModuleDependencies.cmake rename to CMake/sitkCheckForITKModuleDependencies.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index 4bf48b630..543a4fc8a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -51,7 +51,7 @@ include(sitkCheckRequiredFlags) find_package(ITK REQUIRED ) #we require certain packages be turned on in ITK -include("sitkCheckForITKModuleDependencies.cmake") +include(sitkCheckForITKModuleDependencies) if(ITK_FOUND) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index b359c9d52..4c793f325 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -304,7 +304,7 @@ mark_as_advanced(USE_SYSTEM_ITK) if(USE_SYSTEM_ITK) find_package(ITK REQUIRED) #we require certain packages be turned on in ITK - include("${CMAKE_CURRENT_SOURCE_DIR}/../sitkCheckForITKModuleDependencies.cmake") + include(sitkCheckForITKModuleDependencies) else() include(External_ITK) list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES ITK) From 6697be6157c0d8394cec8cbf83f0788098424843 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 21 Sep 2015 14:42:13 -0400 Subject: [PATCH 069/412] Adding wrapping for FFT PadImageFilter This already includes tests and documentation for ITK doxygen. Change-Id: I442c4a42500a1dd1df81b6df7360d21c2dd9c778 --- Code/BasicFilters/json/FFTPadImageFilter.json | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Code/BasicFilters/json/FFTPadImageFilter.json diff --git a/Code/BasicFilters/json/FFTPadImageFilter.json b/Code/BasicFilters/json/FFTPadImageFilter.json new file mode 100644 index 000000000..e911fafa8 --- /dev/null +++ b/Code/BasicFilters/json/FFTPadImageFilter.json @@ -0,0 +1,69 @@ +{ + "name" : "FFTPadImageFilter", + "template_code_filename" : "ImageFilter", + "template_test_filename" : "ImageFilter", + "number_of_inputs" : 1, + "pixel_types" : "BasicPixelIDTypeList", + "include_files" : [ + "sitkBoundaryConditions.hxx" + ], + "members" : [ + { + "name" : "BoundaryCondition", + "enum" : [ + "ZERO_PAD", + "ZERO_FLUX_NEUMANN_PAD", + "PERIODIC_PAD" + ], + "default" : "itk::simple::FFTPadImageFilter::ZERO_FLUX_NEUMANN_PAD", + "custom_itk_cast" : "std::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" + }, + { + "name" : "SizeGreatestPrimeFactor", + "type" : "int", + "default" : "5", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set/Get the greatest prime factor allowed on the size of the padded image. The filter increase the size of the image to reach a size with the greatest prime factor smaller or equal to the specified value. The default value is 13, which is the greatest prime number for which the FFT are precomputed in FFTW, and thus gives very good performance. A greatest prime factor of 2 produce a size which is a power of 2, and thus is suitable for vnl base fft filters. A greatest prime factor of 1 or less - typically 0 - disable the extra padding.", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Set/Get the greatest prime factor allowed on the size of the padded image. The filter increase the size of the image to reach a size with the greatest prime factor smaller or equal to the specified value. The default value is 13, which is the greatest prime number for which the FFT are precomputed in FFTW, and thus gives very good performance. A greatest prime factor of 2 produce a size which is a power of 2, and thus is suitable for vnl base fft filters. A greatest prime factor of 1 or less - typically 0 - disable the extra padding." + } + ], + "tests" : [ + { + "tag" : "defaults", + "description" : "Test with default parameters", + "md5hash" : "7a033cbc1d72c7806a7be37c0a60932b", + "settings" : [], + "inputs" : [ + "Input/BrainProtonDensitySlice.png" + ] + }, + { + "tag" : "more", + "description" : "Test ConstantPad reasonable padding", + "md5hash" : "5c4bebbdfb8a340cdb5347dac3d87046", + "settings" : [ + { + "parameter" : "BoundaryCondition", + "value" : "itk::simple::${name}::PERIODIC_PAD", + "lua_value" : "SimpleITK.${name}_PERIODIC_PAD", + "python_value" : "SimpleITK.${name}.PERIODIC_PAD", + "ruby_value" : "Simpleitk::${name}::PERIODIC_PAD", + "java_value" : "${name}.ConnectivityType.PERIODIC_PAD", + "tcl_value" : "$$${name}_PERIODIC_PAD", + "csharp_value" : "${name}.ConnectivityType.PERIODIC_PAD", + "R_value" : "'PERIODIC_PAD'" + }, + { + "parameter" : "SizeGreatestPrimeFactor", + "value" : "2" + } + ], + "inputs" : [ + "Input/BrainProtonDensitySlice.png" + ] + } + ], + "briefdescription" : "Pad an image to make it suitable for an FFT transformation.", + "detaileddescription" : "FFT filters usually requires a specific image size. The size is decomposed in several prime factors, and the filter only supports prime factors up to a maximum value. This filter automatically finds the greatest prime factor required by the available implementation and pads the input appropriately.\n\nThis code was adapted from the Insight Journal contribution:\n\n\"FFT Based Convolution\" by Gaetan Lehmann http://hdl.handle.net/10380/3154 \n\n\\author Gaetan Lehmann\n\n\\see FFTShiftImageFilter" +} From a4bd962b2e169906a66cee325151e0e17ebf63a8 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 21 Sep 2015 16:12:34 -0400 Subject: [PATCH 070/412] Fix CSharp and Java boundary condition enum for test Change-Id: I96e759fc22e0a4fc3d233ef3cbe0e1c023f24f5c --- Code/BasicFilters/json/FFTPadImageFilter.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/BasicFilters/json/FFTPadImageFilter.json b/Code/BasicFilters/json/FFTPadImageFilter.json index e911fafa8..0d8ad9755 100644 --- a/Code/BasicFilters/json/FFTPadImageFilter.json +++ b/Code/BasicFilters/json/FFTPadImageFilter.json @@ -40,7 +40,7 @@ }, { "tag" : "more", - "description" : "Test ConstantPad reasonable padding", + "description" : "Test Periodic Pad", "md5hash" : "5c4bebbdfb8a340cdb5347dac3d87046", "settings" : [ { @@ -49,9 +49,9 @@ "lua_value" : "SimpleITK.${name}_PERIODIC_PAD", "python_value" : "SimpleITK.${name}.PERIODIC_PAD", "ruby_value" : "Simpleitk::${name}::PERIODIC_PAD", - "java_value" : "${name}.ConnectivityType.PERIODIC_PAD", + "java_value" : "${name}.BoundaryCondition.PERIODIC_PAD", "tcl_value" : "$$${name}_PERIODIC_PAD", - "csharp_value" : "${name}.ConnectivityType.PERIODIC_PAD", + "csharp_value" : "${name}.BoundaryCondition.PERIODIC_PAD", "R_value" : "'PERIODIC_PAD'" }, { From c98be58be959b2448c3ac0fb78b76b875c0a76fb Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 22 Sep 2015 10:38:24 -0400 Subject: [PATCH 071/412] Correcting Java and CSharp enum types Change-Id: I55049e35ba620a5e09c0dccea19d3a2d82a3a5ee --- Code/BasicFilters/json/FFTPadImageFilter.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/BasicFilters/json/FFTPadImageFilter.json b/Code/BasicFilters/json/FFTPadImageFilter.json index 0d8ad9755..9cd899d33 100644 --- a/Code/BasicFilters/json/FFTPadImageFilter.json +++ b/Code/BasicFilters/json/FFTPadImageFilter.json @@ -49,9 +49,9 @@ "lua_value" : "SimpleITK.${name}_PERIODIC_PAD", "python_value" : "SimpleITK.${name}.PERIODIC_PAD", "ruby_value" : "Simpleitk::${name}::PERIODIC_PAD", - "java_value" : "${name}.BoundaryCondition.PERIODIC_PAD", + "java_value" : "${name}.BoundaryConditionType.PERIODIC_PAD", "tcl_value" : "$$${name}_PERIODIC_PAD", - "csharp_value" : "${name}.BoundaryCondition.PERIODIC_PAD", + "csharp_value" : "${name}.BoundaryConditionType.PERIODIC_PAD", "R_value" : "'PERIODIC_PAD'" }, { From 1ac48721816a1ac8dd69d970412c1c40d10ec4b6 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 1 Jun 2015 15:50:49 -0400 Subject: [PATCH 072/412] WIP: Adding local transform fixes Change-Id: I9477057ab88a4282667e7dea8a5988015ecf65a0 --- Code/Common/include/sitkBSplineTransform.h | 2 +- .../include/sitkDisplacementFieldTransform.h | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/Code/Common/include/sitkBSplineTransform.h b/Code/Common/include/sitkBSplineTransform.h index 52c03e38c..0920f2c57 100644 --- a/Code/Common/include/sitkBSplineTransform.h +++ b/Code/Common/include/sitkBSplineTransform.h @@ -38,7 +38,7 @@ class SITKCommon_EXPORT BSplineTransform typedef BSplineTransform Self; typedef Transform Superclass; - BSplineTransform(unsigned int dimensions, unsigned int order=3); + explicit BSplineTransform(unsigned int dimensions, unsigned int order=3); BSplineTransform( const BSplineTransform & ); diff --git a/Code/Common/include/sitkDisplacementFieldTransform.h b/Code/Common/include/sitkDisplacementFieldTransform.h index bd95b1c00..253373c4a 100644 --- a/Code/Common/include/sitkDisplacementFieldTransform.h +++ b/Code/Common/include/sitkDisplacementFieldTransform.h @@ -39,12 +39,22 @@ class SITKCommon_EXPORT DisplacementFieldTransform typedef DisplacementFieldTransform Self; typedef Transform Superclass; - DisplacementFieldTransform( unsigned int dimensions ); - DisplacementFieldTransform( Image &); + explicit DisplacementFieldTransform( unsigned int dimensions ); + + /** \brief Consume an image to construct a displacement field transform. + * + * \warning The input displacement image is transferred to the + * constructed transform object. The input image is modified to be a + * default constructed Image object. + * + * Image must be of sitkVectorFloat64 pixel type with the number of + * components equal to the image dimension. + * + */ + explicit DisplacementFieldTransform( Image &); DisplacementFieldTransform( const DisplacementFieldTransform & ); - explicit DisplacementFieldTransform( const Transform & ); DisplacementFieldTransform &operator=( const DisplacementFieldTransform & ); @@ -55,7 +65,7 @@ class SITKCommon_EXPORT DisplacementFieldTransform /** parameters */ // set displacement methods take ownership for the image and remove it Self &SetDisplacementField(Image &); - /** \todo The returned image is should not directly modify the + /** \todo The returned image should not directly modify the * internal displacement field. */ Image GetDisplacementField() const; From 92fee75035998592555a230ff91cf4e076db78fc Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 12 Jun 2015 15:03:06 -0400 Subject: [PATCH 073/412] Adding ObjectCount measurement to ConnectedComponents filter Change-Id: I1f7d2deda7ac72e886080ed170e9376f4910a837 --- .../json/ConnectedComponentImageFilter.json | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Code/BasicFilters/json/ConnectedComponentImageFilter.json b/Code/BasicFilters/json/ConnectedComponentImageFilter.json index 9b5d948d0..4f461b839 100644 --- a/Code/BasicFilters/json/ConnectedComponentImageFilter.json +++ b/Code/BasicFilters/json/ConnectedComponentImageFilter.json @@ -18,12 +18,27 @@ "detaileddescriptionGet" : "Set/Get whether the connected components are defined strictly by face connectivity or by face+edge+vertex connectivity. Default is FullyConnectedOff. For objects that are 1 pixel wide, use FullyConnectedOn." } ], + "measurements" : [ + { + "name" : "ObjectCount", + "type" : "uint32_t", + "default" : "0u", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "After the filter is executed, holds the number of connected components." + } + ], "custom_methods" : [], "tests" : [ { "tag" : "default", "description" : "2D", "settings" : [], + "measurements_results" : [ + { + "name" : "ObjectCount", + "value" : 23 + } + ], "md5hash" : "548f5184428db10d93e3bf377dee5253", "inputs" : [ "Input/WhiteDots.png" From 8754ca52e74a34cfb1f84825de3f36b7f2fc0b2a Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 15 Jun 2015 11:46:26 -0400 Subject: [PATCH 074/412] Add unsigned int specifier Change-Id: I76361b454240147ff5523983d74f32c297b20508 --- Code/BasicFilters/json/ConnectedComponentImageFilter.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/BasicFilters/json/ConnectedComponentImageFilter.json b/Code/BasicFilters/json/ConnectedComponentImageFilter.json index 4f461b839..0d761512c 100644 --- a/Code/BasicFilters/json/ConnectedComponentImageFilter.json +++ b/Code/BasicFilters/json/ConnectedComponentImageFilter.json @@ -36,7 +36,7 @@ "measurements_results" : [ { "name" : "ObjectCount", - "value" : 23 + "value" : "23u" } ], "md5hash" : "548f5184428db10d93e3bf377dee5253", From 792c30662226111ec75b9f8196ff2d1e6038ceea Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Tue, 28 Jul 2015 15:19:55 -0400 Subject: [PATCH 075/412] Fix leading space problem in doxy2swig.py The script doxy2swig.py has a method space_parse that outputs a space. We don't want this to happen at the beginning of a new line, so check that the previous character was not a newline. Change-Id: I45d67eaad0c3870b03d6456f89d1ffa4c70a74fd --- Utilities/Doxygen/doxy2swig.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Utilities/Doxygen/doxy2swig.py b/Utilities/Doxygen/doxy2swig.py index f37e49186..83a7ba4a7 100755 --- a/Utilities/Doxygen/doxy2swig.py +++ b/Utilities/Doxygen/doxy2swig.py @@ -24,8 +24,9 @@ # This version of the script originated from ITK/Wrapping/Generators/Doc/doxy2swig.py. # My mods: -# self.multi is always 1 (0 was cutting lines improperly) -# added self.java to enable output for JavaDocs +# self.multi is always 1 (0 was cutting lines improperly). +# added self.java to enable output for JavaDocs. +# space_parse doesn't output a space at the beginning of a new line. # # Dave Chen @@ -181,7 +182,11 @@ def generic_parse(self, node, pad=0): self.add_text('\n') def space_parse(self, node): - self.add_text(' ') + """ Only output a space if the last character outputed was not a new line. + I.e., don't allow a line to lead with a space. + """ + if len(self.pieces) and self.pieces[-1][-1] != '\n': + self.add_text(' ') self.generic_parse(node) do_ref = space_parse From 0399fb67ac71053478df1b131e07a93c9e6ad993 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Wed, 29 Jul 2015 16:43:43 -0400 Subject: [PATCH 076/412] Updated space_parse with a noLeadingSpace flag There is now a flag that tells the space_parse method to enable or disable the omit a leading space option. Be default the flag is true, i.e. leading spaces are omitted. In the case of a "See" node, the flag is set to False before the nodes children are traversed. Afterwards, the flag is set back to True. The effect is that children of the See node do get a leading space, indenting them 1 space. Change-Id: I1d0a92c2231705d8d1e40a4b67acb9eff6b9737d --- Utilities/Doxygen/doxy2swig.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/Utilities/Doxygen/doxy2swig.py b/Utilities/Doxygen/doxy2swig.py index 83a7ba4a7..6ec25866f 100755 --- a/Utilities/Doxygen/doxy2swig.py +++ b/Utilities/Doxygen/doxy2swig.py @@ -24,9 +24,8 @@ # This version of the script originated from ITK/Wrapping/Generators/Doc/doxy2swig.py. # My mods: -# self.multi is always 1 (0 was cutting lines improperly). -# added self.java to enable output for JavaDocs. -# space_parse doesn't output a space at the beginning of a new line. +# self.multi is always 1 (0 was cutting lines improperly) +# added self.java to enable output for JavaDocs # # Dave Chen @@ -89,6 +88,13 @@ def __init__(self, src, javaFlag=0): 'basecompoundref') #self.generics = [] + """ flag to enable/disable printing a space in the space_parse method. + if True, space_parse will not print a space if it is at the start + of a new line. True by default. Only disabled for a node + with kind=="see". + """ + self.noLeadingSpace = True + def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. @@ -185,10 +191,14 @@ def space_parse(self, node): """ Only output a space if the last character outputed was not a new line. I.e., don't allow a line to lead with a space. """ - if len(self.pieces) and self.pieces[-1][-1] != '\n': - self.add_text(' ') + if self.noLeadingSpace: + if len(self.pieces) and self.pieces[-1][-1] != '\n': + self.add_text(' ') + else: + self.add_text(' ') self.generic_parse(node) + # The handlers for all these node types get mapped to a space do_ref = space_parse do_ulink = space_parse do_emphasis = space_parse @@ -326,7 +336,9 @@ def do_simplesect(self, node): elif kind == 'see': self.add_text('\n') self.add_text('See:') + self.noLeadingSpace = False self.generic_parse(node) + self.noLeadingSpace = True else: self.generic_parse(node) From 5b1c3b5509d6ab435e505651b8cf6f8354e661b2 Mon Sep 17 00:00:00 2001 From: Dave Chen Date: Thu, 30 Jul 2015 15:58:12 -0400 Subject: [PATCH 077/412] Regenerated the .i files JavaDoc.i and PythonDocstrings.i were regenerated with the new version of doxy2swig.py that eliminates the leading space problem. These leading spaces were causing problems with swig. --- Wrapping/JavaDoc.i | 364 +++++++++++++++++++----------------- Wrapping/PythonDocstrings.i | 353 +++++++++++++++++----------------- 2 files changed, 374 insertions(+), 343 deletions(-) diff --git a/Wrapping/JavaDoc.i b/Wrapping/JavaDoc.i index d5bbb5727..dd8f6e137 100644 --- a/Wrapping/JavaDoc.i +++ b/Wrapping/JavaDoc.i @@ -10,7 +10,7 @@ C++ includes: itkBitwiseNotFunctor.h %typemap(javaimports) itk::Functor::DivFloor "/** - Cast arguments to double, performs division then takes the floor. +Cast arguments to double, performs division then takes the floor. C++ includes: itkDivideFloorFunctor.h */" @@ -149,7 +149,7 @@ public "; %javamethodmodifiers itk::SliceImageFilter::GenerateOutputInformation "/** virtual void itk::SliceImageFilter< TInputImage, TOutputImage >::GenerateOutputInformation() - SliceImageFilter produces an image which is a different resolution and with a +SliceImageFilter produces an image which is a different resolution and with a different pixel spacing than its input image. See: ProcessObject::GenerateOutputInformaton() @@ -1157,7 +1157,7 @@ iterative relaxation process of an estimated ND surface. The surface is described implicitly as the zero level set of a volume $ \\\\phi $ and allowed to deform under curvature flow. A set of contraints is imposed on this movement as follows: - \\\\[ u_{i,j,k}^{n+1} = \\\\left\\\\{ \\\\begin{array}{ll} +\\\\[ u_{i,j,k}^{n+1} = \\\\left\\\\{ \\\\begin{array}{ll} \\\\mbox{max} (u_{i,j,k}^{n} + \\\\Delta t H_{i,j,k}^{n}, 0) & \\\\mbox{\\\\f$B_{i,j,k} = 1\\\\f$} \\\\\\\\ \\\\mbox{min} (u_{i,j,k}^{n} + \\\\Delta t H_{i,j,k}^{n}, 0) & @@ -1800,7 +1800,7 @@ public "; %typemap(javaimports) itk::simple::BSplineTransformInitializerFilter "/** - BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such +BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such that it has a physically consistent definition. It sets the transform domain origin, physical dimensions and direction from information obtained from the image. It also sets the mesh size if asked to do so @@ -2356,7 +2356,7 @@ public "; Labels the pixels on the border of the objects in a binary image. - BinaryContourImageFilter takes a binary image as input, where the pixels in the objects are +BinaryContourImageFilter takes a binary image as input, where the pixels in the objects are the pixels with a value equal to ForegroundValue. Only the pixels on the contours of the objects are kept. The pixels not on the border are changed to BackgroundValue. @@ -2364,7 +2364,7 @@ changed to BackgroundValue. The connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours. - http://hdl.handle.net/1926/1352 +http://hdl.handle.net/1926/1352 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -2516,7 +2516,7 @@ public "; Fast binary dilation. - BinaryDilateImageFilter is a binary dilation morphologic operation. This implementation is +BinaryDilateImageFilter is a binary dilation morphologic operation. This implementation is based on the papers: L.Vincent \"Morphological transformations of binary images with @@ -2698,7 +2698,7 @@ public "; Fast binary erosion. - BinaryErodeImageFilter is a binary erosion morphologic operation. This implementation is +BinaryErodeImageFilter is a binary erosion morphologic operation. This implementation is based on the papers: L.Vincent \"Morphological transformations of binary images with @@ -2881,7 +2881,7 @@ public "; Remove holes not connected to the boundary of the image. - BinaryFillholeImageFilter fills holes in a binary image. +BinaryFillholeImageFilter fills holes in a binary image. Geodesic morphology and the Fillhole algorithm is described in Chapter 6 of Pierre Soille's book \"Morphological Image Analysis: Principles @@ -3012,7 +3012,7 @@ public "; Remove the objects not connected to the boundary of the image. - BinaryGrindPeakImageFilter ginds peaks in a grayscale image. +BinaryGrindPeakImageFilter ginds peaks in a grayscale image. Geodesic morphology and the grind peak algorithm is described in Chapter 6 of Pierre Soille's book \"Morphological Image Analysis: @@ -3161,7 +3161,7 @@ Label the connected components in a binary image and produce a collection of label objects. - BinaryImageToLabelMapFilter labels the objects in a binary image. Each distinct object is +BinaryImageToLabelMapFilter labels the objects in a binary image. Each distinct object is assigned a unique label. The final object labels start with 1 and are consecutive. Objects that are reached earlier by a raster order scan have a lower label. @@ -3547,13 +3547,13 @@ public "; Denoise a binary image using min/max curvature flow. - BinaryMinMaxCurvatureFlowImageFilter implements a curvature driven image denosing algorithm. This filter +BinaryMinMaxCurvatureFlowImageFilter implements a curvature driven image denosing algorithm. This filter assumes that the image is essentially binary: consisting of two classes. Iso-brightness contours in the input image are viewed as a level set. The level set is then evolved using a curvature-based speed function: - \\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] +\\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] where $ F_{\\\\mbox{minmax}} = \\\\min(\\\\kappa,0) $ if $ \\\\mbox{Avg}_{\\\\mbox{stencil}}(x) $ is less than or equal to $ T_{thresold} $ and $ \\\\max(\\\\kappa,0) $ , otherwise. $ \\\\kappa $ is the mean curvature of the iso-brightness contour at point $ x $ . @@ -5269,7 +5269,7 @@ This class is parameterized over the type of the input image and the type of the output image. It is also parameterized by the operation to be applied, using a Functor style. - UnaryFunctorImageFilter allows the output dimension of the filter to be larger than the input +UnaryFunctorImageFilter allows the output dimension of the filter to be larger than the input dimension. Thus subclasses of the UnaryFunctorImageFilter (like the CastImageFilter ) can be used to promote a 2D image to a 3D image, etc. @@ -5966,7 +5966,7 @@ public "; %typemap(javaimports) itk::simple::CenteredTransformInitializerFilter "/** - CenteredTransformInitializerFilter is a helper class intended to initialize the center of rotation and +CenteredTransformInitializerFilter is a helper class intended to initialize the center of rotation and the translation of Transforms having the center of rotation among their parameters. @@ -5993,12 +5993,7 @@ passes as the initial translation to the transform. This second approach assumes that the moments of the anatomical objects are similar for both images and hence the best initial guess for registration is to superimpose both mass centers. Note that this -assumption will probably not hold in multi-modality registration. - - -See: - itk::CenteredTransformInitializer - +assumption will probably not hold in multi-modality registration. \\\\sa itk::CenteredTransformInitializer C++ includes: sitkCenteredTransformInitializerFilter.h */" @@ -6086,7 +6081,7 @@ public "; %typemap(javaimports) itk::simple::CenteredVersorTransformInitializerFilter "/** - CenteredVersorTransformInitializerFilter is a helper class intended to initialize the center of rotation, +CenteredVersorTransformInitializerFilter is a helper class intended to initialize the center of rotation, versor, and translation of the VersorRigid3DTransform. @@ -6370,7 +6365,7 @@ public "; Combines two images in a checkerboard pattern. - CheckerBoardImageFilter takes two input images that must have the same dimension, size, +CheckerBoardImageFilter takes two input images that must have the same dimension, size, origin and spacing and produces an output image of the same size by combinining the pixels from the two input images in a checkerboard pattern. This filter is commonly used for visually comparing two @@ -7287,10 +7282,10 @@ public "; %typemap(javaimports) itk::simple::ComposeImageFilter "/** - ComposeImageFilter combine several scalar images into a multicomponent image. +ComposeImageFilter combine several scalar images into a multicomponent image. - ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . +ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . Inputs and Usage All input images are expected to have the same template parameters @@ -7624,7 +7619,7 @@ public "; Label the objects in a binary image. - ConnectedComponentImageFilter labels the objects in a binary image (non-zero pixels are considered +ConnectedComponentImageFilter labels the objects in a binary image (non-zero pixels are considered to be objects, zero-valued pixels are considered to be background). Each distinct object is assigned a unique label. The filter experiments with some improvements to the existing implementation, and @@ -7710,6 +7705,18 @@ Name of this class */ public "; +%javamethodmodifiers itk::simple::ConnectedComponentImageFilter::GetObjectCount "/** +uint32_t itk::simple::ConnectedComponentImageFilter::GetObjectCount() const + +After the filter is executed, holds the number of connected +components. + +This is a measurement. Its value is updated in the Execute methods, so +the value will only be valid after an execution. + +*/ +public "; + %javamethodmodifiers itk::simple::ConnectedComponentImageFilter::SetFullyConnected "/** Self& itk::simple::ConnectedComponentImageFilter::SetFullyConnected(bool FullyConnected) @@ -7744,7 +7751,7 @@ Label pixels that are connected to a seed and lie within a range of values. - ConnectedThresholdImageFilter labels pixels with ReplaceValue that are connected to an initial Seed +ConnectedThresholdImageFilter labels pixels with ReplaceValue that are connected to an initial Seed AND lie within a Lower and Upper threshold range. See: itk::simple::ConnectedThreshold for the procedural interface @@ -7919,7 +7926,7 @@ public "; Increase the image size by padding with a constant value. - ConstantPadImageFilter changes the output image region. If the output image region is larger +ConstantPadImageFilter changes the output image region. If the output image region is larger than the input image region, the extra pixels are filled in by a constant value. The output image region must be specified. @@ -8253,7 +8260,7 @@ public "; Decrease the image size by cropping the image by an itk::Size at both the upper and lower bounds of the largest possible region. - CropImageFilter changes the image boundary of an image by removing pixels outside the +CropImageFilter changes the image boundary of an image by removing pixels outside the target region. The target region is not specified in advance, but calculated in BeforeThreadedGenerateData() . @@ -8501,12 +8508,12 @@ public "; Denoise an image using curvature driven flow. - CurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- +CurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- brightness contours in the grayscale input image are viewed as a level set. The level set is then evolved using a curvature-based speed function: - \\\\[ I_t = \\\\kappa |\\\\nabla I| \\\\] where $ \\\\kappa $ is the curvature. +\\\\[ I_t = \\\\kappa |\\\\nabla I| \\\\] where $ \\\\kappa $ is the curvature. The advantage of this approach is that sharp boundaries are preserved with smoothing occurring only within a region. However, it should be @@ -8933,7 +8940,7 @@ public "; Deformably register two images using the demons algorithm. - DemonsRegistrationFilter implements the demons deformable algorithm that register two images +DemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the displacement field which will map a moving image onto a fixed image. @@ -9502,7 +9509,7 @@ See T. Vercauteren, X. Pennec, A. Perchant and N. Ayache, \"Non- parametric Diffeomorphic Image Registration with the Demons Algorithm\", Proc. of MICCAI 2007. - DiffeomorphicDemonsRegistrationFilter implements the demons deformable algorithm that register two images +DiffeomorphicDemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the deformation field which will map a moving image onto a fixed image. @@ -10724,6 +10731,18 @@ public "; %javamethodmodifiers itk::simple::DisplacementFieldTransform::DisplacementFieldTransform "/** itk::simple::DisplacementFieldTransform::DisplacementFieldTransform(Image &) + +Consume an image to construct a displacement field transform. + + + +WARNING: +The input displacement image is transferred to the constructed +transform object. The input image is modified to be a default +constructed Image object. +Image must be of sitkVectorFloat64 pixel type with the number of components +equal to the image dimension. + */ public "; @@ -10741,7 +10760,7 @@ public "; Image itk::simple::DisplacementFieldTransform::GetDisplacementField() const Todo -The returned image is should not directly modify the internal +The returned image should not directly modify the internal displacement field. @@ -11989,7 +12008,7 @@ public "; Expand the size of an image by an integer factor in each dimension. - ExpandImageFilter increases the size of an image by an integer factor in each dimension +ExpandImageFilter increases the size of an image by an integer factor in each dimension using a interpolation method. The output image size in each dimension is given by: @@ -12140,10 +12159,10 @@ Decrease the image size by cropping the image to the selected region bounds. - ExtractImageFilter changes the image boundary of an image by removing pixels outside the +ExtractImageFilter changes the image boundary of an image by removing pixels outside the target region. The target region must be specified. - ExtractImageFilter also collapses dimensions so that the input image may have more +ExtractImageFilter also collapses dimensions so that the input image may have more dimensions than the output image (i.e. 4-D input image to a 3-D output image). To specify what dimensions to collapse, the ExtractionRegion must be specified. For any dimension dim where @@ -12195,7 +12214,8 @@ Crop an image by specifying the region to keep See: itk::simple::Extract for the procedural interface - itk::ExtractImageFilter for the Doxygen on the original ITK class. + itk::ExtractImageFilter. The image is flipped across axes for which array[i] is true. @@ -14071,7 +14091,7 @@ public "; Generate an n-dimensional image of a Gabor filter. - GaborImageSource generates an image of either the real (i.e. symmetric) or complex +GaborImageSource generates an image of either the real (i.e. symmetric) or complex (i.e. antisymmetric) part of the Gabor filter with the orientation directed along the x-axis. The GaborKernelFunction is used to evaluate the contribution along the x-axis whereas a non- normalized 1-D Gaussian envelope provides the contribution in each of @@ -14243,7 +14263,7 @@ public "; Generate an n-dimensional image of a Gaussian. - GaussianImageSource generates an image of a Gaussian. m_Normalized determines whether or +GaussianImageSource generates an image of a Gaussian. m_Normalized determines whether or not the Gaussian is normalized (whether or not the sum over infinite space is 1.0) When creating an image, it is preferable tonotnormalize the Gaussian m_Scale scales the output of the Gaussian to span a range @@ -14556,7 +14576,7 @@ edge potential map. General characteristics of an edge potential map is that it has values close to zero in regions near the edges and values close to one inside the shape itself. Typically, the edge potential map is compute from the image gradient, for example: - \\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] +\\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] where $ I $ is image intensity and $ (\\\\nabla * G) $ is the derivative of Gaussian operator. @@ -15949,7 +15969,7 @@ public "; Remove local minima not connected to the boundary of the image. - GrayscaleFillholeImageFilter fills holes in a grayscale image. Holes are local minima in the +GrayscaleFillholeImageFilter fills holes in a grayscale image. Holes are local minima in the grayscale topography that are not connected to boundaries of the image. Gray level values adjacent to a hole are extrapolated across the hole. @@ -16397,7 +16417,7 @@ public "; Remove local maxima not connected to the boundary of the image. - GrayscaleGrindPeakImageFilter removes peaks in a grayscale image. Peaks are local maxima in the +GrayscaleGrindPeakImageFilter removes peaks in a grayscale image. Peaks are local maxima in the grayscale topography that are not connected to boundaries of the image. Gray level values adjacent to a peak are extrapolated through the peak. @@ -17114,7 +17134,7 @@ public "; Generate an n-dimensional image of a grid. - GridImageSource generates an image of a grid. From the abstract... \"Certain classes +GridImageSource generates an image of a grid. From the abstract... \"Certain classes of images find disparate use amongst members of the ITK community for such purposes as visualization, simulation, testing, etc. Currently there exists two derived classes from the ImageSource class used for @@ -17298,7 +17318,7 @@ Identify local minima whose depth below the baseline is greater than h. - HConcaveImageFilter extract local minima that are more than h intensity units below the +HConcaveImageFilter extract local minima that are more than h intensity units below the (local) background. This has the effect of extracting objects that are darker than the background by at least h intensity units. @@ -17436,7 +17456,7 @@ Identify local maxima whose height above the baseline is greater than h. - HConvexImageFilter extract local maxima that are more than h intensity units above the +HConvexImageFilter extract local maxima that are more than h intensity units above the (local) background. This has the effect of extracting objects that are brighter than background by at least h intensity units. @@ -17573,7 +17593,7 @@ public "; Suppress local maxima whose height above the baseline is less than h. - HMaximaImageFilter suppresses local maxima that are less than h intensity units above +HMaximaImageFilter suppresses local maxima that are less than h intensity units above the (local) background. This has the effect of smoothing over the \"high\" parts of the noise in the image without smoothing over large changes in intensity (region boundaries). See the HMinimaImageFilter to suppress the local minima whose depth is less than h intensity @@ -17684,7 +17704,7 @@ public "; Suppress local minima whose depth below the baseline is less than h. - HMinimaImageFilter suppresses local minima that are less than h intensity units below +HMinimaImageFilter suppresses local minima that are less than h intensity units below the (local) background. This has the effect of smoothing over the \"low\" parts of the noise in the image without smoothing over large changes in intensity (region boundaries). See the HMaximaImageFilter to suppress the local maxima whose height is less than h intensity @@ -17988,7 +18008,7 @@ Computes the Hausdorff distance between the set of non-zero pixels of two images. - HausdorffDistanceImageFilter computes the distance between the set non-zero pixels of two images +HausdorffDistanceImageFilter computes the distance between the set non-zero pixels of two images using the following formula: \\\\[ H(A,B) = \\\\max(h(A,B),h(B,A)) \\\\] where \\\\[ h(A,B) = \\\\max_{a \\\\in A} \\\\min_{b \\\\in B} \\\\| a - b\\\\| \\\\] is the directed Hausdorff distance and $A$ and $B$ are respectively the set of non-zero pixels in the first and second input images. @@ -18092,7 +18112,7 @@ Normalize the grayscale values between two images by histogram matching. - HistogramMatchingImageFilter normalizes the grayscale values of a source image based on the +HistogramMatchingImageFilter normalizes the grayscale values of a source image based on the grayscale values of a reference image. This filter uses a histogram matching technique where the histograms of the two images are matched only at a specified number of quantile values. @@ -18106,7 +18126,7 @@ grayscale values are smaller than the mean grayscale value. ThresholdAtMeanInten The source image can be set via either SetInput() or SetSourceImage() . The reference image can be set via SetReferenceImage() . - SetNumberOfHistogramLevels() sets the number of bins used when creating histograms of the source +SetNumberOfHistogramLevels() sets the number of bins used when creating histograms of the source and reference images. SetNumberOfMatchPoints() governs the number of quantile values to be matched. This filter assumes that both the source and reference are of the same @@ -18579,7 +18599,7 @@ public "; %javamethodmodifiers itk::simple::Image::TransformContinuousIndexToPhysicalPoint "/** std::vector< double > itk::simple::Image::TransformContinuousIndexToPhysicalPoint(const std::vector< double > &index) const - Transform continuous index to physical point +Transform continuous index to physical point */ public "; @@ -18587,7 +18607,7 @@ public "; %javamethodmodifiers itk::simple::Image::TransformIndexToPhysicalPoint "/** std::vector< double > itk::simple::Image::TransformIndexToPhysicalPoint(const std::vector< int64_t > &index) const - Transform index to physical point +Transform index to physical point */ public "; @@ -18595,7 +18615,7 @@ public "; %javamethodmodifiers itk::simple::Image::TransformPhysicalPointToContinuousIndex "/** std::vector< double > itk::simple::Image::TransformPhysicalPointToContinuousIndex(const std::vector< double > &point) const - Transform physical point to continuous index +Transform physical point to continuous index */ public "; @@ -18603,7 +18623,7 @@ public "; %javamethodmodifiers itk::simple::Image::TransformPhysicalPointToIndex "/** std::vector< int64_t > itk::simple::Image::TransformPhysicalPointToIndex(const std::vector< double > &point) const - Transform physical point to index +Transform physical point to index */ public "; @@ -18942,6 +18962,7 @@ Self& itk::simple::ImageRegistrationMethod::SetMetricAsDemons(double intensityDi Use demons image metric. + See: itk::DemonsImageToImageMetricv4 @@ -19145,9 +19166,8 @@ public "; %javamethodmodifiers itk::simple::ImageRegistrationMethod::SetOptimizerAsLBFGSB "/** Self& itk::simple::ImageRegistrationMethod::SetOptimizerAsLBFGSB(double gradientConvergenceTolerance=1e-5, unsigned int -maximumNumberOfIterations=500, unsigned int -maximumNumberOfCorrections=5, unsigned int -maximumNumberOfFunctionEvaluations=2000, double +numberOfIterations=500, unsigned int maximumNumberOfCorrections=5, +unsigned int maximumNumberOfFunctionEvaluations=2000, double costFunctionConvergenceFactor=1e+7, double lowerBound=std::numeric_limits< double >::min(), double upperBound=std::numeric_limits< double >::max(), bool trace=false) @@ -19524,7 +19544,7 @@ are mapped to a constant. Values over the interval are mapped to another constant. - IntensityWindowingImageFilter applies pixel-wise a linear transformation to the intensity values of +IntensityWindowingImageFilter applies pixel-wise a linear transformation to the intensity values of input image pixels. The linear transformation is defined by the user in terms of the minimum and maximum values that the output image should have and the lower and upper limits of the intensity window of @@ -19539,7 +19559,7 @@ Wiki Examples: All Examples - IntensityWindowingImageFilter +IntensityWindowingImageFilter See: RescaleIntensityImageFilter @@ -20020,7 +20040,7 @@ public "; Computes the inverse of a displacement field. - InverseDisplacementFieldImageFilter takes a displacement field as input and computes the displacement +InverseDisplacementFieldImageFilter takes a displacement field as input and computes the displacement field that is its inverse. If the input displacement field was mapping coordinates from a space A into a space B, the output of this filter will map coordinates from the space B into the space A. @@ -20409,7 +20429,7 @@ public "; Invert the intensity of an image. - InvertIntensityImageFilter inverts intensity of pixels by subtracting pixel value to a maximum +InvertIntensityImageFilter inverts intensity of pixels by subtracting pixel value to a maximum value. The maximum value can be set with SetMaximum and defaults the maximum of input pixel type. This filter can be used to invert, for example, a binary image, a distance map, etc. @@ -20807,7 +20827,7 @@ public "; Label pixels that are connected to one set of seeds but not another. - IsolatedConnectedImageFilter finds the optimal threshold to separate two regions. It has two +IsolatedConnectedImageFilter finds the optimal threshold to separate two regions. It has two modes, one to separate dark regions surrounded by bright regions by automatically finding a minimum isolating upper threshold, and another to separate bright regions surrounded by dark regions by automatically @@ -21061,7 +21081,7 @@ public "; Isolate watershed basins using two seeds. - IsolatedWatershedImageFilter labels pixels with ReplaceValue1 that are in the same watershed basin +IsolatedWatershedImageFilter labels pixels with ReplaceValue1 that are in the same watershed basin as Seed1 AND NOT the same as Seed2. The filter adjusts the waterlevel until the two seeds are not in different basins. The user supplies a Watershed threshold. The algorithm uses a binary search to adjust the @@ -21613,7 +21633,7 @@ public "; Labels the pixels on the border of the objects in a labeled image. - LabelContourImageFilter takes a labeled image as input, where the pixels in the objects are +LabelContourImageFilter takes a labeled image as input, where the pixels in the objects are the pixels with a value different of the BackgroundValue. Only the pixels on the contours of the objects are kept. The pixels not on the border are changed to BackgroundValue. The labels of the object are @@ -21622,7 +21642,7 @@ the same in the input and in the output image. The connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours. - http://hdl.handle.net/1926/1352 +http://hdl.handle.net/1926/1352 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -21755,7 +21775,7 @@ public "; convert a labeled image to a label collection image - LabelImageToLabelMapFilter converts a label image to a label collection image. The labels are +LabelImageToLabelMapFilter converts a label image to a label collection image. The labels are the same in the input and the output image. @@ -22051,7 +22071,7 @@ public "; Mask and image with a LabelMap . - LabelMapMaskImageFilter mask the content of an input image according to the content of the +LabelMapMaskImageFilter mask the content of an input image according to the content of the input LabelMap . The masked pixel of the input image are set to the BackgroundValue. LabelMapMaskImageFilter can keep the input image for one label only, with Negated = false (the default) or it can mask the input image for a single label, when Negated equals true. In Both cases, the label is set with SetLabel() . @@ -22350,7 +22370,7 @@ public "; Convert a LabelMap to a binary image. - LabelMapToBinaryImageFilter to a binary image. All the objects in the image are used as +LabelMapToBinaryImageFilter to a binary image. All the objects in the image are used as foreground. The background values of the original binary image can be restored by passing this image to the filter with the SetBackgroundImage() method. @@ -22463,7 +22483,7 @@ public "; Converts a LabelMap to a labeled image. - LabelMapToBinaryImageFilter to a label image. +LabelMapToBinaryImageFilter to a label image. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -22859,7 +22879,7 @@ valuates the shape attribute at once. This implementation was taken from the Insight Journal paper: - http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -23213,7 +23233,7 @@ Given an intensity image and a label map, compute min, max, variance and mean of the pixels associated with each label or segment. - LabelStatisticsImageFilter computes the minimum, maximum, sum, mean, median, variance and sigma +LabelStatisticsImageFilter computes the minimum, maximum, sum, mean, median, variance and sigma of regions of an intensity image, where the regions are defined via a label map (a second input). The label image should be integral type. The filter needs all of its input image. It behaves as a filter with @@ -23558,7 +23578,7 @@ public "; Make sure that the objects are not overlapping. - AttributeUniqueLabelMapFilter search the overlapping zones in the overlapping objects and keeps +AttributeUniqueLabelMapFilter search the overlapping zones in the overlapping objects and keeps only a single object on all the pixels of the image. The object to keep is selected according to their label. @@ -25972,14 +25992,14 @@ calculated and the one that gives the largest number of pixels is chosen. Since these both default to 0, if a user only sets one, the other is ignored. - Image size: fixedImage and movingImage need not be the same size, but +Image size: fixedImage and movingImage need not be the same size, but fixedMask must be the same size as fixedImage, and movingMask must be the same size as movingImage. Furthermore, whereas some algorithms require that the \"template\" be smaller than the \"image\" because of errors in the regions where the two are not fully overlapping, this filter has no such restriction. - Image spacing: Since the computations are done in the pixel domain, all +Image spacing: Since the computations are done in the pixel domain, all input images must have the same spacing. Outputs; The output is an image of RealPixelType that is the masked @@ -26896,7 +26916,7 @@ Merges several Label Maps. This filter takes one or more input Label Map and merges them. - SetMethod() can be used to change how the filter manage the labels from the +SetMethod() can be used to change how the filter manage the labels from the different label maps. KEEP (0): MergeLabelMapFilter do its best to keep the label unchanged, but if a label is already used in a previous label map, a new label is assigned. AGGREGATE (1): If the same label is found several times in the label maps, the label @@ -27048,12 +27068,12 @@ public "; Denoise an image using min/max curvature flow. - MinMaxCurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- +MinMaxCurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- brightness contours in the grayscale input image are viewed as a level set. The level set is then evolved using a curvature-based speed function: - \\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] +\\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] where $ F_{\\\\mbox{minmax}} = \\\\max(\\\\kappa,0) $ if $ \\\\mbox{Avg}_{\\\\mbox{stencil}}(x) $ is less than or equal to $ T_{thresold} $ and $ \\\\min(\\\\kappa,0) $ , otherwise. $ \\\\kappa $ is the mean curvature of the iso-brightness contour at point $ x $ . @@ -27455,7 +27475,7 @@ Increase the image size by padding with replicants of the input image value. - MirrorPadImageFilter changes the image bounds of an image. Any added pixels are filled in +MirrorPadImageFilter changes the image bounds of an image. Any added pixels are filled in with a mirrored replica of the input image. For instance, if the output image needs a pixel that istwo pixels to the left of the LargestPossibleRegionof the input image, the value assigned will be @@ -28839,7 +28859,7 @@ Label pixels that are connected to a seed and lie within a neighborhood. - NeighborhoodConnectedImageFilter labels pixels with ReplaceValue that are connected to an initial Seed +NeighborhoodConnectedImageFilter labels pixels with ReplaceValue that are connected to an initial Seed AND whose neighbors all lie within a Lower and Upper threshold range. See: itk::simple::NeighborhoodConnected for the procedural interface @@ -29156,7 +29176,7 @@ C++ includes: sitkNonCopyable.h Normalize an image by setting its mean to zero and variance to one. - NormalizeImageFilter shifts and scales an image so that the pixels in the image have a +NormalizeImageFilter shifts and scales an image so that the pixels in the image have a zero mean and unit variance. This filter uses StatisticsImageFilter to compute the mean and variance of the input and then applies ShiftScaleImageFilter to shift and scale the pixels. NB: since this filter normalizes the data to lie within -1 to 1, @@ -30291,7 +30311,7 @@ public "; Paste an image into another image. - PasteImageFilter allows you to take a section of one image and paste into another +PasteImageFilter allows you to take a section of one image and paste into another image. The SetDestinationIndex() method prescribes where in the first input to start pasting data from the second input. The SetSourceRegion method prescribes the section of the second image to paste into the first. If the output requested @@ -31964,10 +31984,10 @@ public "; %typemap(javaimports) itk::simple::RealAndImaginaryToComplexImageFilter "/** - ComposeImageFilter combine several scalar images into a multicomponent image. +ComposeImageFilter combine several scalar images into a multicomponent image. - ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . +ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . Inputs and Usage All input images are expected to have the same template parameters @@ -32398,10 +32418,10 @@ Base class for computing IIR convolution with an approximation of a Gaussian kernel. - \\\\[ \\\\frac{ 1 }{ \\\\sigma \\\\sqrt{ 2 \\\\pi } } \\\\exp{ +\\\\[ \\\\frac{ 1 }{ \\\\sigma \\\\sqrt{ 2 \\\\pi } } \\\\exp{ \\\\left( - \\\\frac{x^2}{ 2 \\\\sigma^2 } \\\\right) } \\\\] - RecursiveGaussianImageFilter is the base class for recursive filters that approximate convolution +RecursiveGaussianImageFilter is the base class for recursive filters that approximate convolution with the Gaussian kernel. This class implements the recursive filtering method proposed by R.Deriche in IEEE-PAMI Vol.12, No.1, January 1990, pp 78-87, \"Fast Algorithms for Low-Level Vision\" @@ -32540,7 +32560,7 @@ Let \\\\[ L(x; t) = g(x; t) \\\\ast f(x) \\\\] be the scale-space representation Then the normalized derivative operator for normalized coordinates across scale is: - \\\\[ \\\\partial_\\\\xi = \\\\sqrt{t} \\\\partial_x \\\\] +\\\\[ \\\\partial_\\\\xi = \\\\sqrt{t} \\\\partial_x \\\\] The resulting scaling factor is \\\\[ \\\\sigma^N \\\\] where N is the order of the derivative. @@ -32746,7 +32766,7 @@ Wiki Examples: All Examples - RegionalMaximaImageFilter +RegionalMaximaImageFilter See: itk::simple::RegionalMaxima for the procedural interface @@ -32924,7 +32944,7 @@ a minima or not. The SetFlatIsMinima() method let the user choose which behavior This class was contribtued to the Insight Journal by Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. http://hdl.handle.net/1926/153 - RegionalMaximaImageFilter MathematicalMorphologyImageFilters +RegionalMaximaImageFilter MathematicalMorphologyImageFilters See: @@ -32936,7 +32956,7 @@ Wiki Examples: All Examples - RegionalMinimaImageFilter +RegionalMinimaImageFilter See: itk::simple::RegionalMinima for the procedural interface @@ -33106,7 +33126,7 @@ Relabel the components in an image such that consecutive labels are used. - RelabelComponentImageFilter remaps the labels associated with the objects in an image (as from +RelabelComponentImageFilter remaps the labels associated with the objects in an image (as from the output of ConnectedComponentImageFilter ) such that the label numbers are consecutive with no gaps between the label numbers used. By default, the relabeling will also sort the labels based on the size of the object: the largest object will have @@ -33117,7 +33137,7 @@ can be disabled using SetSortByObjectSize. Label #0 is assumed to be the background and is left unaltered by the relabeling. - RelabelComponentImageFilter is typically used on the output of the ConnectedComponentImageFilter for those applications that want to extract the largest object or the +RelabelComponentImageFilter is typically used on the output of the ConnectedComponentImageFilter for those applications that want to extract the largest object or the \"k\" largest objects. Any particular object can be extracted from the relabeled output using a BinaryThresholdImageFilter . A group of objects can be extracted from the relabled output using a ThresholdImageFilter . @@ -33133,7 +33153,7 @@ will be only those remaining. The GetOriginalNumberOfObjects method can be called to find out how many objects were present before the small ones were discarded. - RelabelComponentImageFilter can be run as an \"in place\" filter, where it will overwrite its +RelabelComponentImageFilter can be run as an \"in place\" filter, where it will overwrite its output. The default is run out of place (or generate a separate output). \"In place\" operation can be controlled via methods in the superclass, InPlaceImageFilter::InPlaceOn() and @@ -33527,7 +33547,7 @@ public "; Resample an image via a coordinate transform. - ResampleImageFilter resamples an existing image through some coordinate transform, +ResampleImageFilter resamples an existing image through some coordinate transform, interpolating via some image function. The class is templated over the types of the input and output images. @@ -33790,7 +33810,7 @@ public "; Applies a linear transformation to the intensity levels of the input Image . - RescaleIntensityImageFilter applies pixel-wise a linear transformation to the intensity values of +RescaleIntensityImageFilter applies pixel-wise a linear transformation to the intensity values of input image pixels. The linear transformation is defined by the user in terms of the minimum and maximum values that the output image should have. @@ -33798,7 +33818,7 @@ should have. The following equation gives the mapping of the intensity values - \\\\[ outputPixel = ( inputPixel - inputMin) \\\\cdot +\\\\[ outputPixel = ( inputPixel - inputMin) \\\\cdot \\\\frac{(outputMax - outputMin )}{(inputMax - inputMin)} + outputMin \\\\] All computations are performed in the precison of the input pixel's @@ -35625,7 +35645,7 @@ edge potential map. General characteristics of an edge potential map is that it has values close to zero in regions near the edges and values close to one inside the shape itself. Typically, the edge potential map is compute from the image gradient, for example: - \\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] +\\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] where $ I $ is image intensity and $ (\\\\nabla * G) $ is the derivative of Gaussian operator. @@ -35822,7 +35842,7 @@ public "; Shift and scale the pixels in an image. - ShiftScaleImageFilter shifts the input pixel by Shift (default 0.0) and then scales the +ShiftScaleImageFilter shifts the input pixel by Shift (default 0.0) and then scales the pixel by Scale (default 1.0). All computattions are performed in the precison of the input pixel's RealType. Before assigning the computed value to the output pixel, the value is clamped at the NonpositiveMin @@ -36023,7 +36043,7 @@ public "; Reduce the size of an image by an integer factor in each dimension. - ShrinkImageFilter reduces the size of an image by an integer factor in each dimension. +ShrinkImageFilter reduces the size of an image by an integer factor in each dimension. The algorithm implemented is a simple subsample. The output image size in each dimension is given by: @@ -36140,7 +36160,7 @@ Computes the sigmoid function pixel-wise. A linear transformation is applied first on the argument of the sigmoid fuction. The resulting total transfrom is given by - \\\\[ f(x) = (Max-Min) \\\\cdot \\\\frac{1}{\\\\left(1+e^{- \\\\frac{ +\\\\[ f(x) = (Max-Min) \\\\cdot \\\\frac{1}{\\\\left(1+e^{- \\\\frac{ x - \\\\beta }{\\\\alpha}}\\\\right)} + Min \\\\] Every output pixel is equal to f(x). Where x is the intensity of the @@ -36852,7 +36872,7 @@ Measures the similarity between the set of non-zero pixels of two images. - SimilarityIndexImageFilter measures the similarity between the set non-zero pixels of two images +SimilarityIndexImageFilter measures the similarity between the set non-zero pixels of two images using the following formula: \\\\[ S = \\\\frac{2 | A \\\\cap B |}{|A| + |B|} \\\\] where $A$ and $B$ are respectively the set of non-zero pixels in the first and second input images. Operator $|\\\\cdot|$ represents the size of a set and $\\\\cap$ represents the intersection of two sets. @@ -37435,7 +37455,7 @@ Wiki Examples: All Examples - SobelEdgeDetectionImageFilter +SobelEdgeDetectionImageFilter See: itk::simple::SobelEdgeDetection for the procedural interface @@ -37907,7 +37927,7 @@ public "; Compute min. max, variance and mean of an Image . - StatisticsImageFilter computes the minimum, maximum, sum, mean, variance sigma of an image. +StatisticsImageFilter computes the minimum, maximum, sum, mean, variance sigma of an image. The filter needs all of its input image. It behaves as a filter with an input and output. Thus it can be inserted in a pipline with other filters and the statistics will only be recomputed if a downstream @@ -38246,7 +38266,7 @@ Switzerland. based on a variation of the DemonsRegistrationFilter . The basic mo along with the modification for avoiding large deformations when gradients have small values. - SymmetricForcesDemonsRegistrationFilter implements the demons deformable algorithm that register two images +SymmetricForcesDemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the deformation field which will map a moving image onto a fixed image. @@ -38862,7 +38882,7 @@ Set image values to a user-specified value if they are below, above, or between simple threshold values. - ThresholdImageFilter sets image values to a user-specified \"outside\" value (by default, +ThresholdImageFilter sets image values to a user-specified \"outside\" value (by default, \"black\") if the image values are below, above, or between simple threshold values. @@ -40409,7 +40429,7 @@ Wiki Examples: All Examples - ValuedRegionalMaximaImageFilter +ValuedRegionalMaximaImageFilter See: itk::simple::ValuedRegionalMaxima for the procedural interface @@ -40529,7 +40549,7 @@ Wiki Examples: All Examples - ValuedRegionalMinimaImageFilter +ValuedRegionalMinimaImageFilter See: itk::simple::ValuedRegionalMinima for the procedural interface @@ -41128,7 +41148,7 @@ public "; %typemap(javaimports) itk::simple::Version "/** - Version info for SimpleITK. +Version info for SimpleITK. C++ includes: sitkVersion.h */" @@ -41866,7 +41886,7 @@ public "; Warps an image using an input displacement field. - WarpImageFilter warps an existing image with respect to a given displacement field. +WarpImageFilter warps an existing image with respect to a given displacement field. A displacement field is represented as a image whose pixel type is some vector type with at least N elements, where N is the dimension of @@ -41881,7 +41901,7 @@ Each vector in the displacement field represent the distance between a geometric point in the input space and a point in the output space such that: - \\\\[ p_{in} = p_{out} + d \\\\] +\\\\[ p_{in} = p_{out} + d \\\\] Typically the mapped position does not correspond to an integer pixel position in the input image. Interpolation via an image function is @@ -42399,7 +42419,7 @@ Increase the image size by padding with replicants of the input image value. - WrapPadImageFilter changes the image bounds of an image. Added pixels are filled in with +WrapPadImageFilter changes the image bounds of an image. Added pixels are filled in with a wrapped replica of the input image. For instance, if the output image needs a pixel that istwo pixels to the left of the LargestPossibleRegionof the input image, the value assigned will be @@ -43657,7 +43677,7 @@ public "; Image itk::simple::BinaryClosingByReconstruction(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, double foregroundValue=1.0, bool fullyConnected=false) - itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface +itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryClosingByReconstructionImageFilter in order to support a fully functional API @@ -43669,7 +43689,7 @@ Image itk::simple::BinaryClosingByReconstruction(const Image &, const std::vecto kernel=sitkBall, double foregroundValue=1.0, bool fullyConnected=false) - itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface +itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryClosingByReconstructionImageFilter in order to support a fully functional API @@ -43698,7 +43718,7 @@ Image itk::simple::BinaryDilate(const Image &, uint32_t radius=1, KernelEnum ker backgroundValue=0.0, double foregroundValue=1.0, bool boundaryToForeground=false) - itk::simple::BinaryDilateImageFilter Functional Interface +itk::simple::BinaryDilateImageFilter Functional Interface This function directly calls the execute method of BinaryDilateImageFilter in order to support a fully functional API @@ -43710,7 +43730,7 @@ Image itk::simple::BinaryDilate(const Image &, const std::vector< uint32_t > vec kernel=sitkBall, double backgroundValue=0.0, double foregroundValue=1.0, bool boundaryToForeground=false) - itk::simple::BinaryDilateImageFilter Functional Interface +itk::simple::BinaryDilateImageFilter Functional Interface This function directly calls the execute method of BinaryDilateImageFilter in order to support a fully functional API @@ -43722,7 +43742,7 @@ Image itk::simple::BinaryErode(const Image &, uint32_t radius=1, KernelEnum kern backgroundValue=0.0, double foregroundValue=1.0, bool boundaryToForeground=true) - itk::simple::BinaryErodeImageFilter Functional Interface +itk::simple::BinaryErodeImageFilter Functional Interface This function directly calls the execute method of BinaryErodeImageFilter in order to support a fully functional API @@ -43734,7 +43754,7 @@ Image itk::simple::BinaryErode(const Image &, const std::vector< uint32_t > vect kernel=sitkBall, double backgroundValue=0.0, double foregroundValue=1.0, bool boundaryToForeground=true) - itk::simple::BinaryErodeImageFilter Functional Interface +itk::simple::BinaryErodeImageFilter Functional Interface This function directly calls the execute method of BinaryErodeImageFilter in order to support a fully functional API @@ -43849,7 +43869,7 @@ public "; Image itk::simple::BinaryMorphologicalClosing(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, double foregroundValue=1.0, bool safeBorder=true) - itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface +itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalClosingImageFilter in order to support a fully functional API @@ -43860,7 +43880,7 @@ public "; Image itk::simple::BinaryMorphologicalClosing(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, double foregroundValue=1.0, bool safeBorder=true) - itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface +itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalClosingImageFilter in order to support a fully functional API @@ -43871,7 +43891,7 @@ public "; Image itk::simple::BinaryMorphologicalOpening(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, double backgroundValue=0.0, double foregroundValue=1.0) - itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface +itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalOpeningImageFilter in order to support a fully functional API @@ -43883,7 +43903,7 @@ Image itk::simple::BinaryMorphologicalOpening(const Image &, const std::vector< kernel=sitkBall, double backgroundValue=0.0, double foregroundValue=1.0) - itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface +itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalOpeningImageFilter in order to support a fully functional API @@ -43913,7 +43933,7 @@ Image itk::simple::BinaryOpeningByReconstruction(const Image &, uint32_t radius= foregroundValue=1.0, double backgroundValue=0.0, bool fullyConnected=false) - itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface +itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryOpeningByReconstructionImageFilter in order to support a fully functional API @@ -43925,7 +43945,7 @@ Image itk::simple::BinaryOpeningByReconstruction(const Image &, const std::vecto kernel=sitkBall, double foregroundValue=1.0, double backgroundValue=0.0, bool fullyConnected=false) - itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface +itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryOpeningByReconstructionImageFilter in order to support a fully functional API @@ -44088,7 +44108,7 @@ public "; Image itk::simple::BlackTopHat(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::BlackTopHatImageFilter Functional Interface +itk::simple::BlackTopHatImageFilter Functional Interface This function directly calls the execute method of BlackTopHatImageFilter in order to support a fully functional API @@ -44099,7 +44119,7 @@ public "; Image itk::simple::BlackTopHat(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::BlackTopHatImageFilter Functional Interface +itk::simple::BlackTopHatImageFilter Functional Interface This function directly calls the execute method of BlackTopHatImageFilter in order to support a fully functional API @@ -44163,7 +44183,7 @@ BSplineTransform itk::simple::BSplineTransformInitializer(const Image &image1, c &transformDomainMeshSize=std::vector< uint32_t >(3, 1u), unsigned int order=3u) - BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such +BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such that it has a physically consistent definition. It sets the transform domain origin, physical dimensions and direction from information obtained from the image. It also sets the mesh size if asked to do so @@ -44211,7 +44231,7 @@ Transform itk::simple::CenteredTransformInitializer(const Image &fixedImage, con &transform, CenteredTransformInitializerFilter::OperationModeType oper ationMode=itk::simple::CenteredTransformInitializerFilter::MOMENTS) - CenteredTransformInitializer is a helper class intended to initialize the center of rotation and +CenteredTransformInitializer is a helper class intended to initialize the center of rotation and the translation of Transforms having the center of rotation among their parameters. @@ -44230,7 +44250,7 @@ public "; Transform itk::simple::CenteredVersorTransformInitializer(const Image &fixedImage, const Image &movingImage, const Transform &transform, bool computeRotation=false) - CenteredVersorTransformInitializer is a helper class intended to initialize the center of rotation, +CenteredVersorTransformInitializer is a helper class intended to initialize the center of rotation, versor, and translation of the VersorRigid3DTransform. @@ -44321,7 +44341,7 @@ public "; Image itk::simple::ClosingByReconstruction(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, bool fullyConnected=false, bool preserveIntensities=false) - itk::simple::ClosingByReconstructionImageFilter Functional Interface +itk::simple::ClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of ClosingByReconstructionImageFilter in order to support a fully functional API @@ -44333,7 +44353,7 @@ Image itk::simple::ClosingByReconstruction(const Image &, const std::vector< uin kernel=sitkBall, bool fullyConnected=false, bool preserveIntensities=false) - itk::simple::ClosingByReconstructionImageFilter Functional Interface +itk::simple::ClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of ClosingByReconstructionImageFilter in order to support a fully functional API @@ -44430,7 +44450,7 @@ Image itk::simple::ConfidenceConnected(const Image &image1, const std::vector< s &seedList, unsigned int numberOfIterations=4u, double multiplier=4.5, unsigned int initialNeighborhoodRadius=1u, uint8_t replaceValue=1u) - itk::simple::ConfidenceConnectedImageFilter Functional Interface +itk::simple::ConfidenceConnectedImageFilter Functional Interface This function directly calls the execute method of ConfidenceConnectedImageFilter in order to support a fully functional API @@ -44459,7 +44479,7 @@ Image itk::simple::ConnectedThreshold(const Image &image1, const std::vector< st ConnectedThresholdImageFilter::ConnectivityType connectivity=itk::simp le::ConnectedThresholdImageFilter::FaceConnectivity) - itk::simple::ConnectedThresholdImageFilter Functional Interface +itk::simple::ConnectedThresholdImageFilter Functional Interface This function directly calls the execute method of ConnectedThresholdImageFilter in order to support a fully functional API @@ -44550,7 +44570,7 @@ Image itk::simple::CurvatureAnisotropicDiffusion(const Image &image1, double tim conductanceParameter=3, unsigned int conductanceScalingUpdateInterval=1u, uint32_t numberOfIterations=5u) - itk::simple::CurvatureAnisotropicDiffusionImageFilter Procedural Interface +itk::simple::CurvatureAnisotropicDiffusionImageFilter Procedural Interface This function directly calls the execute method of CurvatureAnisotropicDiffusionImageFilter in order to support a procedural API @@ -44638,7 +44658,7 @@ public "; Image itk::simple::DilateObjectMorphology(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, double objectValue=1) - itk::simple::DilateObjectMorphologyImageFilter Functional Interface +itk::simple::DilateObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of DilateObjectMorphologyImageFilter in order to support a fully functional API @@ -44649,7 +44669,7 @@ public "; Image itk::simple::DilateObjectMorphology(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, double objectValue=1) - itk::simple::DilateObjectMorphologyImageFilter Functional Interface +itk::simple::DilateObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of DilateObjectMorphologyImageFilter in order to support a fully functional API @@ -44869,7 +44889,7 @@ public "; Image itk::simple::ErodeObjectMorphology(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, double objectValue=1, double backgroundValue=0) - itk::simple::ErodeObjectMorphologyImageFilter Functional Interface +itk::simple::ErodeObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of ErodeObjectMorphologyImageFilter in order to support a fully functional API @@ -44880,7 +44900,7 @@ public "; Image itk::simple::ErodeObjectMorphology(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, double objectValue=1, double backgroundValue=0) - itk::simple::ErodeObjectMorphologyImageFilter Functional Interface +itk::simple::ErodeObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of ErodeObjectMorphologyImageFilter in order to support a fully functional API @@ -44939,8 +44959,8 @@ public "; %javamethodmodifiers itk::simple::Extract "/** Image itk::simple::Extract(const Image &image1, const std::vector< unsigned int > -&size=std::vector< unsigned int >(3, 1), const std::vector< int > -&index=std::vector< int >(3, 0), +&size=std::vector< unsigned int >(4, 1), const std::vector< int > +&index=std::vector< int >(4, 0), ExtractImageFilter::DirectionCollapseToStrategyType directionCollapseT oStrategy=itk::simple::ExtractImageFilter::DIRECTIONCOLLAPSETOGUESS) @@ -45001,7 +45021,7 @@ stoppingValue=std::numeric_limits< float >::max()/2.0, FastMarchingBaseImageFilter::TopologyCheckType topologyCheck=itk::simple::FastMarchingBaseImageFilter::Nothing) - itk::simple::FastMarchingBaseImageFilter Functional Interface +itk::simple::FastMarchingBaseImageFilter Functional Interface This function directly calls the execute method of FastMarchingBaseImageFilter in order to support a fully functional API @@ -45235,7 +45255,7 @@ Image itk::simple::GradientAnisotropicDiffusion(const Image &image1, double time conductanceParameter=3, unsigned int conductanceScalingUpdateInterval=1u, uint32_t numberOfIterations=5u) - itk::simple::GradientAnisotropicDiffusionImageFilter Procedural Interface +itk::simple::GradientAnisotropicDiffusionImageFilter Procedural Interface This function directly calls the execute method of GradientAnisotropicDiffusionImageFilter in order to support a procedural API @@ -45339,7 +45359,7 @@ public "; %javamethodmodifiers itk::simple::GrayscaleDilate "/** Image itk::simple::GrayscaleDilate(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall) - itk::simple::GrayscaleDilateImageFilter Functional Interface +itk::simple::GrayscaleDilateImageFilter Functional Interface This function directly calls the execute method of GrayscaleDilateImageFilter in order to support a fully functional API @@ -45350,7 +45370,7 @@ public "; Image itk::simple::GrayscaleDilate(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall) - itk::simple::GrayscaleDilateImageFilter Functional Interface +itk::simple::GrayscaleDilateImageFilter Functional Interface This function directly calls the execute method of GrayscaleDilateImageFilter in order to support a fully functional API @@ -45360,7 +45380,7 @@ public "; %javamethodmodifiers itk::simple::GrayscaleErode "/** Image itk::simple::GrayscaleErode(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall) - itk::simple::GrayscaleErodeImageFilter Functional Interface +itk::simple::GrayscaleErodeImageFilter Functional Interface This function directly calls the execute method of GrayscaleErodeImageFilter in order to support a fully functional API @@ -45371,7 +45391,7 @@ public "; Image itk::simple::GrayscaleErode(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall) - itk::simple::GrayscaleErodeImageFilter Functional Interface +itk::simple::GrayscaleErodeImageFilter Functional Interface This function directly calls the execute method of GrayscaleErodeImageFilter in order to support a fully functional API @@ -45448,7 +45468,7 @@ public "; Image itk::simple::GrayscaleMorphologicalClosing(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalClosingImageFilter in order to support a fully functional API @@ -45459,7 +45479,7 @@ public "; Image itk::simple::GrayscaleMorphologicalClosing(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalClosingImageFilter in order to support a fully functional API @@ -45470,7 +45490,7 @@ public "; Image itk::simple::GrayscaleMorphologicalOpening(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalOpeningImageFilter in order to support a fully functional API @@ -45481,7 +45501,7 @@ public "; Image itk::simple::GrayscaleMorphologicalOpening(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalOpeningImageFilter in order to support a fully functional API @@ -46286,7 +46306,7 @@ public "; %javamethodmodifiers itk::simple::Laplacian "/** Image itk::simple::Laplacian(const Image &image1, bool useImageSpacing=true) - itk::simple::LaplacianImageFilter Procedural Interface +itk::simple::LaplacianImageFilter Procedural Interface This function directly calls the execute method of LaplacianImageFilter in order to support a procedural API @@ -46830,7 +46850,7 @@ public "; %javamethodmodifiers itk::simple::MorphologicalGradient "/** Image itk::simple::MorphologicalGradient(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall) - itk::simple::MorphologicalGradientImageFilter Functional Interface +itk::simple::MorphologicalGradientImageFilter Functional Interface This function directly calls the execute method of MorphologicalGradientImageFilter in order to support a fully functional API @@ -46841,7 +46861,7 @@ public "; Image itk::simple::MorphologicalGradient(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall) - itk::simple::MorphologicalGradientImageFilter Functional Interface +itk::simple::MorphologicalGradientImageFilter Functional Interface This function directly calls the execute method of MorphologicalGradientImageFilter in order to support a fully functional API @@ -46936,7 +46956,7 @@ Image itk::simple::NeighborhoodConnected(const Image &image1, const std::vector< int > &radius=std::vector< unsigned int >(3, 1), double replaceValue=1) - itk::simple::NeighborhoodConnectedImageFilter Functional Interface +itk::simple::NeighborhoodConnectedImageFilter Functional Interface This function directly calls the execute method of NeighborhoodConnectedImageFilter in order to support a fully functional API @@ -47059,7 +47079,7 @@ public "; Image itk::simple::OpeningByReconstruction(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, bool fullyConnected=false, bool preserveIntensities=false) - itk::simple::OpeningByReconstructionImageFilter Functional Interface +itk::simple::OpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of OpeningByReconstructionImageFilter in order to support a fully functional API @@ -47071,7 +47091,7 @@ Image itk::simple::OpeningByReconstruction(const Image &, const std::vector< uin kernel=sitkBall, bool fullyConnected=false, bool preserveIntensities=false) - itk::simple::OpeningByReconstructionImageFilter Functional Interface +itk::simple::OpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of OpeningByReconstructionImageFilter in order to support a fully functional API @@ -47174,7 +47194,7 @@ patchRadius=4u, uint32_t numberOfIterations=1u, uint32_t numberOfSamplePatches=200u, double sampleVariance=400.0, double noiseSigma=0.0, double noiseModelFidelityWeight=0.0) - itk::simple::PatchBasedDenoisingImageFilter Procedural Interface +itk::simple::PatchBasedDenoisingImageFilter Procedural Interface This function directly calls the execute method of PatchBasedDenoisingImageFilter in order to support a procedural API @@ -47319,7 +47339,7 @@ public "; %javamethodmodifiers itk::simple::RealAndImaginaryToComplex "/** Image itk::simple::RealAndImaginaryToComplex(const Image &image1, const Image &image2) - ComposeImageFilter combine several scalar images into a multicomponent image. +ComposeImageFilter combine several scalar images into a multicomponent image. This function directly calls the execute method of RealAndImaginaryToComplexImageFilter in order to support a procedural API @@ -47752,14 +47772,10 @@ The user can also select applications specifically for color images or environment variables. SITK_SHOW_COMMAND, SITK_SHOW_COLOR_COMMAND and SITK_SHOW_3D_COMMAND -allow the following tokens in their strings. - - - \"%a\" for the ImageJ application +allow the following tokens in their strings.\\\\li \\\\c \"%a\" for the ImageJ application \\\\li \\\\c \"%f\" +for SimpleITK's temporary image file - \"%f\" for SimpleITK's temporary image file - For example, the default SITK_SHOW_COMMAND string on Linux systems -is: +For example, the default SITK_SHOW_COMMAND string on Linux systems is: After token substitution it may become: @@ -47825,7 +47841,7 @@ public "; Image itk::simple::SignedDanielssonDistanceMap(const Image &image1, bool insideIsPositive=false, bool squaredDistance=false, bool useImageSpacing=false) - itk::simple::SignedDanielssonDistanceMapImageFilter Procedural Interface +itk::simple::SignedDanielssonDistanceMapImageFilter Procedural Interface This function directly calls the execute method of SignedDanielssonDistanceMapImageFilter in order to support a procedural API @@ -47960,7 +47976,7 @@ int32_t >(3, 0), const std::vector< int32_t > &stop=std::vector< int32_t >(3, std::numeric_limits< int32_t >::max()), const std::vector< int > &step=std::vector< int >(3, 1)) - itk::simple::SliceImageFilter Procedural Interface +itk::simple::SliceImageFilter Procedural Interface This function directly calls the execute method of SliceImageFilter in order to support a procedural API @@ -48395,7 +48411,7 @@ Image itk::simple::VectorConfidenceConnected(const Image &image1, const std::vec &seedList, unsigned int numberOfIterations=4u, double multiplier=4.5, unsigned int initialNeighborhoodRadius=1u, uint8_t replaceValue=1u) - itk::simple::VectorConfidenceConnectedImageFilter Functional Interface +itk::simple::VectorConfidenceConnectedImageFilter Functional Interface This function directly calls the execute method of VectorConfidenceConnectedImageFilter in order to support a fully functional API @@ -48541,7 +48557,7 @@ public "; Image itk::simple::WhiteTopHat(const Image &, uint32_t radius=1, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::WhiteTopHatImageFilter Functional Interface +itk::simple::WhiteTopHatImageFilter Functional Interface This function directly calls the execute method of WhiteTopHatImageFilter in order to support a fully functional API @@ -48552,7 +48568,7 @@ public "; Image itk::simple::WhiteTopHat(const Image &, const std::vector< uint32_t > vectorRadius, KernelEnum kernel=sitkBall, bool safeBorder=true) - itk::simple::WhiteTopHatImageFilter Functional Interface +itk::simple::WhiteTopHatImageFilter Functional Interface This function directly calls the execute method of WhiteTopHatImageFilter in order to support a fully functional API diff --git a/Wrapping/PythonDocstrings.i b/Wrapping/PythonDocstrings.i index c2fe9cec4..c5a29e079 100644 --- a/Wrapping/PythonDocstrings.i +++ b/Wrapping/PythonDocstrings.i @@ -10,7 +10,7 @@ C++ includes: itkBitwiseNotFunctor.h %feature("docstring") itk::Functor::DivFloor " - Cast arguments to double, performs division then takes the floor. +Cast arguments to double, performs division then takes the floor. C++ includes: itkDivideFloorFunctor.h "; @@ -124,7 +124,7 @@ C++ includes: itkSliceImageFilter.h %feature("docstring") itk::SliceImageFilter::GenerateOutputInformation " - SliceImageFilter produces an image which is a different resolution and with a +SliceImageFilter produces an image which is a different resolution and with a different pixel spacing than its input image. See: ProcessObject::GenerateOutputInformaton() @@ -937,7 +937,7 @@ iterative relaxation process of an estimated ND surface. The surface is described implicitly as the zero level set of a volume $ \\\\phi $ and allowed to deform under curvature flow. A set of contraints is imposed on this movement as follows: - \\\\[ u_{i,j,k}^{n+1} = \\\\left\\\\{ \\\\begin{array}{ll} +\\\\[ u_{i,j,k}^{n+1} = \\\\left\\\\{ \\\\begin{array}{ll} \\\\mbox{max} (u_{i,j,k}^{n} + \\\\Delta t H_{i,j,k}^{n}, 0) & \\\\mbox{\\\\f$B_{i,j,k} = 1\\\\f$} \\\\\\\\ \\\\mbox{min} (u_{i,j,k}^{n} + \\\\Delta t H_{i,j,k}^{n}, 0) & @@ -1473,7 +1473,7 @@ parameters fixed parameter %feature("docstring") itk::simple::BSplineTransformInitializerFilter " - BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such +BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such that it has a physically consistent definition. It sets the transform domain origin, physical dimensions and direction from information obtained from the image. It also sets the mesh size if asked to do so @@ -1928,7 +1928,7 @@ Destructor Labels the pixels on the border of the objects in a binary image. - BinaryContourImageFilter takes a binary image as input, where the pixels in the objects are +BinaryContourImageFilter takes a binary image as input, where the pixels in the objects are the pixels with a value equal to ForegroundValue. Only the pixels on the contours of the objects are kept. The pixels not on the border are changed to BackgroundValue. @@ -1936,7 +1936,7 @@ changed to BackgroundValue. The connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours. - http://hdl.handle.net/1926/1352 +http://hdl.handle.net/1926/1352 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -2059,7 +2059,7 @@ Destructor Fast binary dilation. - BinaryDilateImageFilter is a binary dilation morphologic operation. This implementation is +BinaryDilateImageFilter is a binary dilation morphologic operation. This implementation is based on the papers: L.Vincent \"Morphological transformations of binary images with @@ -2200,7 +2200,7 @@ Destructor Fast binary erosion. - BinaryErodeImageFilter is a binary erosion morphologic operation. This implementation is +BinaryErodeImageFilter is a binary erosion morphologic operation. This implementation is based on the papers: L.Vincent \"Morphological transformations of binary images with @@ -2342,7 +2342,7 @@ Destructor Remove holes not connected to the boundary of the image. - BinaryFillholeImageFilter fills holes in a binary image. +BinaryFillholeImageFilter fills holes in a binary image. Geodesic morphology and the Fillhole algorithm is described in Chapter 6 of Pierre Soille's book \"Morphological Image Analysis: Principles @@ -2449,7 +2449,7 @@ Destructor Remove the objects not connected to the boundary of the image. - BinaryGrindPeakImageFilter ginds peaks in a grayscale image. +BinaryGrindPeakImageFilter ginds peaks in a grayscale image. Geodesic morphology and the grind peak algorithm is described in Chapter 6 of Pierre Soille's book \"Morphological Image Analysis: @@ -2569,7 +2569,7 @@ Label the connected components in a binary image and produce a collection of label objects. - BinaryImageToLabelMapFilter labels the objects in a binary image. Each distinct object is +BinaryImageToLabelMapFilter labels the objects in a binary image. Each distinct object is assigned a unique label. The final object labels start with 1 and are consecutive. Objects that are reached earlier by a raster order scan have a lower label. @@ -2889,13 +2889,13 @@ Destructor Denoise a binary image using min/max curvature flow. - BinaryMinMaxCurvatureFlowImageFilter implements a curvature driven image denosing algorithm. This filter +BinaryMinMaxCurvatureFlowImageFilter implements a curvature driven image denosing algorithm. This filter assumes that the image is essentially binary: consisting of two classes. Iso-brightness contours in the input image are viewed as a level set. The level set is then evolved using a curvature-based speed function: - \\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] +\\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] where $ F_{\\\\mbox{minmax}} = \\\\min(\\\\kappa,0) $ if $ \\\\mbox{Avg}_{\\\\mbox{stencil}}(x) $ is less than or equal to $ T_{thresold} $ and $ \\\\max(\\\\kappa,0) $ , otherwise. $ \\\\kappa $ is the mean curvature of the iso-brightness contour at point $ x $ . @@ -4286,7 +4286,7 @@ This class is parameterized over the type of the input image and the type of the output image. It is also parameterized by the operation to be applied, using a Functor style. - UnaryFunctorImageFilter allows the output dimension of the filter to be larger than the input +UnaryFunctorImageFilter allows the output dimension of the filter to be larger than the input dimension. Thus subclasses of the UnaryFunctorImageFilter (like the CastImageFilter ) can be used to promote a 2D image to a 3D image, etc. @@ -4847,7 +4847,7 @@ Set/Get the output pixel type %feature("docstring") itk::simple::CenteredTransformInitializerFilter " - CenteredTransformInitializerFilter is a helper class intended to initialize the center of rotation and +CenteredTransformInitializerFilter is a helper class intended to initialize the center of rotation and the translation of Transforms having the center of rotation among their parameters. @@ -4874,12 +4874,7 @@ passes as the initial translation to the transform. This second approach assumes that the moments of the anatomical objects are similar for both images and hence the best initial guess for registration is to superimpose both mass centers. Note that this -assumption will probably not hold in multi-modality registration. - - -See: - itk::CenteredTransformInitializer - +assumption will probably not hold in multi-modality registration. \\\\sa itk::CenteredTransformInitializer C++ includes: sitkCenteredTransformInitializerFilter.h "; @@ -4944,7 +4939,7 @@ Destructor %feature("docstring") itk::simple::CenteredVersorTransformInitializerFilter " - CenteredVersorTransformInitializerFilter is a helper class intended to initialize the center of rotation, +CenteredVersorTransformInitializerFilter is a helper class intended to initialize the center of rotation, versor, and translation of the VersorRigid3DTransform. @@ -5174,7 +5169,7 @@ Destructor Combines two images in a checkerboard pattern. - CheckerBoardImageFilter takes two input images that must have the same dimension, size, +CheckerBoardImageFilter takes two input images that must have the same dimension, size, origin and spacing and produces an output image of the same size by combinining the pixels from the two input images in a checkerboard pattern. This filter is commonly used for visually comparing two @@ -5906,10 +5901,10 @@ Destructor %feature("docstring") itk::simple::ComposeImageFilter " - ComposeImageFilter combine several scalar images into a multicomponent image. +ComposeImageFilter combine several scalar images into a multicomponent image. - ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . +ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . Inputs and Usage All input images are expected to have the same template parameters @@ -6177,7 +6172,7 @@ Destructor Label the objects in a binary image. - ConnectedComponentImageFilter labels the objects in a binary image (non-zero pixels are considered +ConnectedComponentImageFilter labels the objects in a binary image (non-zero pixels are considered to be objects, zero-valued pixels are considered to be background). Each distinct object is assigned a unique label. The filter experiments with some improvements to the existing implementation, and @@ -6249,6 +6244,16 @@ Name of this class "; +%feature("docstring") itk::simple::ConnectedComponentImageFilter::GetObjectCount " + +After the filter is executed, holds the number of connected +components. + +This is a measurement. Its value is updated in the Execute methods, so +the value will only be valid after an execution. + +"; + %feature("docstring") itk::simple::ConnectedComponentImageFilter::SetFullyConnected " Set/Get whether the connected components are defined strictly by face @@ -6277,7 +6282,7 @@ Label pixels that are connected to a seed and lie within a range of values. - ConnectedThresholdImageFilter labels pixels with ReplaceValue that are connected to an initial Seed +ConnectedThresholdImageFilter labels pixels with ReplaceValue that are connected to an initial Seed AND lie within a Lower and Upper threshold range. See: itk::simple::ConnectedThreshold for the procedural interface @@ -6412,7 +6417,7 @@ Destructor Increase the image size by padding with a constant value. - ConstantPadImageFilter changes the output image region. If the output image region is larger +ConstantPadImageFilter changes the output image region. If the output image region is larger than the input image region, the extra pixels are filled in by a constant value. The output image region must be specified. @@ -6680,7 +6685,7 @@ Destructor Decrease the image size by cropping the image by an itk::Size at both the upper and lower bounds of the largest possible region. - CropImageFilter changes the image boundary of an image by removing pixels outside the +CropImageFilter changes the image boundary of an image by removing pixels outside the target region. The target region is not specified in advance, but calculated in BeforeThreadedGenerateData() . @@ -6874,12 +6879,12 @@ Destructor Denoise an image using curvature driven flow. - CurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- +CurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- brightness contours in the grayscale input image are viewed as a level set. The level set is then evolved using a curvature-based speed function: - \\\\[ I_t = \\\\kappa |\\\\nabla I| \\\\] where $ \\\\kappa $ is the curvature. +\\\\[ I_t = \\\\kappa |\\\\nabla I| \\\\] where $ \\\\kappa $ is the curvature. The advantage of this approach is that sharp boundaries are preserved with smoothing occurring only within a region. However, it should be @@ -7231,7 +7236,7 @@ Destructor Deformably register two images using the demons algorithm. - DemonsRegistrationFilter implements the demons deformable algorithm that register two images +DemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the displacement field which will map a moving image onto a fixed image. @@ -7671,7 +7676,7 @@ See T. Vercauteren, X. Pennec, A. Perchant and N. Ayache, \"Non- parametric Diffeomorphic Image Registration with the Demons Algorithm\", Proc. of MICCAI 2007. - DiffeomorphicDemonsRegistrationFilter implements the demons deformable algorithm that register two images +DiffeomorphicDemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the deformation field which will map a moving image onto a fixed image. @@ -8640,6 +8645,18 @@ C++ includes: sitkDisplacementFieldTransform.h "; %feature("docstring") itk::simple::DisplacementFieldTransform::DisplacementFieldTransform " + +Consume an image to construct a displacement field transform. + + + +WARNING: +The input displacement image is transferred to the constructed +transform object. The input image is modified to be a default +constructed Image object. +Image must be of sitkVectorFloat64 pixel type with the number of components +equal to the image dimension. + "; %feature("docstring") itk::simple::DisplacementFieldTransform::DisplacementFieldTransform " @@ -8651,7 +8668,7 @@ C++ includes: sitkDisplacementFieldTransform.h %feature("docstring") itk::simple::DisplacementFieldTransform::GetDisplacementField " Todo -The returned image is should not directly modify the internal +The returned image should not directly modify the internal displacement field. @@ -9630,7 +9647,7 @@ Destructor Expand the size of an image by an integer factor in each dimension. - ExpandImageFilter increases the size of an image by an integer factor in each dimension +ExpandImageFilter increases the size of an image by an integer factor in each dimension using a interpolation method. The output image size in each dimension is given by: @@ -9756,10 +9773,10 @@ Decrease the image size by cropping the image to the selected region bounds. - ExtractImageFilter changes the image boundary of an image by removing pixels outside the +ExtractImageFilter changes the image boundary of an image by removing pixels outside the target region. The target region must be specified. - ExtractImageFilter also collapses dimensions so that the input image may have more +ExtractImageFilter also collapses dimensions so that the input image may have more dimensions than the output image (i.e. 4-D input image to a 3-D output image). To specify what dimensions to collapse, the ExtractionRegion must be specified. For any dimension dim where @@ -9811,7 +9828,8 @@ Crop an image by specifying the region to keep See: itk::simple::Extract for the procedural interface - itk::ExtractImageFilter for the Doxygen on the original ITK class. + itk::ExtractImageFilter. The image is flipped across axes for which array[i] is true. @@ -11311,7 +11329,7 @@ it's valid when Execute is called with the clientData. Generate an n-dimensional image of a Gabor filter. - GaborImageSource generates an image of either the real (i.e. symmetric) or complex +GaborImageSource generates an image of either the real (i.e. symmetric) or complex (i.e. antisymmetric) part of the Gabor filter with the orientation directed along the x-axis. The GaborKernelFunction is used to evaluate the contribution along the x-axis whereas a non- normalized 1-D Gaussian envelope provides the contribution in each of @@ -11432,7 +11450,7 @@ Destructor Generate an n-dimensional image of a Gaussian. - GaussianImageSource generates an image of a Gaussian. m_Normalized determines whether or +GaussianImageSource generates an image of a Gaussian. m_Normalized determines whether or not the Gaussian is normalized (whether or not the sum over infinite space is 1.0) When creating an image, it is preferable tonotnormalize the Gaussian m_Scale scales the output of the Gaussian to span a range @@ -11667,7 +11685,7 @@ edge potential map. General characteristics of an edge potential map is that it has values close to zero in regions near the edges and values close to one inside the shape itself. Typically, the edge potential map is compute from the image gradient, for example: - \\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] +\\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] where $ I $ is image intensity and $ (\\\\nabla * G) $ is the derivative of Gaussian operator. @@ -12782,7 +12800,7 @@ Destructor Remove local minima not connected to the boundary of the image. - GrayscaleFillholeImageFilter fills holes in a grayscale image. Holes are local minima in the +GrayscaleFillholeImageFilter fills holes in a grayscale image. Holes are local minima in the grayscale topography that are not connected to boundaries of the image. Gray level values adjacent to a hole are extrapolated across the hole. @@ -13152,7 +13170,7 @@ Destructor Remove local maxima not connected to the boundary of the image. - GrayscaleGrindPeakImageFilter removes peaks in a grayscale image. Peaks are local maxima in the +GrayscaleGrindPeakImageFilter removes peaks in a grayscale image. Peaks are local maxima in the grayscale topography that are not connected to boundaries of the image. Gray level values adjacent to a peak are extrapolated through the peak. @@ -13723,7 +13741,7 @@ Destructor Generate an n-dimensional image of a grid. - GridImageSource generates an image of a grid. From the abstract... \"Certain classes +GridImageSource generates an image of a grid. From the abstract... \"Certain classes of images find disparate use amongst members of the ITK community for such purposes as visualization, simulation, testing, etc. Currently there exists two derived classes from the ImageSource class used for @@ -13853,7 +13871,7 @@ Identify local minima whose depth below the baseline is greater than h. - HConcaveImageFilter extract local minima that are more than h intensity units below the +HConcaveImageFilter extract local minima that are more than h intensity units below the (local) background. This has the effect of extracting objects that are darker than the background by at least h intensity units. @@ -13967,7 +13985,7 @@ Identify local maxima whose height above the baseline is greater than h. - HConvexImageFilter extract local maxima that are more than h intensity units above the +HConvexImageFilter extract local maxima that are more than h intensity units above the (local) background. This has the effect of extracting objects that are brighter than background by at least h intensity units. @@ -14080,7 +14098,7 @@ Destructor Suppress local maxima whose height above the baseline is less than h. - HMaximaImageFilter suppresses local maxima that are less than h intensity units above +HMaximaImageFilter suppresses local maxima that are less than h intensity units above the (local) background. This has the effect of smoothing over the \"high\" parts of the noise in the image without smoothing over large changes in intensity (region boundaries). See the HMinimaImageFilter to suppress the local minima whose depth is less than h intensity @@ -14175,7 +14193,7 @@ Destructor Suppress local minima whose depth below the baseline is less than h. - HMinimaImageFilter suppresses local minima that are less than h intensity units below +HMinimaImageFilter suppresses local minima that are less than h intensity units below the (local) background. This has the effect of smoothing over the \"low\" parts of the noise in the image without smoothing over large changes in intensity (region boundaries). See the HMaximaImageFilter to suppress the local maxima whose height is less than h intensity @@ -14423,7 +14441,7 @@ Computes the Hausdorff distance between the set of non-zero pixels of two images. - HausdorffDistanceImageFilter computes the distance between the set non-zero pixels of two images +HausdorffDistanceImageFilter computes the distance between the set non-zero pixels of two images using the following formula: \\\\[ H(A,B) = \\\\max(h(A,B),h(B,A)) \\\\] where \\\\[ h(A,B) = \\\\max_{a \\\\in A} \\\\min_{b \\\\in B} \\\\| a - b\\\\| \\\\] is the directed Hausdorff distance and $A$ and $B$ are respectively the set of non-zero pixels in the first and second input images. @@ -14513,7 +14531,7 @@ Normalize the grayscale values between two images by histogram matching. - HistogramMatchingImageFilter normalizes the grayscale values of a source image based on the +HistogramMatchingImageFilter normalizes the grayscale values of a source image based on the grayscale values of a reference image. This filter uses a histogram matching technique where the histograms of the two images are matched only at a specified number of quantile values. @@ -14527,7 +14545,7 @@ grayscale values are smaller than the mean grayscale value. ThresholdAtMeanInten The source image can be set via either SetInput() or SetSourceImage() . The reference image can be set via SetReferenceImage() . - SetNumberOfHistogramLevels() sets the number of bins used when creating histograms of the source +SetNumberOfHistogramLevels() sets the number of bins used when creating histograms of the source and reference images. SetNumberOfMatchPoints() governs the number of quantile values to be matched. This filter assumes that both the source and reference are of the same @@ -14890,25 +14908,25 @@ make sure that coping actually happens to the itk::Image pointed to is only poin %feature("docstring") itk::simple::Image::TransformContinuousIndexToPhysicalPoint " - Transform continuous index to physical point +Transform continuous index to physical point "; %feature("docstring") itk::simple::Image::TransformIndexToPhysicalPoint " - Transform index to physical point +Transform index to physical point "; %feature("docstring") itk::simple::Image::TransformPhysicalPointToContinuousIndex " - Transform physical point to continuous index +Transform physical point to continuous index "; %feature("docstring") itk::simple::Image::TransformPhysicalPointToIndex " - Transform physical point to index +Transform physical point to index "; @@ -15179,6 +15197,7 @@ See: Use demons image metric. + See: itk::DemonsImageToImageMetricv4 @@ -15623,7 +15642,7 @@ are mapped to a constant. Values over the interval are mapped to another constant. - IntensityWindowingImageFilter applies pixel-wise a linear transformation to the intensity values of +IntensityWindowingImageFilter applies pixel-wise a linear transformation to the intensity values of input image pixels. The linear transformation is defined by the user in terms of the minimum and maximum values that the output image should have and the lower and upper limits of the intensity window of @@ -15638,7 +15657,7 @@ Wiki Examples: All Examples - IntensityWindowingImageFilter +IntensityWindowingImageFilter See: RescaleIntensityImageFilter @@ -16008,7 +16027,7 @@ Destructor Computes the inverse of a displacement field. - InverseDisplacementFieldImageFilter takes a displacement field as input and computes the displacement +InverseDisplacementFieldImageFilter takes a displacement field as input and computes the displacement field that is its inverse. If the input displacement field was mapping coordinates from a space A into a space B, the output of this filter will map coordinates from the space B into the space A. @@ -16317,7 +16336,7 @@ Destructor Invert the intensity of an image. - InvertIntensityImageFilter inverts intensity of pixels by subtracting pixel value to a maximum +InvertIntensityImageFilter inverts intensity of pixels by subtracting pixel value to a maximum value. The maximum value can be set with SetMaximum and defaults the maximum of input pixel type. This filter can be used to invert, for example, a binary image, a distance map, etc. @@ -16634,7 +16653,7 @@ Destructor Label pixels that are connected to one set of seeds but not another. - IsolatedConnectedImageFilter finds the optimal threshold to separate two regions. It has two +IsolatedConnectedImageFilter finds the optimal threshold to separate two regions. It has two modes, one to separate dark regions surrounded by bright regions by automatically finding a minimum isolating upper threshold, and another to separate bright regions surrounded by dark regions by automatically @@ -16837,7 +16856,7 @@ Destructor Isolate watershed basins using two seeds. - IsolatedWatershedImageFilter labels pixels with ReplaceValue1 that are in the same watershed basin +IsolatedWatershedImageFilter labels pixels with ReplaceValue1 that are in the same watershed basin as Seed1 AND NOT the same as Seed2. The filter adjusts the waterlevel until the two seeds are not in different basins. The user supplies a Watershed threshold. The algorithm uses a binary search to adjust the @@ -17255,7 +17274,7 @@ Destructor Labels the pixels on the border of the objects in a labeled image. - LabelContourImageFilter takes a labeled image as input, where the pixels in the objects are +LabelContourImageFilter takes a labeled image as input, where the pixels in the objects are the pixels with a value different of the BackgroundValue. Only the pixels on the contours of the objects are kept. The pixels not on the border are changed to BackgroundValue. The labels of the object are @@ -17264,7 +17283,7 @@ the same in the input and in the output image. The connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours. - http://hdl.handle.net/1926/1352 +http://hdl.handle.net/1926/1352 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -17373,7 +17392,7 @@ Destructor convert a labeled image to a label collection image - LabelImageToLabelMapFilter converts a label image to a label collection image. The labels are +LabelImageToLabelMapFilter converts a label image to a label collection image. The labels are the same in the input and the output image. @@ -17611,7 +17630,7 @@ Destructor Mask and image with a LabelMap . - LabelMapMaskImageFilter mask the content of an input image according to the content of the +LabelMapMaskImageFilter mask the content of an input image according to the content of the input LabelMap . The masked pixel of the input image are set to the BackgroundValue. LabelMapMaskImageFilter can keep the input image for one label only, with Negated = false (the default) or it can mask the input image for a single label, when Negated equals true. In Both cases, the label is set with SetLabel() . @@ -17850,7 +17869,7 @@ Destructor Convert a LabelMap to a binary image. - LabelMapToBinaryImageFilter to a binary image. All the objects in the image are used as +LabelMapToBinaryImageFilter to a binary image. All the objects in the image are used as foreground. The background values of the original binary image can be restored by passing this image to the filter with the SetBackgroundImage() method. @@ -17943,7 +17962,7 @@ Destructor Converts a LabelMap to a labeled image. - LabelMapToBinaryImageFilter to a label image. +LabelMapToBinaryImageFilter to a label image. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -18274,7 +18293,7 @@ valuates the shape attribute at once. This implementation was taken from the Insight Journal paper: - http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -18555,7 +18574,7 @@ Given an intensity image and a label map, compute min, max, variance and mean of the pixels associated with each label or segment. - LabelStatisticsImageFilter computes the minimum, maximum, sum, mean, median, variance and sigma +LabelStatisticsImageFilter computes the minimum, maximum, sum, mean, median, variance and sigma of regions of an intensity image, where the regions are defined via a label map (a second input). The label image should be integral type. The filter needs all of its input image. It behaves as a filter with @@ -18840,7 +18859,7 @@ Destructor Make sure that the objects are not overlapping. - AttributeUniqueLabelMapFilter search the overlapping zones in the overlapping objects and keeps +AttributeUniqueLabelMapFilter search the overlapping zones in the overlapping objects and keeps only a single object on all the pixels of the image. The object to keep is selected according to their label. @@ -20785,14 +20804,14 @@ calculated and the one that gives the largest number of pixels is chosen. Since these both default to 0, if a user only sets one, the other is ignored. - Image size: fixedImage and movingImage need not be the same size, but +Image size: fixedImage and movingImage need not be the same size, but fixedMask must be the same size as fixedImage, and movingMask must be the same size as movingImage. Furthermore, whereas some algorithms require that the \"template\" be smaller than the \"image\" because of errors in the regions where the two are not fully overlapping, this filter has no such restriction. - Image spacing: Since the computations are done in the pixel domain, all +Image spacing: Since the computations are done in the pixel domain, all input images must have the same spacing. Outputs; The output is an image of RealPixelType that is the masked @@ -21543,7 +21562,7 @@ Merges several Label Maps. This filter takes one or more input Label Map and merges them. - SetMethod() can be used to change how the filter manage the labels from the +SetMethod() can be used to change how the filter manage the labels from the different label maps. KEEP (0): MergeLabelMapFilter do its best to keep the label unchanged, but if a label is already used in a previous label map, a new label is assigned. AGGREGATE (1): If the same label is found several times in the label maps, the label @@ -21651,12 +21670,12 @@ Destructor Denoise an image using min/max curvature flow. - MinMaxCurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- +MinMaxCurvatureFlowImageFilter implements a curvature driven image denoising algorithm. Iso- brightness contours in the grayscale input image are viewed as a level set. The level set is then evolved using a curvature-based speed function: - \\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] +\\\\[ I_t = F_{\\\\mbox{minmax}} |\\\\nabla I| \\\\] where $ F_{\\\\mbox{minmax}} = \\\\max(\\\\kappa,0) $ if $ \\\\mbox{Avg}_{\\\\mbox{stencil}}(x) $ is less than or equal to $ T_{thresold} $ and $ \\\\min(\\\\kappa,0) $ , otherwise. $ \\\\kappa $ is the mean curvature of the iso-brightness contour at point $ x $ . @@ -21989,7 +22008,7 @@ Increase the image size by padding with replicants of the input image value. - MirrorPadImageFilter changes the image bounds of an image. Any added pixels are filled in +MirrorPadImageFilter changes the image bounds of an image. Any added pixels are filled in with a mirrored replica of the input image. For instance, if the output image needs a pixel that istwo pixels to the left of the LargestPossibleRegionof the input image, the value assigned will be @@ -23105,7 +23124,7 @@ Label pixels that are connected to a seed and lie within a neighborhood. - NeighborhoodConnectedImageFilter labels pixels with ReplaceValue that are connected to an initial Seed +NeighborhoodConnectedImageFilter labels pixels with ReplaceValue that are connected to an initial Seed AND whose neighbors all lie within a Lower and Upper threshold range. See: itk::simple::NeighborhoodConnected for the procedural interface @@ -23362,7 +23381,7 @@ C++ includes: sitkNonCopyable.h Normalize an image by setting its mean to zero and variance to one. - NormalizeImageFilter shifts and scales an image so that the pixels in the image have a +NormalizeImageFilter shifts and scales an image so that the pixels in the image have a zero mean and unit variance. This filter uses StatisticsImageFilter to compute the mean and variance of the input and then applies ShiftScaleImageFilter to shift and scale the pixels. NB: since this filter normalizes the data to lie within -1 to 1, @@ -24286,7 +24305,7 @@ Destructor Paste an image into another image. - PasteImageFilter allows you to take a section of one image and paste into another +PasteImageFilter allows you to take a section of one image and paste into another image. The SetDestinationIndex() method prescribes where in the first input to start pasting data from the second input. The SetSourceRegion method prescribes the section of the second image to paste into the first. If the output requested @@ -25520,10 +25539,10 @@ Destructor %feature("docstring") itk::simple::RealAndImaginaryToComplexImageFilter " - ComposeImageFilter combine several scalar images into a multicomponent image. +ComposeImageFilter combine several scalar images into a multicomponent image. - ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . +ComposeImageFilter combine several scalar images into an itk::Image of vector pixel ( itk::Vector , itk::RGBPixel , ...), of std::complex pixel, or in an itk::VectorImage . Inputs and Usage All input images are expected to have the same template parameters @@ -25876,10 +25895,10 @@ Base class for computing IIR convolution with an approximation of a Gaussian kernel. - \\\\[ \\\\frac{ 1 }{ \\\\sigma \\\\sqrt{ 2 \\\\pi } } \\\\exp{ +\\\\[ \\\\frac{ 1 }{ \\\\sigma \\\\sqrt{ 2 \\\\pi } } \\\\exp{ \\\\left( - \\\\frac{x^2}{ 2 \\\\sigma^2 } \\\\right) } \\\\] - RecursiveGaussianImageFilter is the base class for recursive filters that approximate convolution +RecursiveGaussianImageFilter is the base class for recursive filters that approximate convolution with the Gaussian kernel. This class implements the recursive filtering method proposed by R.Deriche in IEEE-PAMI Vol.12, No.1, January 1990, pp 78-87, \"Fast Algorithms for Low-Level Vision\" @@ -25994,7 +26013,7 @@ Let \\\\[ L(x; t) = g(x; t) \\\\ast f(x) \\\\] be the scale-space representation Then the normalized derivative operator for normalized coordinates across scale is: - \\\\[ \\\\partial_\\\\xi = \\\\sqrt{t} \\\\partial_x \\\\] +\\\\[ \\\\partial_\\\\xi = \\\\sqrt{t} \\\\partial_x \\\\] The resulting scaling factor is \\\\[ \\\\sigma^N \\\\] where N is the order of the derivative. @@ -26170,7 +26189,7 @@ Wiki Examples: All Examples - RegionalMaximaImageFilter +RegionalMaximaImageFilter See: itk::simple::RegionalMaxima for the procedural interface @@ -26311,7 +26330,7 @@ a minima or not. The SetFlatIsMinima() method let the user choose which behavior This class was contribtued to the Insight Journal by Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. http://hdl.handle.net/1926/153 - RegionalMaximaImageFilter MathematicalMorphologyImageFilters +RegionalMaximaImageFilter MathematicalMorphologyImageFilters See: @@ -26323,7 +26342,7 @@ Wiki Examples: All Examples - RegionalMinimaImageFilter +RegionalMinimaImageFilter See: itk::simple::RegionalMinima for the procedural interface @@ -26456,7 +26475,7 @@ Relabel the components in an image such that consecutive labels are used. - RelabelComponentImageFilter remaps the labels associated with the objects in an image (as from +RelabelComponentImageFilter remaps the labels associated with the objects in an image (as from the output of ConnectedComponentImageFilter ) such that the label numbers are consecutive with no gaps between the label numbers used. By default, the relabeling will also sort the labels based on the size of the object: the largest object will have @@ -26467,7 +26486,7 @@ can be disabled using SetSortByObjectSize. Label #0 is assumed to be the background and is left unaltered by the relabeling. - RelabelComponentImageFilter is typically used on the output of the ConnectedComponentImageFilter for those applications that want to extract the largest object or the +RelabelComponentImageFilter is typically used on the output of the ConnectedComponentImageFilter for those applications that want to extract the largest object or the \"k\" largest objects. Any particular object can be extracted from the relabeled output using a BinaryThresholdImageFilter . A group of objects can be extracted from the relabled output using a ThresholdImageFilter . @@ -26483,7 +26502,7 @@ will be only those remaining. The GetOriginalNumberOfObjects method can be called to find out how many objects were present before the small ones were discarded. - RelabelComponentImageFilter can be run as an \"in place\" filter, where it will overwrite its +RelabelComponentImageFilter can be run as an \"in place\" filter, where it will overwrite its output. The default is run out of place (or generate a separate output). \"In place\" operation can be controlled via methods in the superclass, InPlaceImageFilter::InPlaceOn() and @@ -26796,7 +26815,7 @@ Destructor Resample an image via a coordinate transform. - ResampleImageFilter resamples an existing image through some coordinate transform, +ResampleImageFilter resamples an existing image through some coordinate transform, interpolating via some image function. The class is templated over the types of the input and output images. @@ -27009,7 +27028,7 @@ Destructor Applies a linear transformation to the intensity levels of the input Image . - RescaleIntensityImageFilter applies pixel-wise a linear transformation to the intensity values of +RescaleIntensityImageFilter applies pixel-wise a linear transformation to the intensity values of input image pixels. The linear transformation is defined by the user in terms of the minimum and maximum values that the output image should have. @@ -27017,7 +27036,7 @@ should have. The following equation gives the mapping of the intensity values - \\\\[ outputPixel = ( inputPixel - inputMin) \\\\cdot +\\\\[ outputPixel = ( inputPixel - inputMin) \\\\cdot \\\\frac{(outputMax - outputMin )}{(inputMax - inputMin)} + outputMin \\\\] All computations are performed in the precison of the input pixel's @@ -28415,7 +28434,7 @@ edge potential map. General characteristics of an edge potential map is that it has values close to zero in regions near the edges and values close to one inside the shape itself. Typically, the edge potential map is compute from the image gradient, for example: - \\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] +\\\\[ g(I) = 1 / ( 1 + | (\\\\nabla * G)(I)| ) \\\\] \\\\[ g(I) = \\\\exp^{-|(\\\\nabla * G)(I)|} \\\\] where $ I $ is image intensity and $ (\\\\nabla * G) $ is the derivative of Gaussian operator. @@ -28570,7 +28589,7 @@ Destructor Shift and scale the pixels in an image. - ShiftScaleImageFilter shifts the input pixel by Shift (default 0.0) and then scales the +ShiftScaleImageFilter shifts the input pixel by Shift (default 0.0) and then scales the pixel by Scale (default 1.0). All computattions are performed in the precison of the input pixel's RealType. Before assigning the computed value to the output pixel, the value is clamped at the NonpositiveMin @@ -28731,7 +28750,7 @@ Destructor Reduce the size of an image by an integer factor in each dimension. - ShrinkImageFilter reduces the size of an image by an integer factor in each dimension. +ShrinkImageFilter reduces the size of an image by an integer factor in each dimension. The algorithm implemented is a simple subsample. The output image size in each dimension is given by: @@ -28829,7 +28848,7 @@ Computes the sigmoid function pixel-wise. A linear transformation is applied first on the argument of the sigmoid fuction. The resulting total transfrom is given by - \\\\[ f(x) = (Max-Min) \\\\cdot \\\\frac{1}{\\\\left(1+e^{- \\\\frac{ +\\\\[ f(x) = (Max-Min) \\\\cdot \\\\frac{1}{\\\\left(1+e^{- \\\\frac{ x - \\\\beta }{\\\\alpha}}\\\\right)} + Min \\\\] Every output pixel is equal to f(x). Where x is the intensity of the @@ -29364,7 +29383,7 @@ Measures the similarity between the set of non-zero pixels of two images. - SimilarityIndexImageFilter measures the similarity between the set non-zero pixels of two images +SimilarityIndexImageFilter measures the similarity between the set non-zero pixels of two images using the following formula: \\\\[ S = \\\\frac{2 | A \\\\cap B |}{|A| + |B|} \\\\] where $A$ and $B$ are respectively the set of non-zero pixels in the first and second input images. Operator $|\\\\cdot|$ represents the size of a set and $\\\\cap$ represents the intersection of two sets. @@ -29838,7 +29857,7 @@ Wiki Examples: All Examples - SobelEdgeDetectionImageFilter +SobelEdgeDetectionImageFilter See: itk::simple::SobelEdgeDetection for the procedural interface @@ -30230,7 +30249,7 @@ Destructor Compute min. max, variance and mean of an Image . - StatisticsImageFilter computes the minimum, maximum, sum, mean, variance sigma of an image. +StatisticsImageFilter computes the minimum, maximum, sum, mean, variance sigma of an image. The filter needs all of its input image. It behaves as a filter with an input and output. Thus it can be inserted in a pipline with other filters and the statistics will only be recomputed if a downstream @@ -30517,7 +30536,7 @@ Switzerland. based on a variation of the DemonsRegistrationFilter . The basic mo along with the modification for avoiding large deformations when gradients have small values. - SymmetricForcesDemonsRegistrationFilter implements the demons deformable algorithm that register two images +SymmetricForcesDemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the deformation field which will map a moving image onto a fixed image. @@ -31003,7 +31022,7 @@ Set image values to a user-specified value if they are below, above, or between simple threshold values. - ThresholdImageFilter sets image values to a user-specified \"outside\" value (by default, +ThresholdImageFilter sets image values to a user-specified \"outside\" value (by default, \"black\") if the image values are below, above, or between simple threshold values. @@ -32222,7 +32241,7 @@ Wiki Examples: All Examples - ValuedRegionalMaximaImageFilter +ValuedRegionalMaximaImageFilter See: itk::simple::ValuedRegionalMaxima for the procedural interface @@ -32320,7 +32339,7 @@ Wiki Examples: All Examples - ValuedRegionalMinimaImageFilter +ValuedRegionalMinimaImageFilter See: itk::simple::ValuedRegionalMinima for the procedural interface @@ -32798,7 +32817,7 @@ Destructor %feature("docstring") itk::simple::Version " - Version info for SimpleITK. +Version info for SimpleITK. C++ includes: sitkVersion.h "; @@ -33370,7 +33389,7 @@ Destructor Warps an image using an input displacement field. - WarpImageFilter warps an existing image with respect to a given displacement field. +WarpImageFilter warps an existing image with respect to a given displacement field. A displacement field is represented as a image whose pixel type is some vector type with at least N elements, where N is the dimension of @@ -33385,7 +33404,7 @@ Each vector in the displacement field represent the distance between a geometric point in the input space and a point in the output space such that: - \\\\[ p_{in} = p_{out} + d \\\\] +\\\\[ p_{in} = p_{out} + d \\\\] Typically the mapped position does not correspond to an integer pixel position in the input image. Interpolation via an image function is @@ -33794,7 +33813,7 @@ Increase the image size by padding with replicants of the input image value. - WrapPadImageFilter changes the image bounds of an image. Added pixels are filled in with +WrapPadImageFilter changes the image bounds of an image. Added pixels are filled in with a wrapped replica of the input image. For instance, if the output image needs a pixel that istwo pixels to the left of the LargestPossibleRegionof the input image, the value assigned will be @@ -34832,7 +34851,7 @@ See: %feature("docstring") itk::simple::BinaryClosingByReconstruction " - itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface +itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryClosingByReconstructionImageFilter in order to support a fully functional API @@ -34840,7 +34859,7 @@ This function directly calls the execute method of BinaryClosingByReconstruction %feature("docstring") itk::simple::BinaryClosingByReconstruction " - itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface +itk::simple::BinaryClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryClosingByReconstructionImageFilter in order to support a fully functional API @@ -34862,7 +34881,7 @@ See: %feature("docstring") itk::simple::BinaryDilate " - itk::simple::BinaryDilateImageFilter Functional Interface +itk::simple::BinaryDilateImageFilter Functional Interface This function directly calls the execute method of BinaryDilateImageFilter in order to support a fully functional API @@ -34870,7 +34889,7 @@ This function directly calls the execute method of BinaryDilateImageFilter in or %feature("docstring") itk::simple::BinaryDilate " - itk::simple::BinaryDilateImageFilter Functional Interface +itk::simple::BinaryDilateImageFilter Functional Interface This function directly calls the execute method of BinaryDilateImageFilter in order to support a fully functional API @@ -34878,7 +34897,7 @@ This function directly calls the execute method of BinaryDilateImageFilter in or %feature("docstring") itk::simple::BinaryErode " - itk::simple::BinaryErodeImageFilter Functional Interface +itk::simple::BinaryErodeImageFilter Functional Interface This function directly calls the execute method of BinaryErodeImageFilter in order to support a fully functional API @@ -34886,7 +34905,7 @@ This function directly calls the execute method of BinaryErodeImageFilter in ord %feature("docstring") itk::simple::BinaryErode " - itk::simple::BinaryErodeImageFilter Functional Interface +itk::simple::BinaryErodeImageFilter Functional Interface This function directly calls the execute method of BinaryErodeImageFilter in order to support a fully functional API @@ -34980,7 +34999,7 @@ See: %feature("docstring") itk::simple::BinaryMorphologicalClosing " - itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface +itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalClosingImageFilter in order to support a fully functional API @@ -34988,7 +35007,7 @@ This function directly calls the execute method of BinaryMorphologicalClosingIma %feature("docstring") itk::simple::BinaryMorphologicalClosing " - itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface +itk::simple::BinaryMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalClosingImageFilter in order to support a fully functional API @@ -34996,7 +35015,7 @@ This function directly calls the execute method of BinaryMorphologicalClosingIma %feature("docstring") itk::simple::BinaryMorphologicalOpening " - itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface +itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalOpeningImageFilter in order to support a fully functional API @@ -35004,7 +35023,7 @@ This function directly calls the execute method of BinaryMorphologicalOpeningIma %feature("docstring") itk::simple::BinaryMorphologicalOpening " - itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface +itk::simple::BinaryMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of BinaryMorphologicalOpeningImageFilter in order to support a fully functional API @@ -35027,7 +35046,7 @@ See: %feature("docstring") itk::simple::BinaryOpeningByReconstruction " - itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface +itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryOpeningByReconstructionImageFilter in order to support a fully functional API @@ -35035,7 +35054,7 @@ This function directly calls the execute method of BinaryOpeningByReconstruction %feature("docstring") itk::simple::BinaryOpeningByReconstruction " - itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface +itk::simple::BinaryOpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of BinaryOpeningByReconstructionImageFilter in order to support a fully functional API @@ -35170,7 +35189,7 @@ See: %feature("docstring") itk::simple::BlackTopHat " - itk::simple::BlackTopHatImageFilter Functional Interface +itk::simple::BlackTopHatImageFilter Functional Interface This function directly calls the execute method of BlackTopHatImageFilter in order to support a fully functional API @@ -35178,7 +35197,7 @@ This function directly calls the execute method of BlackTopHatImageFilter in ord %feature("docstring") itk::simple::BlackTopHat " - itk::simple::BlackTopHatImageFilter Functional Interface +itk::simple::BlackTopHatImageFilter Functional Interface This function directly calls the execute method of BlackTopHatImageFilter in order to support a fully functional API @@ -35230,7 +35249,7 @@ See: %feature("docstring") itk::simple::BSplineTransformInitializer " - BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such +BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid such that it has a physically consistent definition. It sets the transform domain origin, physical dimensions and direction from information obtained from the image. It also sets the mesh size if asked to do so @@ -35267,7 +35286,7 @@ See: %feature("docstring") itk::simple::CenteredTransformInitializer " - CenteredTransformInitializer is a helper class intended to initialize the center of rotation and +CenteredTransformInitializer is a helper class intended to initialize the center of rotation and the translation of Transforms having the center of rotation among their parameters. @@ -35283,7 +35302,7 @@ See: %feature("docstring") itk::simple::CenteredVersorTransformInitializer " - CenteredVersorTransformInitializer is a helper class intended to initialize the center of rotation, +CenteredVersorTransformInitializer is a helper class intended to initialize the center of rotation, versor, and translation of the VersorRigid3DTransform. @@ -35357,7 +35376,7 @@ See: %feature("docstring") itk::simple::ClosingByReconstruction " - itk::simple::ClosingByReconstructionImageFilter Functional Interface +itk::simple::ClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of ClosingByReconstructionImageFilter in order to support a fully functional API @@ -35365,7 +35384,7 @@ This function directly calls the execute method of ClosingByReconstructionImageF %feature("docstring") itk::simple::ClosingByReconstruction " - itk::simple::ClosingByReconstructionImageFilter Functional Interface +itk::simple::ClosingByReconstructionImageFilter Functional Interface This function directly calls the execute method of ClosingByReconstructionImageFilter in order to support a fully functional API @@ -35444,7 +35463,7 @@ See: %feature("docstring") itk::simple::ConfidenceConnected " - itk::simple::ConfidenceConnectedImageFilter Functional Interface +itk::simple::ConfidenceConnectedImageFilter Functional Interface This function directly calls the execute method of ConfidenceConnectedImageFilter in order to support a fully functional API @@ -35466,7 +35485,7 @@ See: %feature("docstring") itk::simple::ConnectedThreshold " - itk::simple::ConnectedThresholdImageFilter Functional Interface +itk::simple::ConnectedThresholdImageFilter Functional Interface This function directly calls the execute method of ConnectedThresholdImageFilter in order to support a fully functional API @@ -35533,7 +35552,7 @@ See: %feature("docstring") itk::simple::CurvatureAnisotropicDiffusion " - itk::simple::CurvatureAnisotropicDiffusionImageFilter Procedural Interface +itk::simple::CurvatureAnisotropicDiffusionImageFilter Procedural Interface This function directly calls the execute method of CurvatureAnisotropicDiffusionImageFilter in order to support a procedural API @@ -35606,7 +35625,7 @@ See: %feature("docstring") itk::simple::DilateObjectMorphology " - itk::simple::DilateObjectMorphologyImageFilter Functional Interface +itk::simple::DilateObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of DilateObjectMorphologyImageFilter in order to support a fully functional API @@ -35614,7 +35633,7 @@ This function directly calls the execute method of DilateObjectMorphologyImageFi %feature("docstring") itk::simple::DilateObjectMorphology " - itk::simple::DilateObjectMorphologyImageFilter Functional Interface +itk::simple::DilateObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of DilateObjectMorphologyImageFilter in order to support a fully functional API @@ -35785,7 +35804,7 @@ See: %feature("docstring") itk::simple::ErodeObjectMorphology " - itk::simple::ErodeObjectMorphologyImageFilter Functional Interface +itk::simple::ErodeObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of ErodeObjectMorphologyImageFilter in order to support a fully functional API @@ -35793,7 +35812,7 @@ This function directly calls the execute method of ErodeObjectMorphologyImageFil %feature("docstring") itk::simple::ErodeObjectMorphology " - itk::simple::ErodeObjectMorphologyImageFilter Functional Interface +itk::simple::ErodeObjectMorphologyImageFilter Functional Interface This function directly calls the execute method of ErodeObjectMorphologyImageFilter in order to support a fully functional API @@ -35886,7 +35905,7 @@ See: %feature("docstring") itk::simple::FastMarchingBase " - itk::simple::FastMarchingBaseImageFilter Functional Interface +itk::simple::FastMarchingBaseImageFilter Functional Interface This function directly calls the execute method of FastMarchingBaseImageFilter in order to support a fully functional API @@ -36055,7 +36074,7 @@ See: %feature("docstring") itk::simple::GradientAnisotropicDiffusion " - itk::simple::GradientAnisotropicDiffusionImageFilter Procedural Interface +itk::simple::GradientAnisotropicDiffusionImageFilter Procedural Interface This function directly calls the execute method of GradientAnisotropicDiffusionImageFilter in order to support a procedural API @@ -36143,7 +36162,7 @@ See: %feature("docstring") itk::simple::GrayscaleDilate " - itk::simple::GrayscaleDilateImageFilter Functional Interface +itk::simple::GrayscaleDilateImageFilter Functional Interface This function directly calls the execute method of GrayscaleDilateImageFilter in order to support a fully functional API @@ -36151,7 +36170,7 @@ This function directly calls the execute method of GrayscaleDilateImageFilter in %feature("docstring") itk::simple::GrayscaleDilate " - itk::simple::GrayscaleDilateImageFilter Functional Interface +itk::simple::GrayscaleDilateImageFilter Functional Interface This function directly calls the execute method of GrayscaleDilateImageFilter in order to support a fully functional API @@ -36159,7 +36178,7 @@ This function directly calls the execute method of GrayscaleDilateImageFilter in %feature("docstring") itk::simple::GrayscaleErode " - itk::simple::GrayscaleErodeImageFilter Functional Interface +itk::simple::GrayscaleErodeImageFilter Functional Interface This function directly calls the execute method of GrayscaleErodeImageFilter in order to support a fully functional API @@ -36167,7 +36186,7 @@ This function directly calls the execute method of GrayscaleErodeImageFilter in %feature("docstring") itk::simple::GrayscaleErode " - itk::simple::GrayscaleErodeImageFilter Functional Interface +itk::simple::GrayscaleErodeImageFilter Functional Interface This function directly calls the execute method of GrayscaleErodeImageFilter in order to support a fully functional API @@ -36231,7 +36250,7 @@ See: %feature("docstring") itk::simple::GrayscaleMorphologicalClosing " - itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalClosingImageFilter in order to support a fully functional API @@ -36239,7 +36258,7 @@ This function directly calls the execute method of GrayscaleMorphologicalClosing %feature("docstring") itk::simple::GrayscaleMorphologicalClosing " - itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalClosingImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalClosingImageFilter in order to support a fully functional API @@ -36247,7 +36266,7 @@ This function directly calls the execute method of GrayscaleMorphologicalClosing %feature("docstring") itk::simple::GrayscaleMorphologicalOpening " - itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalOpeningImageFilter in order to support a fully functional API @@ -36255,7 +36274,7 @@ This function directly calls the execute method of GrayscaleMorphologicalOpening %feature("docstring") itk::simple::GrayscaleMorphologicalOpening " - itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface +itk::simple::GrayscaleMorphologicalOpeningImageFilter Functional Interface This function directly calls the execute method of GrayscaleMorphologicalOpeningImageFilter in order to support a fully functional API @@ -36836,7 +36855,7 @@ See: %feature("docstring") itk::simple::Laplacian " - itk::simple::LaplacianImageFilter Procedural Interface +itk::simple::LaplacianImageFilter Procedural Interface This function directly calls the execute method of LaplacianImageFilter in order to support a procedural API @@ -37267,7 +37286,7 @@ See: %feature("docstring") itk::simple::MorphologicalGradient " - itk::simple::MorphologicalGradientImageFilter Functional Interface +itk::simple::MorphologicalGradientImageFilter Functional Interface This function directly calls the execute method of MorphologicalGradientImageFilter in order to support a fully functional API @@ -37275,7 +37294,7 @@ This function directly calls the execute method of MorphologicalGradientImageFil %feature("docstring") itk::simple::MorphologicalGradient " - itk::simple::MorphologicalGradientImageFilter Functional Interface +itk::simple::MorphologicalGradientImageFilter Functional Interface This function directly calls the execute method of MorphologicalGradientImageFilter in order to support a fully functional API @@ -37345,7 +37364,7 @@ See: %feature("docstring") itk::simple::NeighborhoodConnected " - itk::simple::NeighborhoodConnectedImageFilter Functional Interface +itk::simple::NeighborhoodConnectedImageFilter Functional Interface This function directly calls the execute method of NeighborhoodConnectedImageFilter in order to support a fully functional API @@ -37445,7 +37464,7 @@ See: %feature("docstring") itk::simple::OpeningByReconstruction " - itk::simple::OpeningByReconstructionImageFilter Functional Interface +itk::simple::OpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of OpeningByReconstructionImageFilter in order to support a fully functional API @@ -37453,7 +37472,7 @@ This function directly calls the execute method of OpeningByReconstructionImageF %feature("docstring") itk::simple::OpeningByReconstruction " - itk::simple::OpeningByReconstructionImageFilter Functional Interface +itk::simple::OpeningByReconstructionImageFilter Functional Interface This function directly calls the execute method of OpeningByReconstructionImageFilter in order to support a fully functional API @@ -37526,7 +37545,7 @@ See: %feature("docstring") itk::simple::PatchBasedDenoising " - itk::simple::PatchBasedDenoisingImageFilter Procedural Interface +itk::simple::PatchBasedDenoisingImageFilter Procedural Interface This function directly calls the execute method of PatchBasedDenoisingImageFilter in order to support a procedural API @@ -37629,7 +37648,7 @@ See: %feature("docstring") itk::simple::RealAndImaginaryToComplex " - ComposeImageFilter combine several scalar images into a multicomponent image. +ComposeImageFilter combine several scalar images into a multicomponent image. This function directly calls the execute method of RealAndImaginaryToComplexImageFilter in order to support a procedural API @@ -37973,14 +37992,10 @@ The user can also select applications specifically for color images or environment variables. SITK_SHOW_COMMAND, SITK_SHOW_COLOR_COMMAND and SITK_SHOW_3D_COMMAND -allow the following tokens in their strings. - - - \"%a\" for the ImageJ application +allow the following tokens in their strings.\\\\li \\\\c \"%a\" for the ImageJ application \\\\li \\\\c \"%f\" +for SimpleITK's temporary image file - \"%f\" for SimpleITK's temporary image file - For example, the default SITK_SHOW_COMMAND string on Linux systems -is: +For example, the default SITK_SHOW_COMMAND string on Linux systems is: After token substitution it may become: @@ -38037,7 +38052,7 @@ See: %feature("docstring") itk::simple::SignedDanielssonDistanceMap " - itk::simple::SignedDanielssonDistanceMapImageFilter Procedural Interface +itk::simple::SignedDanielssonDistanceMapImageFilter Procedural Interface This function directly calls the execute method of SignedDanielssonDistanceMapImageFilter in order to support a procedural API @@ -38143,7 +38158,7 @@ generated. %feature("docstring") itk::simple::Slice " - itk::simple::SliceImageFilter Procedural Interface +itk::simple::SliceImageFilter Procedural Interface This function directly calls the execute method of SliceImageFilter in order to support a procedural API @@ -38497,7 +38512,7 @@ See: %feature("docstring") itk::simple::VectorConfidenceConnected " - itk::simple::VectorConfidenceConnectedImageFilter Functional Interface +itk::simple::VectorConfidenceConnectedImageFilter Functional Interface This function directly calls the execute method of VectorConfidenceConnectedImageFilter in order to support a fully functional API @@ -38610,7 +38625,7 @@ See: %feature("docstring") itk::simple::WhiteTopHat " - itk::simple::WhiteTopHatImageFilter Functional Interface +itk::simple::WhiteTopHatImageFilter Functional Interface This function directly calls the execute method of WhiteTopHatImageFilter in order to support a fully functional API @@ -38618,7 +38633,7 @@ This function directly calls the execute method of WhiteTopHatImageFilter in ord %feature("docstring") itk::simple::WhiteTopHat " - itk::simple::WhiteTopHatImageFilter Functional Interface +itk::simple::WhiteTopHatImageFilter Functional Interface This function directly calls the execute method of WhiteTopHatImageFilter in order to support a fully functional API From 7b8399814f4efd4ebba99b9859cb867d89bdd022 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 20 Jul 2015 14:52:11 -0400 Subject: [PATCH 078/412] Require libraries when a wrapping for a language is enabled At the Superbuild level when wrapping for a language was enabled, the requirements for the language were not marked as required. Not when a language is enabled the cmake package is required. Conflicts: CMake/sitkLanguageOptions.cmake Change-Id: I07f40e1e934d72b8d9b5fe128a1a5a8c30f1df47 --- CMake/sitkLanguageOptions.cmake | 43 +++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/CMake/sitkLanguageOptions.cmake b/CMake/sitkLanguageOptions.cmake index d3348f5d3..979840f7f 100644 --- a/CMake/sitkLanguageOptions.cmake +++ b/CMake/sitkLanguageOptions.cmake @@ -25,13 +25,16 @@ endmacro() # option ( WRAP_LUA "Wrap Lua" ON ) -find_package ( PythonInterp QUIET) # If you're not using python or it's the first time, be quiet -if (NOT WRAP_PYTHON) +if (DEFINED WRAP_PYTHON AND WRAP_PYTHON) + set(_QUIET "REQUIRED") +else() set(_QUIET "QUIET") endif() +find_package ( PythonInterp ${_QUIET}) + find_package ( PythonLibs ${PYTHON_VERSION_STRING} EXACT ${_QUIET} ) if (PYTHON_VERSION_STRING VERSION_LESS 2.6) @@ -61,8 +64,14 @@ endif() option( WRAP_PYTHON "Wrap Python" ${WRAP_PYTHON_DEFAULT} ) check_PIC_flag ( Python ) -find_package ( Java COMPONENTS Development Runtime QUIET ) -find_package ( JNI QUIET ) +if (DEFINED WRAP_JAVA AND WRAP_JAVA) + set(_QUIET "REQUIRED") +else() + set(_QUIET "QUIET") +endif() + +find_package ( Java COMPONENTS Development Runtime ${_QUIET} ) +find_package ( JNI ${_QUIET} ) if ( ${JAVA_FOUND} AND ${JNI_FOUND} ) set( WRAP_JAVA_DEFAULT ON ) else ( ${JAVA_FOUND} AND ${JNI_FOUND} ) @@ -92,7 +101,14 @@ list( APPEND SITK_LANGUAGES_VARS option ( WRAP_JAVA "Wrap Java" ${WRAP_JAVA_DEFAULT} ) check_PIC_flag ( Java ) -find_package ( TCL QUIET ) + +if (DEFINED WRAP_TCL AND WRAP_TCL) + set(_QUIET "REQUIRED") +else() + set(_QUIET "QUIET") +endif() + +find_package ( TCL ${_QUIET} ) if ( ${TCL_FOUND} ) set ( WRAP_TCL_DEFAULT ON ) else ( ${TCL_FOUND} ) @@ -124,7 +140,14 @@ list( APPEND SITK_LANGUAGES_VARS option ( WRAP_RUBY "Wrap Ruby" ${WRAP_RUBY_DEFAULT} ) check_PIC_flag ( Ruby ) -find_package( CSharp QUIET ) + +if (DEFINED WRAP_CSHARP AND WRAP_CSHARP) + set(_QUIET "REQUIRED") +else() + set(_QUIET "QUIET") +endif() + +find_package( CSharp ${_QUIET} ) if ( ${CSHARP_FOUND} AND NOT MINGW ) set ( WRAP_CSHARP_DEFAULT ON ) else () @@ -137,7 +160,13 @@ list( APPEND SITK_LANGUAGES_VARS ) option ( WRAP_CSHARP "Wrap C#" ${WRAP_CSHARP_DEFAULT} ) -find_package(R QUIET) +if (DEFINED WRAP_R AND WRAP_R) + set(_QUIET "REQUIRED") +else() + set(_QUIET "QUIET") +endif() + +find_package(R ${_QUIET}) if ( ${R_FOUND} AND NOT WIN32 ) set ( WRAP_R_DEFAULT ON ) else( ) From aa33380d1bc49f69c9360bcfe925ab0a02b2b7d2 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 14 Aug 2015 09:47:19 -0400 Subject: [PATCH 079/412] Do not pass unneeded language arguments on the command line Only pass language CMake variable to the SimpleITK sub-superbuild project when the language is enabled. Conflicts: CMake/sitkLanguageOptions.cmake Change-Id: I8c46f920d5ae3423912e5b78d4263a6907b09654 --- CMake/sitkLanguageOptions.cmake | 148 +++++++++++++++++++------------- 1 file changed, 87 insertions(+), 61 deletions(-) diff --git a/CMake/sitkLanguageOptions.cmake b/CMake/sitkLanguageOptions.cmake index 979840f7f..daf3658f2 100644 --- a/CMake/sitkLanguageOptions.cmake +++ b/CMake/sitkLanguageOptions.cmake @@ -47,23 +47,28 @@ if ( PYTHONLIBS_FOUND AND PYTHONINTERP_FOUND else() set( WRAP_PYTHON_DEFAULT OFF ) endif() -list( APPEND SITK_LANGUAGES_VARS - PYTHON_DEBUG_LIBRARY - PYTHON_EXECUTABLE - PYTHON_LIBRARY - PYTHON_INCLUDE_DIR -# PYTHON_INCLUDE_PATH ( deprecated ) - ) -# Debian "jessie" has this additional variable required to match -# python versions. -if(PYTHON_INCLUDE_DIR2) + +option( WRAP_PYTHON "Wrap Python" ${WRAP_PYTHON_DEFAULT} ) + +if ( WRAP_PYTHON ) list( APPEND SITK_LANGUAGES_VARS - PYTHON_INCLUDE_DIR2 + PYTHON_DEBUG_LIBRARY + PYTHON_EXECUTABLE + PYTHON_LIBRARY + PYTHON_INCLUDE_DIR + # PYTHON_INCLUDE_PATH ( deprecated ) ) -endif() -option( WRAP_PYTHON "Wrap Python" ${WRAP_PYTHON_DEFAULT} ) +# Debian "jessie" has this additional variable required to match +# python versions. + if(PYTHON_INCLUDE_DIR2) + list( APPEND SITK_LANGUAGES_VARS + PYTHON_INCLUDE_DIR2 + ) + endif() +endif () check_PIC_flag ( Python ) + if (DEFINED WRAP_JAVA AND WRAP_JAVA) set(_QUIET "REQUIRED") else() @@ -77,30 +82,33 @@ if ( ${JAVA_FOUND} AND ${JNI_FOUND} ) else ( ${JAVA_FOUND} AND ${JNI_FOUND} ) set( WRAP_JAVA_DEFAULT OFF ) endif ( ${JAVA_FOUND} AND ${JNI_FOUND} ) -list( APPEND SITK_LANGUAGES_VARS - Java_JAVA_EXECUTABLE - Java_JAVAC_EXECUTABLE - Java_JAR_EXECUTABLE - Java_VERSION_STRING - Java_VERSION_MAJOR - Java_VERSION_MINOR - Java_VERSION_PATCH - Java_VERSION_TWEAK - Java_VERSION - Java_INCLUDE_DIRS - Java_LIBRARIES - JNI_INCLUDE_DIRS - JNI_LIBRARIES - JAVA_AWT_LIBRARY - JAVA_JVM_LIBRARY - JAVA_INCLUDE_PATH - JAVA_INCLUDE_PATH2 - JAVA_AWT_INCLUDE_PATH - - ) + option ( WRAP_JAVA "Wrap Java" ${WRAP_JAVA_DEFAULT} ) check_PIC_flag ( Java ) +if ( WRAP_JAVA ) + list( APPEND SITK_LANGUAGES_VARS + Java_JAVA_EXECUTABLE + Java_JAVAC_EXECUTABLE + Java_JAR_EXECUTABLE + Java_VERSION_STRING + Java_VERSION_MAJOR + Java_VERSION_MINOR + Java_VERSION_PATCH + Java_VERSION_TWEAK + Java_VERSION + Java_INCLUDE_DIRS + Java_LIBRARIES + JNI_INCLUDE_DIRS + JNI_LIBRARIES + JAVA_AWT_LIBRARY + JAVA_JVM_LIBRARY + JAVA_INCLUDE_PATH + JAVA_INCLUDE_PATH2 + JAVA_AWT_INCLUDE_PATH + ) +endif() + if (DEFINED WRAP_TCL AND WRAP_TCL) set(_QUIET "REQUIRED") @@ -114,32 +122,42 @@ if ( ${TCL_FOUND} ) else ( ${TCL_FOUND} ) set ( WRAP_TCL_DEFAULT OFF ) endif ( ${TCL_FOUND} ) -list( APPEND SITK_LANGUAGES_VARS - TCL_LIBRARY - TCL_INCLUDE_PATH - TCL_TCLSH - TK_LIBRARY - TK_INCLUDE_PATH - TK_WISH ) + option ( WRAP_TCL "Wrap Tcl" ${WRAP_TCL_DEFAULT} ) +if ( WRAP_TCL ) + list( APPEND SITK_LANGUAGES_VARS + TCL_LIBRARY + TCL_INCLUDE_PATH + TCL_TCLSH + TK_LIBRARY + TK_INCLUDE_PATH + TK_WISH + ) +endif() + + find_package ( Ruby QUIET ) if ( ${RUBY_FOUND} ) set ( WRAP_RUBY_DEFAULT ON ) else ( ${RUBY_FOUND} ) set ( WRAP_RUBY_DEFAULT OFF ) endif ( ${RUBY_FOUND} ) -check_PIC_flag ( Ruby ) -list( APPEND SITK_LANGUAGES_VARS - RUBY_EXECUTABLE - RUBY_INCLUDE_DIRS - RUBY_LIBRARY - RUBY_VERSION - RUBY_FOUND - RUBY_INCLUDE_PATH ) + option ( WRAP_RUBY "Wrap Ruby" ${WRAP_RUBY_DEFAULT} ) check_PIC_flag ( Ruby ) +if ( WRAP_RUBY ) + list( APPEND SITK_LANGUAGES_VARS + RUBY_EXECUTABLE + RUBY_INCLUDE_DIRS + RUBY_LIBRARY + RUBY_VERSION + RUBY_FOUND + RUBY_INCLUDE_PATH + ) +endif() + if (DEFINED WRAP_CSHARP AND WRAP_CSHARP) set(_QUIET "REQUIRED") @@ -153,13 +171,18 @@ if ( ${CSHARP_FOUND} AND NOT MINGW ) else () set ( WRAP_CSHARP_DEFAULT OFF ) endif () -list( APPEND SITK_LANGUAGES_VARS - CSHARP_COMPILER - CSHARP_INTERPRETER - CSHARP_PLATFORM -) + option ( WRAP_CSHARP "Wrap C#" ${WRAP_CSHARP_DEFAULT} ) +if ( WRAP_CSHARP ) + list( APPEND SITK_LANGUAGES_VARS + CSHARP_COMPILER + CSHARP_INTERPRETER + CSHARP_PLATFORM + ) +endif() + + if (DEFINED WRAP_R AND WRAP_R) set(_QUIET "REQUIRED") else() @@ -173,15 +196,18 @@ else( ) set ( WRAP_R_DEFAULT OFF ) endif( ) - -list( APPEND SITK_LANGUAGES_VARS - R_INCLUDE_DIR - R_LIBRARIES - R_LIBRARY_BASE - R_COMMAND - RSCRIPT_EXECUTABLE ) option ( WRAP_R "Wrap R" ${WRAP_R_DEFAULT} ) +if ( WRAP_R ) + list( APPEND SITK_LANGUAGES_VARS + R_INCLUDE_DIR + R_LIBRARIES + R_LIBRARY_BASE + R_COMMAND + RSCRIPT_EXECUTABLE ) +endif() + + if( WIN32 ) mark_as_advanced( WRAP_R ) endif() From c02797891eb4a4c5c28a6cfdeb6af5edbfa8ad6c Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 23 Sep 2015 15:17:55 -0400 Subject: [PATCH 080/412] Updating ITK superbuild towards v4.8.1 pending release Change-Id: I382f994d50092fe8cd6d5308da789cbd4925bb8a --- SuperBuild/External_ITK.cmake | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 33eeda7d6..b44580890 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,8 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY git://itk.org/ITK.git) # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG 0ccdf6f19d36b812c77bfc4fa4ff9dfd6243ac66) # after v4.7.2 release +set(ITK_TAG_COMMAND GIT_TAG 3eaba76ccecb4128e91073b1e45058675a365025) +# right before v4.8.1 release if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From cec0b39732ed90de858f82f6e58febb7c1bacc4e Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 24 Sep 2015 12:57:49 -0400 Subject: [PATCH 081/412] Add missing Java variables to the language options files The correct version of javadoc was not getting propagated. Change-Id: Ib399449144e331850388c13302138b5fdaef9b7d --- CMake/sitkLanguageOptions.cmake | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CMake/sitkLanguageOptions.cmake b/CMake/sitkLanguageOptions.cmake index daf3658f2..0d94e5630 100644 --- a/CMake/sitkLanguageOptions.cmake +++ b/CMake/sitkLanguageOptions.cmake @@ -91,6 +91,8 @@ if ( WRAP_JAVA ) Java_JAVA_EXECUTABLE Java_JAVAC_EXECUTABLE Java_JAR_EXECUTABLE + Java_JAVADOC_EXECUTABLE + Java_JAVAH_EXECUTABLE Java_VERSION_STRING Java_VERSION_MAJOR Java_VERSION_MINOR From fee435f79f7004844ec4397f2e5e84073d8ac1e8 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 24 Sep 2015 17:14:58 -0400 Subject: [PATCH 082/412] Update ITK superbuild to 4.8.1 release Change-Id: Ib7d893c6eada99e0d418a2595986602b17027a5f --- SuperBuild/External_ITK.cmake | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index b44580890..7cc52ffb3 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,8 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY git://itk.org/ITK.git) # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG 3eaba76ccecb4128e91073b1e45058675a365025) -# right before v4.8.1 release +set(ITK_TAG_COMMAND GIT_TAG v4.8.1) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From db0ce5d4445185bf41d3b1e9e8f4acccc81dd77f Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 25 Sep 2015 16:23:01 -0400 Subject: [PATCH 083/412] Updating SimpleITK to 0.9.1 version for release Change-Id: I2690c33b64ec60d554b6778acf87d221ce5150d7 --- Version.cmake | 2 +- Wrapping/Rpackaging/SimpleITK/DESCRIPTION | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Version.cmake b/Version.cmake index 375a62a36..301cd654f 100644 --- a/Version.cmake +++ b/Version.cmake @@ -10,7 +10,7 @@ set(SimpleITK_VERSION_MAJOR 0) set(SimpleITK_VERSION_MINOR 9) -set(SimpleITK_VERSION_PATCH 0) +set(SimpleITK_VERSION_PATCH 1) #set(SimpleITK_VERSION_TWEAK "") diff --git a/Wrapping/Rpackaging/SimpleITK/DESCRIPTION b/Wrapping/Rpackaging/SimpleITK/DESCRIPTION index 3d5e235f9..b85e83095 100644 --- a/Wrapping/Rpackaging/SimpleITK/DESCRIPTION +++ b/Wrapping/Rpackaging/SimpleITK/DESCRIPTION @@ -1,6 +1,6 @@ Package: SimpleITK -Version: 0.9.0 -Date: 2012-04-05 +Version: 0.9.1 +Date: 2015-09-15 Title: Bindings to SimpleITK Image segmentation and registration toolkit. Authors@R: c(person("Richard", "Beare", role = c("aut", "cre"), email = "Richard.Beare@ieee.org"), From 87ac38a9c7418b6f476a6448369a1aa7e388a709 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 28 Sep 2015 13:58:46 -0400 Subject: [PATCH 084/412] Add md5 to URL for check sum Change-Id: I7ba27bdb4a4c8ac9b3fe8b90729a368ff54ba4f2 --- Documentation/Doxygen/PythonDownloads.dox | 262 +++++++++++----------- 1 file changed, 131 insertions(+), 131 deletions(-) diff --git a/Documentation/Doxygen/PythonDownloads.dox b/Documentation/Doxygen/PythonDownloads.dox index bf7c3cc20..8c716f43d 100644 --- a/Documentation/Doxygen/PythonDownloads.dox +++ b/Documentation/Doxygen/PythonDownloads.dox @@ -12,166 +12,166 @@ $ easy_install SimpleITK \section v090 SimpleITK 0.9.0 - \liSimpleITK-0.9.0-py2.6-linux-i686.egg - \liSimpleITK-0.9.0-py2.6-linux-x86_64.egg - \liSimpleITK-0.9.0-py2.6-macosx-10.6-universal.egg - \liSimpleITK-0.9.0-py2.7-linux-i686.egg - \liSimpleITK-0.9.0-py2.7-linux-x86_64.egg - \liSimpleITK-0.9.0-py2.7-macosx-10.6-intel.egg - \liSimpleITK-0.9.0-py2.7-win32.egg - \liSimpleITK-0.9.0-py2.7-win-amd64.egg - \liSimpleITK-0.9.0-py3.3-linux-i686.egg - \liSimpleITK-0.9.0-py3.3-linux-x86_64.egg - \liSimpleITK-0.9.0-py3.3-win32.egg - \liSimpleITK-0.9.0-py3.3-win-amd64.egg - \liSimpleITK-0.9.0-py3.4-linux-i686.egg - \liSimpleITK-0.9.0-py3.4-linux-x86_64.egg - \liSimpleITK-0.9.0-py3.4-win32.egg - \liSimpleITK-0.9.0-py3.4-win-amd64.egg + \liSimpleITK-0.9.0-py2.6-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.7-macosx-10.6-intel.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.3-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.3-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.3-win32.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.3-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.4-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.4-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.4-win32.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.4-win-amd64.egg (hosted at SourceForge) \section v081 SimpleITK 0.8.1 - \liSimpleITK-0.8.1-py2.6-linux-i686.egg - \liSimpleITK-0.8.1-py2.6-linux-x86_64.egg - \liSimpleITK-0.8.1-py2.6-macosx-10.6-universal.egg - \liSimpleITK-0.8.1-py2.7-linux-i686.egg - \liSimpleITK-0.8.1-py2.7-linux-x86_64.egg - \liSimpleITK-0.8.1-py2.7-macosx-10.6-intel.egg - \liSimpleITK-0.8.1-py2.7-win32.egg - \liSimpleITK-0.8.1-py2.7-win-amd64.egg - \liSimpleITK-0.8.1-py3.3-linux-i686.egg - \liSimpleITK-0.8.1-py3.3-linux-x86_64.egg - \liSimpleITK-0.8.1-py3.3-win32.egg - \liSimpleITK-0.8.1-py3.3-win-amd64.egg - \liSimpleITK-0.8.1-py3.4-linux-i686.egg - \liSimpleITK-0.8.1-py3.4-linux-x86_64.egg - \liSimpleITK-0.8.1-py3.4-win32.egg - \liSimpleITK-0.8.1-py3.4-win-amd64.egg + \liSimpleITK-0.8.1-py2.6-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.7-macosx-10.6-intel.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.3-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.3-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.3-win32.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.3-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.4-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.4-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.4-win32.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.4-win-amd64.egg (hosted at SourceForge) \section v080 SimpleITK 0.8.0 - \liSimpleITK-0.8.0-py2.6-linux-i686.egg - \liSimpleITK-0.8.0-py2.6-linux-x86_64.egg - \liSimpleITK-0.8.0-py2.6-macosx-10.6-universal.egg - \liSimpleITK-0.8.0-py2.6-macosx-10.7-intel.egg - \liSimpleITK-0.8.0-py2.7-linux-i686.egg - \liSimpleITK-0.8.0-py2.7-linux-x86_64.egg - \liSimpleITK-0.8.0-py2.7-macosx-10.7-intel.egg - \liSimpleITK-0.8.0-py2.7-win32.egg - \liSimpleITK-0.8.0-py2.7-win-amd64.egg - \liSimpleITK-0.8.0-py3.2-linux-i686.egg - \liSimpleITK-0.8.0-py3.2-linux-x86_64.egg - \liSimpleITK-0.8.0-py3.2-win32.egg - \liSimpleITK-0.8.0-py3.2-win-amd64.egg - \liSimpleITK-0.8.0-py3.3-linux-i686.egg - \liSimpleITK-0.8.0-py3.3-linux-x86_64.egg - \liSimpleITK-0.8.0-py3.3-win32.egg - \liSimpleITK-0.8.0-py3.3-win-amd64.egg + \liSimpleITK-0.8.0-py2.6-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.6-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.2-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.2-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.2-win32.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.2-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.3-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.3-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.3-win32.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.3-win-amd64.egg (hosted at SourceForge) \section v071 SimpleITK 0.7.1 - \liSimpleITK-0.7.1.post1.1-py2.7-win-amd64.egg - \liSimpleITK-0.7.1.post1.1-py3.2-win-amd64.egg - \liSimpleITK-0.7.1.post1.1-py3.3-win-amd64.egg - \liSimpleITK-0.7.1.post1-py2.6-linux-x86_64.egg - \liSimpleITK-0.7.1.post1-py2.6-macosx-10.6-universal.egg - \liSimpleITK-0.7.1.post1-py2.7-linux-i686.egg - \liSimpleITK-0.7.1.post1-py2.7-linux-x86_64.egg - \liSimpleITK-0.7.1.post1-py2.7-macosx-10.7-intel.egg - \liSimpleITK-0.7.1.post1-py2.7-win32.egg - \liSimpleITK-0.7.1.post1-py2.7-win-amd64.egg - \liSimpleITK-0.7.1.post1-py3.2-linux-i686.egg - \liSimpleITK-0.7.1.post1-py3.2-linux-x86_64.egg - \liSimpleITK-0.7.1.post1-py3.2-win32.egg - \liSimpleITK-0.7.1.post1-py3.2-win-amd64.egg - \liSimpleITK-0.7.1.post1-py3.3-win32.egg - \liSimpleITK-0.7.1.post1-py3.3-win-amd64.egg + \liSimpleITK-0.7.1.post1.1-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1.1-py3.2-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1.1-py3.3-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py3.2-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py3.2-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py3.2-win32.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py3.2-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py3.3-win32.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py3.3-win-amd64.egg (hosted at SourceForge) \section v070 SimpleITK 0.7.0 - \liSimpleITK-0.7.0-py2.6-linux-x86_64.egg - \liSimpleITK-0.7.0-py2.6-macosx-10.6-universal.egg - \liSimpleITK-0.7.0-py2.7-linux-i686.egg - \liSimpleITK-0.7.0-py2.7-linux-x86_64.egg - \liSimpleITK-0.7.0-py2.7-macosx-10.7-intel.egg - \liSimpleITK-0.7.0-py2.7-win32.egg - \liSimpleITK-0.7.0-py2.7-win-amd64.egg - \liSimpleITK-0.7.0-py3.2-linux-x86_64.egg - \liSimpleITK-0.7.0-py3.2-win32.egg - \liSimpleITK-0.7.0-py3.2-win-amd64.egg - \liSimpleITK-0.7.0-py3.3-win32.egg - \liSimpleITK-0.7.0-py3.3-win-amd64.egg + \liSimpleITK-0.7.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py3.2-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py3.2-win32.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py3.2-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py3.3-win32.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py3.3-win-amd64.egg (hosted at SourceForge) \section v061 SimpleITK 0.6.1 - \liSimpleITK-0.6.1.post2-py3.2-win32.egg - \liSimpleITK-0.6.1.post2-py3.2-win-amd64.egg - \liSimpleITK-0.6.1-py2.6-linux-x86_64.egg - \liSimpleITK-0.6.1-py2.6-macosx-10.6-universal.egg - \liSimpleITK-0.6.1-py2.7-linux-i686.egg - \liSimpleITK-0.6.1-py2.7-linux-x86_64.egg - \liSimpleITK-0.6.1-py2.7-macosx-10.7-intel.egg - \liSimpleITK-0.6.1-py2.7-win32.egg - \liSimpleITK-0.6.1-py2.7-win-amd64.egg - \liSimpleITK-0.6.1-py3.2-linux-i686.egg - \liSimpleITK-0.6.1-py3.2-linux-x86_64.egg + \liSimpleITK-0.6.1.post2-py3.2-win32.egg (hosted at SourceForge) + \liSimpleITK-0.6.1.post2-py3.2-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py3.2-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py3.2-linux-x86_64.egg (hosted at SourceForge) \section v060 SimpleITK 0.6.0 - \liSimpleITK-0.6.0-py2.6-linux-x86_64.egg - \liSimpleITK-0.6.0-py2.6-macosx-10.6-universal.egg - \liSimpleITK-0.6.0-py2.7-linux-i686.egg - \liSimpleITK-0.6.0-py2.7-linux-x86_64.egg - \liSimpleITK-0.6.0-py2.7-macosx-10.7-intel.egg - \liSimpleITK-0.6.0-py2.7-win32.egg - \liSimpleITK-0.6.0-py2.7-win-amd64.egg - \liSimpleITK-0.6.0-py3.2-linux-i686.egg - \liSimpleITK-0.6.0-py3.2-linux-x86_64.egg + \liSimpleITK-0.6.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py3.2-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py3.2-linux-x86_64.egg (hosted at SourceForge) \section v051 SimpleITK 0.5.1 - \liSimpleITK-0.5.1-py2.6-linux-x86_64.egg - \liSimpleITK-0.5.1-py2.6-macosx-10.6-universal.egg - \liSimpleITK-0.5.1-py2.6-macosx-10.7-intel.egg - \liSimpleITK-0.5.1-py2.7-linux-i686.egg - \liSimpleITK-0.5.1-py2.7-linux-x86_64.egg - \liSimpleITK-0.5.1-py2.7-macosx-10.7-intel.egg - \liSimpleITK-0.5.1-py2.7-win-amd64.egg - \liSimpleITK-0.5.1-py2.7-win32.egg + \liSimpleITK-0.5.1-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.6-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.7-win32.egg (hosted at SourceForge) \section v050 SimpleITK 0.5.0 - \liSimpleITK-0.5.0-py2.6-linux-x86_64.egg - \liSimpleITK-0.5.0-py2.6-macosx-10.6-universal.egg - \liSimpleITK-0.5.0-py2.6-macosx-10.7-intel.egg - \liSimpleITK-0.5.0-py2.7-linux-i686.egg - \liSimpleITK-0.5.0-py2.7-linux-x86_64.egg - \liSimpleITK-0.5.0-py2.7-macosx-10.7-intel.egg - \liSimpleITK-0.5.0-py2.7-win-amd64.egg - \liSimpleITK-0.5.0-py2.7-win32.egg + \liSimpleITK-0.5.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.6-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.7-win32.egg (hosted at SourceForge) \section v040b SimpleITK 0.4.0 Beta - \liSimpleITK-0.4.0.macosx-10.7-intel-py2.7.egg - \liSimpleITK-0.4.0.macosx-10.7-intel-py2.6.egg - \liSimpleITK-0.4.0.macosx-10.6-universal-py2.6.egg - \liSimpleITK-0.4.0-py2.6-linux-i686.egg - \liSimpleITK-0.4.0-py2.6-linux-x86_64.egg - \liSimpleITK-0.4.0-py2.7-linux-i686.egg - \liSimpleITK-0.4.0-py2.7-linux-x86_64.egg - \liSimpleITK-0.4.0-py2.7-win-amd64.egg - \liSimpleITK-0.4.0-py2.7-10.7-win32.egg + \liSimpleITK-0.4.0.macosx-10.7-intel-py2.7.egg (hosted at SourceForge) + \liSimpleITK-0.4.0.macosx-10.7-intel-py2.6.egg (hosted at SourceForge) + \liSimpleITK-0.4.0.macosx-10.6-universal-py2.6.egg (hosted at SourceForge) + \liSimpleITK-0.4.0-py2.6-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.4.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.4.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.4.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.4.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.4.0-py2.7-10.7-win32.egg (hosted at SourceForge) \section v030b SimpleITK 0.3.0 Beta - \liSimpleITK-0.3.0.macosx-10.7-intel-py2.7.egg - \liSimpleITK-0.3.0.macosx-10.7-intel-py2.6.egg - \liSimpleITK-0.3.0.macosx-10.6-universal-py2.6.egg - \liSimpleITK-0.3.0-py2.6-linux-x86_64.egg - \liSimpleITK-0.3.0-py2.7-linux-i686.egg - \liSimpleITK-0.3.0-py2.7-linux-x86_64.egg - \liSimpleITK-0.3.0-py2.7-win32.egg - \liSimpleITK-0.3.0-py2.7-win-amd64.egg - \liSimpleITK-0.3.0-py2.6-win32.egg + \liSimpleITK-0.3.0.macosx-10.7-intel-py2.7.egg (hosted at SourceForge) + \liSimpleITK-0.3.0.macosx-10.7-intel-py2.6.egg (hosted at SourceForge) + \liSimpleITK-0.3.0.macosx-10.6-universal-py2.6.egg (hosted at SourceForge) + \liSimpleITK-0.3.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.3.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.3.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.3.0-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.3.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.3.0-py2.6-win32.egg (hosted at SourceForge) */ From 613ba5e9bf447b83d47c5e58dec1a2e7821d3135 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 28 Sep 2015 15:14:14 -0400 Subject: [PATCH 085/412] Update Python download URLs to use https Change-Id: I1ed66332971e61b3f47f4de31b1ac91baac2b24c --- Documentation/Doxygen/PythonDownloads.dox | 262 +++++++++++----------- 1 file changed, 131 insertions(+), 131 deletions(-) diff --git a/Documentation/Doxygen/PythonDownloads.dox b/Documentation/Doxygen/PythonDownloads.dox index 8c716f43d..586c714b2 100644 --- a/Documentation/Doxygen/PythonDownloads.dox +++ b/Documentation/Doxygen/PythonDownloads.dox @@ -12,166 +12,166 @@ $ easy_install SimpleITK \section v090 SimpleITK 0.9.0 - \liSimpleITK-0.9.0-py2.6-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py2.6-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py2.7-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py2.7-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py2.7-macosx-10.6-intel.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py2.7-win32.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py2.7-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py3.3-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py3.3-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py3.3-win32.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py3.3-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py3.4-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py3.4-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py3.4-win32.egg (hosted at SourceForge) - \liSimpleITK-0.9.0-py3.4-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.6-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.7-macosx-10.6-intel.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.3-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.3-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.3-win32.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.3-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.4-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.4-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.4-win32.egg (hosted at SourceForge) + \liSimpleITK-0.9.0-py3.4-win-amd64.egg (hosted at SourceForge) \section v081 SimpleITK 0.8.1 - \liSimpleITK-0.8.1-py2.6-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py2.6-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py2.7-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py2.7-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py2.7-macosx-10.6-intel.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py2.7-win32.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py2.7-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py3.3-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py3.3-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py3.3-win32.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py3.3-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py3.4-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py3.4-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py3.4-win32.egg (hosted at SourceForge) - \liSimpleITK-0.8.1-py3.4-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.6-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.7-macosx-10.6-intel.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.3-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.3-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.3-win32.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.3-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.4-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.4-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.4-win32.egg (hosted at SourceForge) + \liSimpleITK-0.8.1-py3.4-win-amd64.egg (hosted at SourceForge) \section v080 SimpleITK 0.8.0 - \liSimpleITK-0.8.0-py2.6-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py2.6-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py2.6-macosx-10.7-intel.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py2.7-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py2.7-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py2.7-win32.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py2.7-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py3.2-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py3.2-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py3.2-win32.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py3.2-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py3.3-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py3.3-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py3.3-win32.egg (hosted at SourceForge) - \liSimpleITK-0.8.0-py3.3-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.6-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.6-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.2-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.2-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.2-win32.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.2-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.3-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.3-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.3-win32.egg (hosted at SourceForge) + \liSimpleITK-0.8.0-py3.3-win-amd64.egg (hosted at SourceForge) \section v071 SimpleITK 0.7.1 - \liSimpleITK-0.7.1.post1.1-py2.7-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1.1-py3.2-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1.1-py3.3-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1-py2.6-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1-py2.7-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1-py2.7-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1-py2.7-win32.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1-py2.7-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1-py3.2-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1-py3.2-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1-py3.2-win32.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1-py3.2-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1-py3.3-win32.egg (hosted at SourceForge) - \liSimpleITK-0.7.1.post1-py3.3-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1.1-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1.1-py3.2-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1.1-py3.3-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py3.2-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py3.2-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py3.2-win32.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py3.2-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py3.3-win32.egg (hosted at SourceForge) + \liSimpleITK-0.7.1.post1-py3.3-win-amd64.egg (hosted at SourceForge) \section v070 SimpleITK 0.7.0 - \liSimpleITK-0.7.0-py2.6-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.7.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) - \liSimpleITK-0.7.0-py2.7-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.7.0-py2.7-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.7.0-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) - \liSimpleITK-0.7.0-py2.7-win32.egg (hosted at SourceForge) - \liSimpleITK-0.7.0-py2.7-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.7.0-py3.2-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.7.0-py3.2-win32.egg (hosted at SourceForge) - \liSimpleITK-0.7.0-py3.2-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.7.0-py3.3-win32.egg (hosted at SourceForge) - \liSimpleITK-0.7.0-py3.3-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py3.2-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py3.2-win32.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py3.2-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py3.3-win32.egg (hosted at SourceForge) + \liSimpleITK-0.7.0-py3.3-win-amd64.egg (hosted at SourceForge) \section v061 SimpleITK 0.6.1 - \liSimpleITK-0.6.1.post2-py3.2-win32.egg (hosted at SourceForge) - \liSimpleITK-0.6.1.post2-py3.2-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.6.1-py2.6-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.6.1-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) - \liSimpleITK-0.6.1-py2.7-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.6.1-py2.7-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.6.1-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) - \liSimpleITK-0.6.1-py2.7-win32.egg (hosted at SourceForge) - \liSimpleITK-0.6.1-py2.7-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.6.1-py3.2-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.6.1-py3.2-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.6.1.post2-py3.2-win32.egg (hosted at SourceForge) + \liSimpleITK-0.6.1.post2-py3.2-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py3.2-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.6.1-py3.2-linux-x86_64.egg (hosted at SourceForge) \section v060 SimpleITK 0.6.0 - \liSimpleITK-0.6.0-py2.6-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.6.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) - \liSimpleITK-0.6.0-py2.7-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.6.0-py2.7-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.6.0-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) - \liSimpleITK-0.6.0-py2.7-win32.egg (hosted at SourceForge) - \liSimpleITK-0.6.0-py2.7-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.6.0-py3.2-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.6.0-py3.2-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py3.2-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.6.0-py3.2-linux-x86_64.egg (hosted at SourceForge) \section v051 SimpleITK 0.5.1 - \liSimpleITK-0.5.1-py2.6-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.5.1-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) - \liSimpleITK-0.5.1-py2.6-macosx-10.7-intel.egg (hosted at SourceForge) - \liSimpleITK-0.5.1-py2.7-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.5.1-py2.7-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.5.1-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) - \liSimpleITK-0.5.1-py2.7-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.5.1-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.6-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.5.1-py2.7-win32.egg (hosted at SourceForge) \section v050 SimpleITK 0.5.0 - \liSimpleITK-0.5.0-py2.6-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.5.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) - \liSimpleITK-0.5.0-py2.6-macosx-10.7-intel.egg (hosted at SourceForge) - \liSimpleITK-0.5.0-py2.7-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.5.0-py2.7-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.5.0-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) - \liSimpleITK-0.5.0-py2.7-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.5.0-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.6-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.7-macosx-10.7-intel.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.5.0-py2.7-win32.egg (hosted at SourceForge) \section v040b SimpleITK 0.4.0 Beta - \liSimpleITK-0.4.0.macosx-10.7-intel-py2.7.egg (hosted at SourceForge) - \liSimpleITK-0.4.0.macosx-10.7-intel-py2.6.egg (hosted at SourceForge) - \liSimpleITK-0.4.0.macosx-10.6-universal-py2.6.egg (hosted at SourceForge) - \liSimpleITK-0.4.0-py2.6-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.4.0-py2.6-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.4.0-py2.7-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.4.0-py2.7-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.4.0-py2.7-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.4.0-py2.7-10.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.4.0.macosx-10.7-intel-py2.7.egg (hosted at SourceForge) + \liSimpleITK-0.4.0.macosx-10.7-intel-py2.6.egg (hosted at SourceForge) + \liSimpleITK-0.4.0.macosx-10.6-universal-py2.6.egg (hosted at SourceForge) + \liSimpleITK-0.4.0-py2.6-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.4.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.4.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.4.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.4.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.4.0-py2.7-10.7-win32.egg (hosted at SourceForge) \section v030b SimpleITK 0.3.0 Beta - \liSimpleITK-0.3.0.macosx-10.7-intel-py2.7.egg (hosted at SourceForge) - \liSimpleITK-0.3.0.macosx-10.7-intel-py2.6.egg (hosted at SourceForge) - \liSimpleITK-0.3.0.macosx-10.6-universal-py2.6.egg (hosted at SourceForge) - \liSimpleITK-0.3.0-py2.6-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.3.0-py2.7-linux-i686.egg (hosted at SourceForge) - \liSimpleITK-0.3.0-py2.7-linux-x86_64.egg (hosted at SourceForge) - \liSimpleITK-0.3.0-py2.7-win32.egg (hosted at SourceForge) - \liSimpleITK-0.3.0-py2.7-win-amd64.egg (hosted at SourceForge) - \liSimpleITK-0.3.0-py2.6-win32.egg (hosted at SourceForge) + \liSimpleITK-0.3.0.macosx-10.7-intel-py2.7.egg (hosted at SourceForge) + \liSimpleITK-0.3.0.macosx-10.7-intel-py2.6.egg (hosted at SourceForge) + \liSimpleITK-0.3.0.macosx-10.6-universal-py2.6.egg (hosted at SourceForge) + \liSimpleITK-0.3.0-py2.6-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.3.0-py2.7-linux-i686.egg (hosted at SourceForge) + \liSimpleITK-0.3.0-py2.7-linux-x86_64.egg (hosted at SourceForge) + \liSimpleITK-0.3.0-py2.7-win32.egg (hosted at SourceForge) + \liSimpleITK-0.3.0-py2.7-win-amd64.egg (hosted at SourceForge) + \liSimpleITK-0.3.0-py2.6-win32.egg (hosted at SourceForge) */ From 0022379a3fd1c12d682bb09f61edd64ab79c575b Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 28 Sep 2015 15:14:36 -0400 Subject: [PATCH 086/412] Adding 0.9.1 release eggs to download page Change-Id: I99e457f295527a988f8f06c04b8af8b44fc551a5 --- Documentation/Doxygen/PythonDownloads.dox | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Documentation/Doxygen/PythonDownloads.dox b/Documentation/Doxygen/PythonDownloads.dox index 586c714b2..1bbae7dfe 100644 --- a/Documentation/Doxygen/PythonDownloads.dox +++ b/Documentation/Doxygen/PythonDownloads.dox @@ -9,6 +9,23 @@ It is also referenced from Python package index Pypi to facilitate automatic dow $ easy_install SimpleITK \endcode +\section v091 SimpleITK 0.9.1 + \li SimpleITK-0.9.1-py2.6-linux-i686.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py2.6-linux-x86_64.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py2.6-macosx-10.6-universal.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py2.7-linux-i686.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py2.7-linux-x86_64.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py2.7-macosx-10.6-intel.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py2.7-win32.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py2.7-win-amd64.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py3.3-linux-i686.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py3.3-linux-x86_64.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py3.3-win32.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py3.3-win-amd64.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py3.4-linux-i686.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py3.4-linux-x86_64.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py3.4-win32.egg (hosted at SourceForge) + \li SimpleITK-0.9.1-py3.4-win-amd64.egg (hosted at SourceForge) \section v090 SimpleITK 0.9.0 From 04c816edd7279333da4a3ffb6a187df7e792e7ab Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 7 Oct 2015 14:12:27 -0400 Subject: [PATCH 087/412] Updating ITK Superbuild towards 4.9 along master branch Change-Id: I44ce49c46243847d791df60a9f45d60cbc8bfdba --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 68a85e420..bbf2332af 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY git://itk.org/ITK.git) # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG v4.8.1) +set(ITK_TAG_COMMAND GIT_TAG 8c446afdd2781c0c54a2d9b115528c6d01d93abb) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 40ba6f512ef1d43c21d6bd78572e8df55ea238e3 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 7 Oct 2015 14:13:21 -0400 Subject: [PATCH 088/412] Adding print of learning rate in OptimizerScales test This help to evaluating the output and ensure the optimizer is going along the same path. Change-Id: I851554591427005dbf4f294e34478976a5550b36 --- Testing/Unit/sitkImageRegistrationMethodTests.cxx | 1 + 1 file changed, 1 insertion(+) diff --git a/Testing/Unit/sitkImageRegistrationMethodTests.cxx b/Testing/Unit/sitkImageRegistrationMethodTests.cxx index fa1b792ed..aaf5564e9 100644 --- a/Testing/Unit/sitkImageRegistrationMethodTests.cxx +++ b/Testing/Unit/sitkImageRegistrationMethodTests.cxx @@ -49,6 +49,7 @@ class IterationUpdate { std::cout << "\tLevel: " << std::setw(3) << m_Method.GetCurrentLevel() << std::endl; std::cout << "\tScales: " << m_Method.GetOptimizerScales() << std::endl; + std::cout << "\tLearning Rate: " << m_Method.GetOptimizerLearningRate() << std::endl; this->scales = m_Method.GetOptimizerScales(); this->toString = m_Method.ToString(); } From 9b368a528a80149716e58534c79bd3f43f69458a Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 8 Oct 2015 09:13:58 -0400 Subject: [PATCH 089/412] Adding initial json file to generate filter Change-Id: I9ea567576e07b4c24aa40bfaf236ab12798886ab --- ...ndmarkBasedTransformInitializerFilter.json | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Code/BasicFilters/json/LandmarkBasedTransformInitializerFilter.json diff --git a/Code/BasicFilters/json/LandmarkBasedTransformInitializerFilter.json b/Code/BasicFilters/json/LandmarkBasedTransformInitializerFilter.json new file mode 100644 index 000000000..bb0a3b36a --- /dev/null +++ b/Code/BasicFilters/json/LandmarkBasedTransformInitializerFilter.json @@ -0,0 +1,72 @@ +{ + "name" : "LandmarkBasedTransformInitializerFilter", + "template_code_filename" : "ImageFilter", + "doc" : "", + "number_of_inputs" : 0, + "output_image_type" : "float", + "pixel_types" : "typelist::MakeTypeList >::Type", + "filter_type" : "itk::LandmarkBasedTransformInitializer< itk::AffineTransform< double, TImageType::ImageDimension >, TImageType, TImageType>", + "include_files" : [ + "sitkTransform.h" + ], + "inputs" : [ + { + "name" : "Transform", + "type" : "Transform", + "custom_itk_cast" : "const typename FilterType::TransformType *itkTx = dynamic_cast(inTransform->GetITKBase() );\n if ( !itkTx )\n {\n sitkExceptionMacro( \"Unexpected error converting transform! Possible miss matching dimensions!\" );\n }\n else { filter->SetTransform( const_cast(itkTx) ); }" + } + ], + "members" : [ + { + "name" : "FixedLandmarks", + "type" : "std::vector", + "default" : "std::vector()", + "doc" : "", + "itk_type" : "LandmarkPointContainer", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set the Fixed landmark point containers", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Get the shrink factors." + }, + { + "name" : "MovingLandmarks", + "type" : "std::vector", + "default" : "std::vector()", + "doc" : "", + "itk_type" : "LandmarkPointContainer", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set the Moving landmark point containers", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Get the shrink factors." + }, + { + "name" : "LandmarkWeight", + "type" : "std::vector", + "default" : "std::vector()", + "doc" : "", + "itk_type" : "LandmarkWeight", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set the landmark weight point containers Weight includes diagonal elements of weight matrix", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Get the shrink factors." + }, + { + "name" : "ReferenceImage", + "type" : "Image", + "default" : "Image()", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set the reference image to define the parametric domain for the BSpline transform" + }, + { + "name" : "BSplineNumberOfControlPoints", + "type" : "unsigned int", + "default" : "4u", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set/Get the number of iterations", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Set/Get the number of iterations" + } + ], + "briefdescription" : "", + "detaileddescription" : "This class computes the transform that aligns the fixed and moving images given a set of pair landmarks. The class is templated over the Transform type as well as fixed image and moving image types. The transform computed gives the best fit transform that maps the fixed and moving images in a least squares sense. The indices are taken to correspond, so point 1 in the first set will get mapped close to point 1 in the second set, etc.\n\nCurrently, the following transforms are supported by the class: VersorRigid3DTransform Rigid2DTransform AffineTransform BSplineTransform \n\nAn equal number of fixed and moving landmarks need to be specified using SetFixedLandmarks() and SetMovingLandmarks() . Any number of landmarks may be specified. In the case of using Affine or BSpline transforms, each landmark pair can contribute in the final transform based on its defined weight. Number of weights should be equal to the number of landmarks and can be specified using SetLandmarkWeight() . By defaults are weights are set to one. Call InitializeTransform() to initialize the transform.\n\nThe class is based in part on Hybrid/vtkLandmarkTransform originally implemented in python by David G. Gobbi.\n\nThe solution is based on Berthold K. P. Horn (1987), \"Closed-form solution of absolute orientation\nusing unit quaternions,\" http://people.csail.mit.edu/bkph/papers/Absolute_Orientation.pdf \n\nThe Affine Transform initializer is based on an algorithm by H Spaeth, and is described in the Insight Journal Article \"Affine Transformation for Landmark Based Registration Initializer\nin ITK\" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.com/browse/publication/825 \n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Rigidly register one image to another using manually specified landmarks" +} From 11cada192e0000f9ba235457414a3086633c785d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 8 Oct 2015 10:04:44 -0400 Subject: [PATCH 090/412] Replacing json with generated source files. --- ...kLandmarkBasedTransformInitializerFilter.h | 177 +++++++++++++++ ...ndmarkBasedTransformInitializerFilter.json | 72 ------ ...andmarkBasedTransformInitializerFilter.cxx | 205 ++++++++++++++++++ 3 files changed, 382 insertions(+), 72 deletions(-) create mode 100644 Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h delete mode 100644 Code/BasicFilters/json/LandmarkBasedTransformInitializerFilter.json create mode 100644 Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx diff --git a/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h b/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h new file mode 100644 index 000000000..33fbb8da6 --- /dev/null +++ b/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h @@ -0,0 +1,177 @@ +/*========================================================================= +* +* Copyright Insight Software Consortium +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0.txt +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT 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 __sitkLandmarkBasedTransformInitializerFilter_h +#define __sitkLandmarkBasedTransformInitializerFilter_h + +/* + * WARNING: DO NOT EDIT THIS FILE! + * THIS FILE IS AUTOMATICALLY GENERATED BY THE SIMPLEITK BUILD PROCESS. + * Please look at sitkImageFilterTemplate.h.in to make changes. + */ + +#include + +#include "sitkBasicFilters.h" +#include "sitkImageFilter.h" + +namespace itk { + namespace simple { + + /**\class LandmarkBasedTransformInitializerFilter + + +This class computes the transform that aligns the fixed and moving images given a set of pair landmarks. The class is templated over the Transform type as well as fixed image and moving image types. The transform computed gives the best fit transform that maps the fixed and moving images in a least squares sense. The indices are taken to correspond, so point 1 in the first set will get mapped close to point 1 in the second set, etc. + +Currently, the following transforms are supported by the class: VersorRigid3DTransform Rigid2DTransform AffineTransform BSplineTransform + +An equal number of fixed and moving landmarks need to be specified using SetFixedLandmarks() and SetMovingLandmarks() . Any number of landmarks may be specified. In the case of using Affine or BSpline transforms, each landmark pair can contribute in the final transform based on its defined weight. Number of weights should be equal to the number of landmarks and can be specified using SetLandmarkWeight() . By defaults are weights are set to one. Call InitializeTransform() to initialize the transform. + +The class is based in part on Hybrid/vtkLandmarkTransform originally implemented in python by David G. Gobbi. + +The solution is based on Berthold K. P. Horn (1987), "Closed-form solution of absolute orientation +using unit quaternions," http://people.csail.mit.edu/bkph/papers/Absolute_Orientation.pdf + +The Affine Transform initializer is based on an algorithm by H Spaeth, and is described in the Insight Journal Article "Affine Transformation for Landmark Based Registration Initializer +in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.com/browse/publication/825 + +\par Wiki Examples: + +\li All Examples + +\li Rigidly register one image to another using manually specified landmarks +\sa itk::simple::LandmarkBasedTransformInitializerFilter for the procedural interface +\sa itk::LandmarkBasedTransformInitializer for the Doxygen on the original ITK class. + */ + class SITKBasicFilters_EXPORT LandmarkBasedTransformInitializerFilter : public ImageFilter<0> { + public: + typedef LandmarkBasedTransformInitializerFilter Self; + + /** Default Constructor that takes no arguments and initializes + * default parameters */ + LandmarkBasedTransformInitializerFilter(); + + /** Destructor */ + ~LandmarkBasedTransformInitializerFilter(); + + /** Define the pixels types supported by this filter */ + typedef typelist::MakeTypeList >::Type PixelIDTypeList; + + + + /** + * Set the Fixed landmark point containers + */ + Self& SetFixedLandmarks ( std::vector FixedLandmarks ) { this->m_FixedLandmarks = FixedLandmarks; return *this; } + + /** + * Get the shrink factors. + */ + std::vector GetFixedLandmarks() const { return this->m_FixedLandmarks; } + + /** + * Set the Moving landmark point containers + */ + Self& SetMovingLandmarks ( std::vector MovingLandmarks ) { this->m_MovingLandmarks = MovingLandmarks; return *this; } + + /** + * Get the shrink factors. + */ + std::vector GetMovingLandmarks() const { return this->m_MovingLandmarks; } + + /** + * Set the landmark weight point containers Weight includes diagonal elements of weight matrix + */ + Self& SetLandmarkWeight ( std::vector LandmarkWeight ) { this->m_LandmarkWeight = LandmarkWeight; return *this; } + + /** + * Get the shrink factors. + */ + std::vector GetLandmarkWeight() const { return this->m_LandmarkWeight; } + + /** + * Set the reference image to define the parametric domain for the BSpline transform + */ + Self& SetReferenceImage ( Image ReferenceImage ) { this->m_ReferenceImage = ReferenceImage; return *this; } + + /** + */ + Image GetReferenceImage() const { return this->m_ReferenceImage; } + + /** + * Set/Get the number of iterations + */ + Self& SetBSplineNumberOfControlPoints ( unsigned int BSplineNumberOfControlPoints ) { this->m_BSplineNumberOfControlPoints = BSplineNumberOfControlPoints; return *this; } + + /** + * Set/Get the number of iterations + */ + unsigned int GetBSplineNumberOfControlPoints() const { return this->m_BSplineNumberOfControlPoints; } + /** Name of this class */ + std::string GetName() const { return std::string ("LandmarkBasedTransformInitializerFilter"); } + + /** Print ourselves out */ + std::string ToString() const; + + + /** Execute the filter on the input image */ + Image Execute ( const Transform & transform ); + + + /** Execute the filter on the input image with the given parameters */ + Image Execute ( const Transform & transform, std::vector fixedLandmarks, std::vector movingLandmarks, std::vector landmarkWeight, Image referenceImage, unsigned int bSplineNumberOfControlPoints ); + + + private: + + /** Setup for member function dispatching */ + + typedef Image (Self::*MemberFunctionType)( const Transform * transform ); + template Image ExecuteInternal ( const Transform * transform ); + + + + friend struct detail::MemberFunctionAddressor; + + std::auto_ptr > m_MemberFactory; + + + /* */ + std::vector m_FixedLandmarks; + /* */ + std::vector m_MovingLandmarks; + /* */ + std::vector m_LandmarkWeight; + Image m_ReferenceImage; + unsigned int m_BSplineNumberOfControlPoints; + }; + + + + /** + * \brief itk::simple::LandmarkBasedTransformInitializerFilter Procedural Interface + * + * This function directly calls the execute method of LandmarkBasedTransformInitializerFilter + * in order to support a procedural API + * + * \sa itk::simple::LandmarkBasedTransformInitializerFilter for the object oriented interface + */ + SITKBasicFilters_EXPORT Image LandmarkBasedTransformInitializer ( const Transform & transform, std::vector fixedLandmarks = std::vector(), std::vector movingLandmarks = std::vector(), std::vector landmarkWeight = std::vector(), Image referenceImage = Image(), unsigned int bSplineNumberOfControlPoints = 4u ); + + } +} +#endif diff --git a/Code/BasicFilters/json/LandmarkBasedTransformInitializerFilter.json b/Code/BasicFilters/json/LandmarkBasedTransformInitializerFilter.json deleted file mode 100644 index bb0a3b36a..000000000 --- a/Code/BasicFilters/json/LandmarkBasedTransformInitializerFilter.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "name" : "LandmarkBasedTransformInitializerFilter", - "template_code_filename" : "ImageFilter", - "doc" : "", - "number_of_inputs" : 0, - "output_image_type" : "float", - "pixel_types" : "typelist::MakeTypeList >::Type", - "filter_type" : "itk::LandmarkBasedTransformInitializer< itk::AffineTransform< double, TImageType::ImageDimension >, TImageType, TImageType>", - "include_files" : [ - "sitkTransform.h" - ], - "inputs" : [ - { - "name" : "Transform", - "type" : "Transform", - "custom_itk_cast" : "const typename FilterType::TransformType *itkTx = dynamic_cast(inTransform->GetITKBase() );\n if ( !itkTx )\n {\n sitkExceptionMacro( \"Unexpected error converting transform! Possible miss matching dimensions!\" );\n }\n else { filter->SetTransform( const_cast(itkTx) ); }" - } - ], - "members" : [ - { - "name" : "FixedLandmarks", - "type" : "std::vector", - "default" : "std::vector()", - "doc" : "", - "itk_type" : "LandmarkPointContainer", - "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set the Fixed landmark point containers", - "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Get the shrink factors." - }, - { - "name" : "MovingLandmarks", - "type" : "std::vector", - "default" : "std::vector()", - "doc" : "", - "itk_type" : "LandmarkPointContainer", - "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set the Moving landmark point containers", - "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Get the shrink factors." - }, - { - "name" : "LandmarkWeight", - "type" : "std::vector", - "default" : "std::vector()", - "doc" : "", - "itk_type" : "LandmarkWeight", - "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set the landmark weight point containers Weight includes diagonal elements of weight matrix", - "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Get the shrink factors." - }, - { - "name" : "ReferenceImage", - "type" : "Image", - "default" : "Image()", - "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set the reference image to define the parametric domain for the BSpline transform" - }, - { - "name" : "BSplineNumberOfControlPoints", - "type" : "unsigned int", - "default" : "4u", - "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set/Get the number of iterations", - "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Set/Get the number of iterations" - } - ], - "briefdescription" : "", - "detaileddescription" : "This class computes the transform that aligns the fixed and moving images given a set of pair landmarks. The class is templated over the Transform type as well as fixed image and moving image types. The transform computed gives the best fit transform that maps the fixed and moving images in a least squares sense. The indices are taken to correspond, so point 1 in the first set will get mapped close to point 1 in the second set, etc.\n\nCurrently, the following transforms are supported by the class: VersorRigid3DTransform Rigid2DTransform AffineTransform BSplineTransform \n\nAn equal number of fixed and moving landmarks need to be specified using SetFixedLandmarks() and SetMovingLandmarks() . Any number of landmarks may be specified. In the case of using Affine or BSpline transforms, each landmark pair can contribute in the final transform based on its defined weight. Number of weights should be equal to the number of landmarks and can be specified using SetLandmarkWeight() . By defaults are weights are set to one. Call InitializeTransform() to initialize the transform.\n\nThe class is based in part on Hybrid/vtkLandmarkTransform originally implemented in python by David G. Gobbi.\n\nThe solution is based on Berthold K. P. Horn (1987), \"Closed-form solution of absolute orientation\nusing unit quaternions,\" http://people.csail.mit.edu/bkph/papers/Absolute_Orientation.pdf \n\nThe Affine Transform initializer is based on an algorithm by H Spaeth, and is described in the Insight Journal Article \"Affine Transformation for Landmark Based Registration Initializer\nin ITK\" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.com/browse/publication/825 \n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Rigidly register one image to another using manually specified landmarks" -} diff --git a/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx b/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx new file mode 100644 index 000000000..31d5f1255 --- /dev/null +++ b/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx @@ -0,0 +1,205 @@ +/*========================================================================= +* +* Copyright Insight Software Consortium +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0.txt +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*=========================================================================*/ +/* + * WARNING: DO NOT EDIT THIS FILE! + * THIS FILE IS AUTOMATICALLY GENERATED BY THE SIMPLEITK BUILD PROCESS. + * Please look at sitkImageFilterTemplate.cxx.in to make changes. + */ + +#include "itkImage.h" +#include "itkVectorImage.h" +#include "itkLabelMap.h" +#include "itkLabelObject.h" +#include "itkNumericTraits.h" +#include "itkNumericTraitsVariableLengthVectorPixel.h" +#include "itkVectorIndexSelectionCastImageFilter.h" +#include "itkComposeImageFilter.h" + +#include "sitkLandmarkBasedTransformInitializerFilter.h" +#include "itkLandmarkBasedTransformInitializerFilter.h" + +// Additional include files +#include "sitkTransform.h" +// Done with additional include files + +namespace itk { +namespace simple { + +//----------------------------------------------------------------------------- + +// +// Default constructor that initializes parameters +// +LandmarkBasedTransformInitializerFilter::LandmarkBasedTransformInitializerFilter () +{ + + this->m_FixedLandmarks = std::vector(); + this->m_MovingLandmarks = std::vector(); + this->m_LandmarkWeight = std::vector(); + this->m_ReferenceImage = Image(); + this->m_BSplineNumberOfControlPoints = 4u; + + this->m_MemberFactory.reset( new detail::MemberFunctionFactory( this ) ); + + this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > (); + this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > (); + + + +} + +// +// Destructor +// +LandmarkBasedTransformInitializerFilter::~LandmarkBasedTransformInitializerFilter () +{ + +} + + + +// +// ToString +// +std::string LandmarkBasedTransformInitializerFilter::ToString() const +{ + std::ostringstream out; + out << "itk::simple::LandmarkBasedTransformInitializerFilter\n"; + out << " FixedLandmarks: "; + this->ToStringHelper(out, this->m_FixedLandmarks); + out << std::endl; + out << " MovingLandmarks: "; + this->ToStringHelper(out, this->m_MovingLandmarks); + out << std::endl; + out << " LandmarkWeight: "; + this->ToStringHelper(out, this->m_LandmarkWeight); + out << std::endl; + out << " ReferenceImage: "; + this->ToStringHelper(out, this->m_ReferenceImage); + out << std::endl; + out << " BSplineNumberOfControlPoints: "; + this->ToStringHelper(out, this->m_BSplineNumberOfControlPoints); + out << std::endl; + + out << ProcessObject::ToString(); + return out.str(); +} + +// +// Execute +// +Image LandmarkBasedTransformInitializerFilter::Execute ( const Transform & transform, std::vector fixedLandmarks, std::vector movingLandmarks, std::vector landmarkWeight, Image referenceImage, unsigned int bSplineNumberOfControlPoints ) +{ + this->SetFixedLandmarks ( fixedLandmarks ); + this->SetMovingLandmarks ( movingLandmarks ); + this->SetLandmarkWeight ( landmarkWeight ); + this->SetReferenceImage ( referenceImage ); + this->SetBSplineNumberOfControlPoints ( bSplineNumberOfControlPoints ); + + return this->Execute ( transform ); +} + + +Image LandmarkBasedTransformInitializerFilter::Execute ( const Transform & transform ) +{ + PixelIDValueEnum type = transform.GetPixelID(); + unsigned int dimension = transform.GetDimension(); + + return this->m_MemberFactory->GetMemberFunction( type, dimension )( &transform ); +} + + +//----------------------------------------------------------------------------- + +// +// Custom Casts +// +namespace { + +} + +//----------------------------------------------------------------------------- + +// +// ExecuteInternal +// +template +Image LandmarkBasedTransformInitializerFilter::ExecuteInternal ( const Transform * inTransform ) +{ + // Define the input and output image types + typedef TImageType InputImageType; + + + //Define output image type + typedef float OutputImageType; + + + + typedef itk::LandmarkBasedTransformInitializer< itk::AffineTransform< double, TImageType::ImageDimension >, TImageType, TImageType> FilterType; + // Set up the ITK filter + typename FilterType::Pointer filter = FilterType::New(); + + + assert( inTransform != NULL ); + const typename FilterType::TransformType *itkTx = dynamic_cast(inTransform->GetITKBase() ); + if ( !itkTx ) + { + sitkExceptionMacro( "Unexpected error converting transform! Possible miss matching dimensions!" ); + } + else { filter->SetTransform( const_cast(itkTx) ); } + + + filter->SetFixedLandmarks ( this->m_FixedLandmarks ); + filter->SetMovingLandmarks ( this->m_MovingLandmarks ); + filter->SetLandmarkWeight ( this->m_LandmarkWeight ); + filter->SetReferenceImage ( this->m_ReferenceImage ); + filter->SetBSplineNumberOfControlPoints ( this->m_BSplineNumberOfControlPoints ); + + + + + this->PreUpdate( filter.GetPointer() ); + + + + // Run the ITK filter and return the output as a SimpleITK image + filter->Update(); + + + + typename FilterType::OutputImageType *itkOutImage = filter->GetOutput(); + this->FixNonZeroIndex( itkOutImage ); + return Image( this->CastITKToImage(itkOutImage) ); + +} + +//----------------------------------------------------------------------------- + + +// +// Function to run the Execute method of this filter +// +Image LandmarkBasedTransformInitializer ( const Transform & transform, std::vector fixedLandmarks, std::vector movingLandmarks, std::vector landmarkWeight, Image referenceImage, unsigned int bSplineNumberOfControlPoints ) +{ + LandmarkBasedTransformInitializerFilter filter; + return filter.Execute ( transform, fixedLandmarks, movingLandmarks, landmarkWeight, referenceImage, bSplineNumberOfControlPoints ); +} + + +} // end namespace simple +} // end namespace itk From 5ad6e9a456823557b79b56101111c40bd4180239 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Fri, 9 Oct 2015 14:45:52 -0400 Subject: [PATCH 091/412] Added SITK_OVERRIDE macro Add SITK_OVERRIDE to sitkMacro.h to eliminate a warning produced by clang 7.0. The compiler complains when a class overrides a member function without the "override" specifier, a new feature of C++11. Change-Id: If7bcd648432315495a3fa014489b9d8396ba7d94 --- Code/BasicFilters/include/itkHashImageFilter.h | 8 ++++---- .../BasicFilters/include/itkSliceImageFilter.h | 10 +++++----- Code/Common/include/sitkMacro.h | 18 ++++++++++++++++++ Code/Common/src/sitkProcessObject.cxx | 4 ++-- Code/Common/src/sitkTransform.cxx | 4 ++-- 5 files changed, 31 insertions(+), 13 deletions(-) diff --git a/Code/BasicFilters/include/itkHashImageFilter.h b/Code/BasicFilters/include/itkHashImageFilter.h index 68208e8f3..9711edcfa 100644 --- a/Code/BasicFilters/include/itkHashImageFilter.h +++ b/Code/BasicFilters/include/itkHashImageFilter.h @@ -83,7 +83,7 @@ class HashImageFilter: * output. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) SITK_OVERRIDE; protected: @@ -91,18 +91,18 @@ class HashImageFilter: // virtual ~HashImageFilter(); // implementation not needed - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const SITK_OVERRIDE; // See superclass for doxygen documentation // // This method is to do work after the superclass potential threaded // copy. - void AfterThreadedGenerateData(); + void AfterThreadedGenerateData() SITK_OVERRIDE; // See superclass for doxygen documentation // // Override since the filter produces all of its output - void EnlargeOutputRequestedRegion(DataObject *data); + void EnlargeOutputRequestedRegion(DataObject *data) SITK_OVERRIDE; private: HashImageFilter(const Self &); //purposely not implemented diff --git a/Code/BasicFilters/include/itkSliceImageFilter.h b/Code/BasicFilters/include/itkSliceImageFilter.h index 2e152e5b6..cdadefff3 100644 --- a/Code/BasicFilters/include/itkSliceImageFilter.h +++ b/Code/BasicFilters/include/itkSliceImageFilter.h @@ -116,9 +116,9 @@ class ITK_EXPORT SliceImageFilter: * resolution and with a different pixel spacing than its input * image. * \sa ProcessObject::GenerateOutputInformaton() */ - virtual void GenerateOutputInformation(); + virtual void GenerateOutputInformation() SITK_OVERRIDE; - virtual void GenerateInputRequestedRegion(); + virtual void GenerateInputRequestedRegion() SITK_OVERRIDE; #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ @@ -132,7 +132,7 @@ class ITK_EXPORT SliceImageFilter: protected: SliceImageFilter(); // ~SliceImageFilter() {} default ok - void PrintSelf(std::ostream & os, Indent indent) const; + void PrintSelf(std::ostream & os, Indent indent) const SITK_OVERRIDE; /** SliceImageFilter can be implemented as a multithreaded filter. * Therefore, this implementation provides a ThreadedGenerateData() routine @@ -145,9 +145,9 @@ class ITK_EXPORT SliceImageFilter: * \sa ImageToImageFilter::ThreadedGenerateData(), * ImageToImageFilter::GenerateData() */ void ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread, - ThreadIdType threadId); + ThreadIdType threadId) SITK_OVERRIDE; - void VerifyInputInformation(); + void VerifyInputInformation() SITK_OVERRIDE; private: SliceImageFilter(const Self &); //purposely not implemented diff --git a/Code/Common/include/sitkMacro.h b/Code/Common/include/sitkMacro.h index c4fb98e84..eb090aee1 100644 --- a/Code/Common/include/sitkMacro.h +++ b/Code/Common/include/sitkMacro.h @@ -51,6 +51,24 @@ #endif #endif + +#if __cplusplus >= 201103L +// In c++11 the override keyword allows you to explicity define that a function +// is intended to override the base-class version. This makes the code more +// managable and fixes a set of common hard-to-find bugs. +#define SITK_OVERRIDE override +// In C++11 the throw-list specification has been deprecated, +// replaced with the noexcept specifier. Using this function +// specification adds the run-time check that the method does not +// throw. If it does throw then std::terminate will be called. +// Use cautiously. +#define SITK_NOEXCEPT noexcept +#else +#define SITK_OVERRIDE +#define SITK_NOEXCEPT throw() +#endif + + namespace itk { namespace simple { diff --git a/Code/Common/src/sitkProcessObject.cxx b/Code/Common/src/sitkProcessObject.cxx index 4b4acf6ac..cf5b9f56d 100644 --- a/Code/Common/src/sitkProcessObject.cxx +++ b/Code/Common/src/sitkProcessObject.cxx @@ -66,7 +66,7 @@ class SimpleAdaptorCommand } /** Invoke the member function. */ - virtual void Execute(Object *, const EventObject & ) + virtual void Execute(Object *, const EventObject & ) SITK_OVERRIDE { if (m_That) { @@ -75,7 +75,7 @@ class SimpleAdaptorCommand } /** Invoke the member function with a const object */ - virtual void Execute(const Object *, const EventObject & ) + virtual void Execute(const Object *, const EventObject & ) SITK_OVERRIDE { if ( m_That ) { diff --git a/Code/Common/src/sitkTransform.cxx b/Code/Common/src/sitkTransform.cxx index 44c5484f2..15058a872 100644 --- a/Code/Common/src/sitkTransform.cxx +++ b/Code/Common/src/sitkTransform.cxx @@ -178,8 +178,8 @@ class HolderCommand ObjectType *Get() {return this->m_Object;} const ObjectType *Get() const {return this->m_Object;} - void Execute(itk::Object*, const itk::EventObject&) {} - void Execute(const itk::Object*, const itk::EventObject&) {} + void Execute(itk::Object*, const itk::EventObject&) SITK_OVERRIDE {} + void Execute(const itk::Object*, const itk::EventObject&) SITK_OVERRIDE {} protected: HolderCommand() : m_Object(NULL) {}; From ad7de48d8424595c00334b3808f09eb256fdaac7 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Tue, 13 Oct 2015 11:03:59 -0400 Subject: [PATCH 092/412] Changed SITK_OVERRIDE to ITK_OVERRIDE The ITK header should use ITK_OVERRIDE, not SITK_OVERRIDE. Change-Id: I73988c7103f71bc91facf8ba529fc8ff09425275 --- Code/BasicFilters/include/itkHashImageFilter.h | 8 ++++---- Code/BasicFilters/include/itkSliceImageFilter.h | 10 +++++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Code/BasicFilters/include/itkHashImageFilter.h b/Code/BasicFilters/include/itkHashImageFilter.h index 9711edcfa..56cd18758 100644 --- a/Code/BasicFilters/include/itkHashImageFilter.h +++ b/Code/BasicFilters/include/itkHashImageFilter.h @@ -83,7 +83,7 @@ class HashImageFilter: * output. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) SITK_OVERRIDE; + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; protected: @@ -91,18 +91,18 @@ class HashImageFilter: // virtual ~HashImageFilter(); // implementation not needed - virtual void PrintSelf(std::ostream & os, Indent indent) const SITK_OVERRIDE; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; // See superclass for doxygen documentation // // This method is to do work after the superclass potential threaded // copy. - void AfterThreadedGenerateData() SITK_OVERRIDE; + void AfterThreadedGenerateData() ITK_OVERRIDE; // See superclass for doxygen documentation // // Override since the filter produces all of its output - void EnlargeOutputRequestedRegion(DataObject *data) SITK_OVERRIDE; + void EnlargeOutputRequestedRegion(DataObject *data) ITK_OVERRIDE; private: HashImageFilter(const Self &); //purposely not implemented diff --git a/Code/BasicFilters/include/itkSliceImageFilter.h b/Code/BasicFilters/include/itkSliceImageFilter.h index cdadefff3..76f4f62af 100644 --- a/Code/BasicFilters/include/itkSliceImageFilter.h +++ b/Code/BasicFilters/include/itkSliceImageFilter.h @@ -116,9 +116,9 @@ class ITK_EXPORT SliceImageFilter: * resolution and with a different pixel spacing than its input * image. * \sa ProcessObject::GenerateOutputInformaton() */ - virtual void GenerateOutputInformation() SITK_OVERRIDE; + virtual void GenerateOutputInformation() ITK_OVERRIDE; - virtual void GenerateInputRequestedRegion() SITK_OVERRIDE; + virtual void GenerateInputRequestedRegion() ITK_OVERRIDE; #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ @@ -132,7 +132,7 @@ class ITK_EXPORT SliceImageFilter: protected: SliceImageFilter(); // ~SliceImageFilter() {} default ok - void PrintSelf(std::ostream & os, Indent indent) const SITK_OVERRIDE; + void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** SliceImageFilter can be implemented as a multithreaded filter. * Therefore, this implementation provides a ThreadedGenerateData() routine @@ -145,9 +145,9 @@ class ITK_EXPORT SliceImageFilter: * \sa ImageToImageFilter::ThreadedGenerateData(), * ImageToImageFilter::GenerateData() */ void ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread, - ThreadIdType threadId) SITK_OVERRIDE; + ThreadIdType threadId) ITK_OVERRIDE; - void VerifyInputInformation() SITK_OVERRIDE; + void VerifyInputInformation() ITK_OVERRIDE; private: SliceImageFilter(const Self &); //purposely not implemented From a27e299fb6287790bb80711d8821127a6420ff5e Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 8 Oct 2015 14:54:10 -0400 Subject: [PATCH 093/412] Adding manual changes to the LandmarkBasedTransformInitializer Change-Id: I9d30c872ad2d39e7da2dd74ddee5ddb5e7cad32b --- ...kLandmarkBasedTransformInitializerFilter.h | 16 ++-- Code/BasicFilters/src/CMakeLists.txt | 1 + ...andmarkBasedTransformInitializerFilter.cxx | 88 ++++++++++++------- Code/Common/include/SimpleITK.h | 1 + Testing/Unit/sitkBasicFiltersTests.cxx | 36 ++++++++ Wrapping/SimpleITK.i | 1 + 6 files changed, 103 insertions(+), 40 deletions(-) diff --git a/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h b/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h index 33fbb8da6..3162f3071 100644 --- a/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h +++ b/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h @@ -69,7 +69,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co ~LandmarkBasedTransformInitializerFilter(); /** Define the pixels types supported by this filter */ - typedef typelist::MakeTypeList >::Type PixelIDTypeList; + typedef typelist::MakeTypeList >::Type PixelIDTypeList; @@ -79,7 +79,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co Self& SetFixedLandmarks ( std::vector FixedLandmarks ) { this->m_FixedLandmarks = FixedLandmarks; return *this; } /** - * Get the shrink factors. + * */ std::vector GetFixedLandmarks() const { return this->m_FixedLandmarks; } @@ -99,7 +99,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co Self& SetLandmarkWeight ( std::vector LandmarkWeight ) { this->m_LandmarkWeight = LandmarkWeight; return *this; } /** - * Get the shrink factors. + * */ std::vector GetLandmarkWeight() const { return this->m_LandmarkWeight; } @@ -129,19 +129,19 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co /** Execute the filter on the input image */ - Image Execute ( const Transform & transform ); + Transform Execute ( const Transform & transform ); /** Execute the filter on the input image with the given parameters */ - Image Execute ( const Transform & transform, std::vector fixedLandmarks, std::vector movingLandmarks, std::vector landmarkWeight, Image referenceImage, unsigned int bSplineNumberOfControlPoints ); + Transform Execute ( const Transform & transform, std::vector fixedLandmarks, std::vector movingLandmarks, std::vector landmarkWeight, Image referenceImage, unsigned int numberOfControlPoints ); private: /** Setup for member function dispatching */ - typedef Image (Self::*MemberFunctionType)( const Transform * transform ); - template Image ExecuteInternal ( const Transform * transform ); + typedef Transform (Self::*MemberFunctionType)( const Transform * transform ); + template Transform ExecuteInternal ( const Transform * transform ); @@ -170,7 +170,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co * * \sa itk::simple::LandmarkBasedTransformInitializerFilter for the object oriented interface */ - SITKBasicFilters_EXPORT Image LandmarkBasedTransformInitializer ( const Transform & transform, std::vector fixedLandmarks = std::vector(), std::vector movingLandmarks = std::vector(), std::vector landmarkWeight = std::vector(), Image referenceImage = Image(), unsigned int bSplineNumberOfControlPoints = 4u ); + SITKBasicFilters_EXPORT Transform LandmarkBasedTransformInitializer ( const Transform & transform, std::vector fixedLandmarks = std::vector(), std::vector movingLandmarks = std::vector(), std::vector landmarkWeight = std::vector(), Image referenceImage = Image(), unsigned int numberOfControlPoints = 4u ); } } diff --git a/Code/BasicFilters/src/CMakeLists.txt b/Code/BasicFilters/src/CMakeLists.txt index 6168071c2..ff67bc5fa 100644 --- a/Code/BasicFilters/src/CMakeLists.txt +++ b/Code/BasicFilters/src/CMakeLists.txt @@ -44,6 +44,7 @@ set ( SimpleITKBasicFilters1Source sitkBSplineTransformInitializerFilter.cxx sitkCenteredTransformInitializerFilter.cxx sitkCenteredVersorTransformInitializerFilter.cxx + sitkLandmarkBasedTransformInitializerFilter.cxx ) add_library ( SimpleITKBasicFilters1 ${SimpleITKBasicFilters1Source} ) diff --git a/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx b/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx index 31d5f1255..91a556ed1 100644 --- a/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx +++ b/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx @@ -31,7 +31,7 @@ #include "itkComposeImageFilter.h" #include "sitkLandmarkBasedTransformInitializerFilter.h" -#include "itkLandmarkBasedTransformInitializerFilter.h" +#include "itkLandmarkBasedTransformInitializer.h" // Additional include files #include "sitkTransform.h" @@ -89,8 +89,8 @@ std::string LandmarkBasedTransformInitializerFilter::ToString() const out << " LandmarkWeight: "; this->ToStringHelper(out, this->m_LandmarkWeight); out << std::endl; - out << " ReferenceImage: "; - this->ToStringHelper(out, this->m_ReferenceImage); + // out << " ReferenceImage: "; + // this->ToStringHelper(out, this->m_ReferenceImage); out << std::endl; out << " BSplineNumberOfControlPoints: "; this->ToStringHelper(out, this->m_BSplineNumberOfControlPoints); @@ -103,24 +103,29 @@ std::string LandmarkBasedTransformInitializerFilter::ToString() const // // Execute // -Image LandmarkBasedTransformInitializerFilter::Execute ( const Transform & transform, std::vector fixedLandmarks, std::vector movingLandmarks, std::vector landmarkWeight, Image referenceImage, unsigned int bSplineNumberOfControlPoints ) +Transform LandmarkBasedTransformInitializerFilter::Execute ( const Transform & transform, std::vector fixedLandmarks, std::vector movingLandmarks, std::vector landmarkWeight, Image referenceImage, unsigned int numberOfControlPoints ) { this->SetFixedLandmarks ( fixedLandmarks ); this->SetMovingLandmarks ( movingLandmarks ); this->SetLandmarkWeight ( landmarkWeight ); this->SetReferenceImage ( referenceImage ); - this->SetBSplineNumberOfControlPoints ( bSplineNumberOfControlPoints ); + this->SetBSplineNumberOfControlPoints ( numberOfControlPoints ); return this->Execute ( transform ); } -Image LandmarkBasedTransformInitializerFilter::Execute ( const Transform & transform ) +Transform LandmarkBasedTransformInitializerFilter::Execute ( const Transform & transform ) { - PixelIDValueEnum type = transform.GetPixelID(); unsigned int dimension = transform.GetDimension(); - return this->m_MemberFactory->GetMemberFunction( type, dimension )( &transform ); + if ( this->m_ReferenceImage.GetSize() != std::vector(this->m_ReferenceImage.GetDimension(), 0u) && + dimension != this->m_ReferenceImage.GetDimension() ) + { + sitkExceptionMacro ( "ReferenceImage for LandmarkBasedTransformInitializerFilter does not match dimension of the transform!" ); + } + + return this->m_MemberFactory->GetMemberFunction( sitkFloat32, dimension )( &transform ); } @@ -139,24 +144,25 @@ namespace { // ExecuteInternal // template -Image LandmarkBasedTransformInitializerFilter::ExecuteInternal ( const Transform * inTransform ) +Transform LandmarkBasedTransformInitializerFilter::ExecuteInternal ( const Transform * inTransform ) { - // Define the input and output image types - typedef TImageType InputImageType; - - - //Define output image type - typedef float OutputImageType; + // Define the input and output image types + typedef itk::ImageBase InputImageType; + const unsigned int Dimension = InputImageType::ImageDimension; - typedef itk::LandmarkBasedTransformInitializer< itk::AffineTransform< double, TImageType::ImageDimension >, TImageType, TImageType> FilterType; + typedef itk::LandmarkBasedTransformInitializer< itk::Transform< double, Dimension, Dimension >, InputImageType, InputImageType> FilterType; // Set up the ITK filter typename FilterType::Pointer filter = FilterType::New(); + // This initializers modifies the input, we copy the transform to + // prevent this change + Transform copyTransform(*inTransform); + copyTransform.SetFixedParameters(copyTransform.GetFixedParameters()); + - assert( inTransform != NULL ); - const typename FilterType::TransformType *itkTx = dynamic_cast(inTransform->GetITKBase() ); + const typename FilterType::TransformType *itkTx = dynamic_cast(copyTransform.GetITKBase()); if ( !itkTx ) { sitkExceptionMacro( "Unexpected error converting transform! Possible miss matching dimensions!" ); @@ -164,27 +170,45 @@ Image LandmarkBasedTransformInitializerFilter::ExecuteInternal ( const Transform else { filter->SetTransform( const_cast(itkTx) ); } - filter->SetFixedLandmarks ( this->m_FixedLandmarks ); - filter->SetMovingLandmarks ( this->m_MovingLandmarks ); - filter->SetLandmarkWeight ( this->m_LandmarkWeight ); - filter->SetReferenceImage ( this->m_ReferenceImage ); - filter->SetBSplineNumberOfControlPoints ( this->m_BSplineNumberOfControlPoints ); - + typedef typename FilterType::LandmarkPointContainer PointContainer; + PointContainer fixedITKPoints; + for( unsigned int i = 0; i < m_FixedLandmarks.size()- Dimension - 1; i += Dimension) + { + typename FilterType::LandmarkPointType pt(&m_FixedLandmarks[i]); + fixedITKPoints.push_back(pt); + } + filter->SetFixedLandmarks(fixedITKPoints); + PointContainer movingITKPoints; + for( unsigned int i = 0; i < m_MovingLandmarks.size()- Dimension - 1; i += Dimension) + { + typename FilterType::LandmarkPointType pt(&m_MovingLandmarks[i]); + movingITKPoints.push_back(pt); + } + filter->SetMovingLandmarks(movingITKPoints); - this->PreUpdate( filter.GetPointer() ); + filter->SetLandmarkWeight ( this->m_LandmarkWeight ); + if ( this->m_ReferenceImage.GetSize() != std::vector(this->m_ReferenceImage.GetDimension(), 0u) ) + { + // Get the pointer to the ITK image contained in image1 + typename InputImageType::ConstPointer referenceImage = this->CastImageToITK( this->m_ReferenceImage ); + ////filter->SetReferenceImage ( referenceImage.GetPointer() ); + } + filter->SetBSplineNumberOfControlPoints ( this->m_BSplineNumberOfControlPoints ); - // Run the ITK filter and return the output as a SimpleITK image - filter->Update(); + if (this->GetDebug()) + { + std::cout << "Executing ITK filter:" << std::endl; + filter->Print(std::cout); + } + filter->InitializeTransform(); - typename FilterType::OutputImageType *itkOutImage = filter->GetOutput(); - this->FixNonZeroIndex( itkOutImage ); - return Image( this->CastITKToImage(itkOutImage) ); + return copyTransform; } @@ -194,10 +218,10 @@ Image LandmarkBasedTransformInitializerFilter::ExecuteInternal ( const Transform // // Function to run the Execute method of this filter // -Image LandmarkBasedTransformInitializer ( const Transform & transform, std::vector fixedLandmarks, std::vector movingLandmarks, std::vector landmarkWeight, Image referenceImage, unsigned int bSplineNumberOfControlPoints ) +Transform LandmarkBasedTransformInitializer ( const Transform & transform, std::vector fixedLandmarks, std::vector movingLandmarks, std::vector landmarkWeight, Image referenceImage, unsigned int numberOfControlPoints ) { LandmarkBasedTransformInitializerFilter filter; - return filter.Execute ( transform, fixedLandmarks, movingLandmarks, landmarkWeight, referenceImage, bSplineNumberOfControlPoints ); + return filter.Execute ( transform, fixedLandmarks, movingLandmarks, landmarkWeight, referenceImage, numberOfControlPoints ); } diff --git a/Code/Common/include/SimpleITK.h b/Code/Common/include/SimpleITK.h index 0f3475628..b8d927228 100644 --- a/Code/Common/include/SimpleITK.h +++ b/Code/Common/include/SimpleITK.h @@ -67,6 +67,7 @@ #include "sitkBSplineTransformInitializerFilter.h" #include "sitkCenteredTransformInitializerFilter.h" #include "sitkCenteredVersorTransformInitializerFilter.h" +#include "sitkLandmarkBasedTransformInitializerFilter.h" #include "sitkCastImageFilter.h" #include "sitkAdditionalProcedures.h" diff --git a/Testing/Unit/sitkBasicFiltersTests.cxx b/Testing/Unit/sitkBasicFiltersTests.cxx index a1947ffa5..d46d648ec 100644 --- a/Testing/Unit/sitkBasicFiltersTests.cxx +++ b/Testing/Unit/sitkBasicFiltersTests.cxx @@ -49,6 +49,7 @@ #include #include #include +#include #include #include @@ -75,6 +76,8 @@ #include "sitkVersorRigid3DTransform.h" #include "sitkSimilarity3DTransform.h" +#include "sitkAffineTransform.h" +#include "sitkEuler2DTransform.h" TEST(BasicFilter,FastSymmetricForcesDemonsRegistrationFilter_ENUMCHECK) { typedef itk::Image ImageType; @@ -622,6 +625,39 @@ TEST(BasicFilters,CenteredVersorTransformInitializer) { +TEST(BasicFilters,LandmarkBasedTransformInitializer) { + namespace sitk = itk::simple; + + sitk::LandmarkBasedTransformInitializerFilter filter; + + EXPECT_EQ ( "LandmarkBasedTransformInitializerFilter", filter.GetName() ); + std::cout << filter.ToString(); + + const double points[8] = { 0.0,0.0, 0.0,1.0, 1.0,0.0, 1.1,1.0 }; + + std::vector fixedPoints(&points[0], &points[8]); + std::vector movingPoints(&points[0], &points[8]); + + movingPoints[7] += .1; + + sitk::Transform tx = sitk::AffineTransform(2); + + filter.SetFixedLandmarks( fixedPoints ); + filter.SetMovingLandmarks( movingPoints ); + sitk::Transform out = filter.Execute( tx ); + + std::cout << out.ToString(); + + + tx = sitk::Euler2DTransform(); + out = filter.Execute( tx ); + + std::cout << out.ToString(); + + +} + + TEST(BasicFilters,Cast_Commands) { // test cast filter with a bunch of commands diff --git a/Wrapping/SimpleITK.i b/Wrapping/SimpleITK.i index 5fa777bba..1681cb9f8 100644 --- a/Wrapping/SimpleITK.i +++ b/Wrapping/SimpleITK.i @@ -177,6 +177,7 @@ namespace std %include "sitkBSplineTransformInitializerFilter.h" %include "sitkCenteredTransformInitializerFilter.h" %include "sitkCenteredVersorTransformInitializerFilter.h" +%include "sitkLandmarkBasedTransformInitializerFilter.h" %include "sitkCastImageFilter.h" %include "sitkAdditionalProcedures.h" From 635ff8743cb598f653949b4aadeb746aa3bfbc75 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 20 Oct 2015 12:59:06 -0400 Subject: [PATCH 094/412] Expanding testing for the LandmarkBasedTransformInitializer Change-Id: I4a7acc726e6533a8c5d20a8c7c60070d7895afde --- Testing/Unit/SimpleITKTestHarness.h | 23 +++++++++++++++ Testing/Unit/sitkBasicFiltersTests.cxx | 40 ++++++++++++++++++-------- 2 files changed, 51 insertions(+), 12 deletions(-) diff --git a/Testing/Unit/SimpleITKTestHarness.h b/Testing/Unit/SimpleITKTestHarness.h index ef8eb2754..83e42c097 100644 --- a/Testing/Unit/SimpleITKTestHarness.h +++ b/Testing/Unit/SimpleITKTestHarness.h @@ -272,6 +272,16 @@ inline std::vector v4(double v1, double v2, double v3, double v4) return temp; } +inline std::vector v6(double v1, double v2, double v3, + double v4, double v5, double v6) +{ + std::vector temp(6); + temp[0]=v1;temp[1]=v2;temp[2]=v3; + temp[3]=v4;temp[4]=v5;temp[5]=v6; + return temp; +} + + inline std::vector v9(double v1, double v2, double v3, double v4, double v5, double v6, double v7, double v8, double v9) @@ -283,6 +293,19 @@ inline std::vector v9(double v1, double v2, double v3, return temp; } +inline std::vector v12(double v1, double v2, double v3, + double v4, double v5, double v6, + double v7, double v8, double v9, + double v10, double v11, double v12) +{ + std::vector temp(12); + temp[0]=v1;temp[1]=v2;temp[2]=v3; + temp[3]=v4;temp[4]=v5;temp[5]=v6; + temp[6]=v7;temp[7]=v8;temp[8]=v9; + temp[9]=v10;temp[10]=v11;temp[11]=v12; + return temp; +} + } diff --git a/Testing/Unit/sitkBasicFiltersTests.cxx b/Testing/Unit/sitkBasicFiltersTests.cxx index d46d648ec..9e6e22be1 100644 --- a/Testing/Unit/sitkBasicFiltersTests.cxx +++ b/Testing/Unit/sitkBasicFiltersTests.cxx @@ -78,6 +78,9 @@ #include "sitkSimilarity3DTransform.h" #include "sitkAffineTransform.h" #include "sitkEuler2DTransform.h" +#include "sitkSimilarity2DTransform.h" +#include "sitkVersorTransform.h" +#include "sitkScaleVersor3DTransform.h" TEST(BasicFilter,FastSymmetricForcesDemonsRegistrationFilter_ENUMCHECK) { typedef itk::Image ImageType; @@ -630,30 +633,43 @@ TEST(BasicFilters,LandmarkBasedTransformInitializer) { sitk::LandmarkBasedTransformInitializerFilter filter; - EXPECT_EQ ( "LandmarkBasedTransformInitializerFilter", filter.GetName() ); - std::cout << filter.ToString(); - const double points[8] = { 0.0,0.0, 0.0,1.0, 1.0,0.0, 1.1,1.0 }; + const double points2d[] = { 0.0,0.0, 1.0,1.0, 1.0,0.0, 1.1,1.0, 2.34, 10.98}; - std::vector fixedPoints(&points[0], &points[8]); - std::vector movingPoints(&points[0], &points[8]); + std::vector fixedPoints(&points2d[0], &points2d[10]); + std::vector movingPoints(&points2d[0], &points2d[10]); - movingPoints[7] += .1; - sitk::Transform tx = sitk::AffineTransform(2); + sitk::Transform out; filter.SetFixedLandmarks( fixedPoints ); filter.SetMovingLandmarks( movingPoints ); - sitk::Transform out = filter.Execute( tx ); - std::cout << out.ToString(); + EXPECT_EQ ( "LandmarkBasedTransformInitializerFilter", filter.GetName() ); + + out = filter.Execute( sitk::Euler2DTransform() ); + EXPECT_VECTOR_DOUBLE_NEAR(v3(0.0, 0.0, 0.0), out.GetParameters(), 1e-25); + + out = filter.Execute( sitk::Similarity2DTransform() ); + EXPECT_VECTOR_DOUBLE_NEAR(v4(1.0, 0.0, 0.0, 0.0), out.GetParameters(), 1e-25); + + + EXPECT_ANY_THROW( filter.Execute( sitk::VersorTransform() ) ); + + out = filter.Execute( sitk::VersorRigid3DTransform() ); + EXPECT_VECTOR_DOUBLE_NEAR(v6(0.0, 0.0, 0.0, 0.0, 0.0, 0.0), out.GetParameters(), 1e-25); + + out = filter.Execute( sitk::ScaleVersor3DTransform() ); + EXPECT_VECTOR_DOUBLE_NEAR(v9(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0), out.GetParameters(), 1e-25); + + + out = filter.Execute( sitk::AffineTransform(2) ); + EXPECT_VECTOR_DOUBLE_NEAR(v6(1.0, 0.0, 0.0, 1.0, 0.0, 0.0), out.GetParameters(), 1e-15); - tx = sitk::Euler2DTransform(); - out = filter.Execute( tx ); - std::cout << out.ToString(); + out = filter.Execute( sitk::AffineTransform(3) ); } From a7c21e232ced0956d935ff7ff6d54248b9856a3a Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 23 Oct 2015 09:38:22 -0400 Subject: [PATCH 095/412] Updating ITK Superbuild version This patch includes fixes to the convergence monitor classes to fix some failing tests. Change-Id: Ie918469447354540c3cb67f00f85406e0880055d --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index bbf2332af..6cf13566f 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY git://itk.org/ITK.git) # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG 8c446afdd2781c0c54a2d9b115528c6d01d93abb) +set(ITK_TAG_COMMAND GIT_TAG 189385780861b4a1ced5702a13f796d355255577) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 2f82ded7fe65800557c6edb4b43e8fc0e5a93cf7 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 26 Oct 2015 15:08:22 -0400 Subject: [PATCH 096/412] BUG: Update ITK_DIR to match version Change-Id: I7605935008c08184758566bd3ecfacc169c9a6cc --- SuperBuild/External_ITK.cmake | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 6cf13566f..1fde644e5 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -90,5 +90,5 @@ ExternalProject_Add(${proj} ExternalProject_Get_Property(ITK install_dir) -set(ITK_DIR "${install_dir}/lib/cmake/ITK-4.8" ) -set(WrapITK_DIR "${install_dir}/lib/cmake/ITK-4.8/WrapITK") +set(ITK_DIR "${install_dir}/lib/cmake/ITK-4.9" ) +set(WrapITK_DIR "${install_dir}/lib/cmake/ITK-4.9/WrapITK") From 2fc59f90997cb3fbd76f5d514382338c84541a6c Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 27 Oct 2015 11:01:32 -0400 Subject: [PATCH 097/412] Moving Python Wrapping to sub-directory Change-Id: I3263abdc77cb7175bfb324c3453a940af0aa779b --- Wrapping/CMakeLists.txt | 147 +----------------- Wrapping/Python/CMakeLists.txt | 144 +++++++++++++++++ .../Packaging}/__init__.py | 0 .../Packaging}/ez_setup.py | 0 .../Packaging}/setup.py.in | 0 .../Packaging}/setupegg.py | 0 Wrapping/{ => Python}/Python.i | 0 Wrapping/{ => Python}/PythonDocstrings.i | 0 .../PythonVirtualEnvInstall.cmake.in | 4 +- Wrapping/Python/dist/CMakeLists.txt | 25 +++ Wrapping/{ => Python}/dist/install_wheel.py | 0 .../{ => Python}/sitkNumpyArrayConversion.cxx | 0 Wrapping/{ => Python}/sitkPyCommand.cxx | 0 Wrapping/{ => Python}/sitkPyCommand.h | 0 Wrapping/SimpleITK.i | 2 + Wrapping/dist/CMakeLists.txt | 29 ---- 16 files changed, 180 insertions(+), 171 deletions(-) create mode 100644 Wrapping/Python/CMakeLists.txt rename Wrapping/{PythonPackage => Python/Packaging}/__init__.py (100%) rename Wrapping/{PythonPackage => Python/Packaging}/ez_setup.py (100%) rename Wrapping/{PythonPackage => Python/Packaging}/setup.py.in (100%) rename Wrapping/{PythonPackage => Python/Packaging}/setupegg.py (100%) rename Wrapping/{ => Python}/Python.i (100%) rename Wrapping/{ => Python}/PythonDocstrings.i (100%) rename Wrapping/{ => Python}/PythonVirtualEnvInstall.cmake.in (97%) create mode 100644 Wrapping/Python/dist/CMakeLists.txt rename Wrapping/{ => Python}/dist/install_wheel.py (100%) rename Wrapping/{ => Python}/sitkNumpyArrayConversion.cxx (100%) rename Wrapping/{ => Python}/sitkPyCommand.cxx (100%) rename Wrapping/{ => Python}/sitkPyCommand.h (100%) diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index 45fc79b59..63e49cd25 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -40,6 +40,12 @@ if ( WRAP_LUA OR WRAP_PYTHON OR WRAP_JAVA OR WRAP_CSHARP OR WRAP_TCL OR WRAP_R O endif() + +# A general packaging target, not built by default, to build packages for each +# language. This should depend on all language specific targets. +add_custom_target( dist cmake -E echo "Finished generating wrapped packages for distribution..." ) + + # # lua SWIG configuration # @@ -71,146 +77,7 @@ endif() # python SWIG configuration # if ( WRAP_PYTHON ) - find_package ( PythonLibs REQUIRED ) - find_package ( PythonInterp REQUIRED ) - include_directories ( ${PYTHON_INCLUDE_DIR} ${SimpleITK_SOURCE_DIR}/Wrapping ) - - option ( SimpleITK_PYTHON_THREADS "Enable threaded python usage by unlocking the GIL." ON ) - mark_as_advanced( SimpleITK_PYTHON_THREADS ) - option ( SimpleITK_PYTHON_WHEEL "Add building of python wheels to the dist target." OFF ) - mark_as_advanced( SimpleITK_PYTHON_WHEEL ) - - - # Run swig - set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_GLOBAL_FLAGS} -features autodoc=1 -keyword ) - if( SimpleITK_PYTHON_THREADS ) - set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_FLAGS} -threads) - endif() - set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) - set(SWIG_MODULE_SimpleITK_EXTRA_DEPS ${SWIG_EXTRA_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/Python.i ) - SWIG_add_module ( SimpleITK python - SimpleITK.i - sitkPyCommand.cxx ) - SWIG_link_libraries ( SimpleITK ${SimpleITK_LIBRARIES} ${PYTHON_LIBRARIES}) - set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/SimpleITKPYTHON_wrap.cxx PROPERTIES COMPILE_FLAGS "-w") - sitk_strip_target( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ) - - set(SWIG_MODULE_SimpleITKPython_TARGET_NAME "${SWIG_MODULE_SimpleITK_TARGET_NAME}") - - # Installation - set( SIMPLEITK_PYTHON_PACKAGE_DIR "${SimpleITK_BINARY_DIR}/Wrapping" ) - file( TO_NATIVE_PATH "${SIMPLEITK_PYTHON_PACKAGE_DIR}" SIMPLEITK_PYTHON_PACKAGE_DIR ) - get_target_property( SWIG_MODULE_SimpleITKPython_TARGET_LOCATION ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} OUTPUT_NAME ) - add_custom_command( - TARGET ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy "$" "${CMAKE_CURRENT_BINARY_DIR}" - ) - get_target_property( SIMPLEITK_RELATIVE_BINARY_MODULE ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} LOCATION ) - get_filename_component( SIMPLEITK_RELATIVE_BINARY_MODULE "${SIMPLEITK_RELATIVE_BINARY_MODULE}" NAME ) - - - if ( SimpleITK_DOC_FILES ) - # create a python list for the import documents to include in - # packaging - - # This string is targed for setup.py. It will be passed through - # the build-time configuration script and as a command line - # argument. This sequence is having portability issues with - # quote. So Windows needs separate handling from Unix-like - # platforms. - if( WIN32 ) - set( _q "'" ) - else() - set( _q "\\'") - endif() - - # specially handle the first element - list( GET SimpleITK_DOC_FILES 0 d ) - file(TO_NATIVE_PATH "${d}" d ) - set( SimpleITK_DOC_FILES_AS_LIST "[r${_q}${d}${_q}") - set( _doc_list "${SimpleITK_DOC_FILES}" ) - list( REMOVE_AT _doc_list 0 ) - - foreach( d ${_doc_list} ) - file(TO_NATIVE_PATH "${d}" d ) - set( SimpleITK_DOC_FILES_AS_LIST "${SimpleITK_DOC_FILES_AS_LIST},r${_q}${d}${_q}") - endforeach() - set( SimpleITK_DOC_FILES_AS_LIST "${SimpleITK_DOC_FILES_AS_LIST}]") - - endif() - - include( sitkConfigureFileBuildtime ) - configure_file_buildtime( "${CMAKE_CURRENT_SOURCE_DIR}/PythonPackage/setup.py.in" - "${CMAKE_CURRENT_BINARY_DIR}/PythonPackage/setup.py" ) - - configure_file( - "${CMAKE_CURRENT_SOURCE_DIR}/PythonPackage/setupegg.py" - "${CMAKE_CURRENT_BINARY_DIR}/PythonPackage/setupegg.py" - COPYONLY ) - - configure_file( - "${CMAKE_CURRENT_SOURCE_DIR}/PythonPackage/ez_setup.py" - "${CMAKE_CURRENT_BINARY_DIR}/PythonPackage/ez_setup.py" - COPYONLY ) - - configure_file( - "${CMAKE_CURRENT_SOURCE_DIR}/PythonPackage/__init__.py" - "${CMAKE_CURRENT_BINARY_DIR}/__init__.py" - COPYONLY ) - - option(SITK_PYTHON_USE_VIRTUALENV "Create a Python Virtual Environment for testing." ON) - mark_as_advanced(SITK_PYTHON_USE_VIRTUALENV) - - if (SITK_PYTHON_USE_VIRTUALENV) - sitk_enforce_forbid_downloads( SITK_PYTHON_USE_VIRTUALENV ) - # - # Setup Python Virtual Enviroment for testing and packaging - # - set( PythonVirtualenvHome "${SimpleITK_BINARY_DIR}/Testing/Installation/PythonVirtualenv" ) - - # virtualenv places the python executable in different - # locations. Also note than on windows installations where python is - # installed only for a single user the may be a missing dll issue. - if( WIN32 ) - set( VIRTUAL_PYTHON_EXECUTABLE - "${PythonVirtualenvHome}/Scripts/python") - else( ) - set( VIRTUAL_PYTHON_EXECUTABLE "${PythonVirtualenvHome}/bin/python" ) - endif() - set(TEST_PYTHON_EXECUTABLE "${VIRTUAL_PYTHON_EXECUTABLE}" - CACHE INTERNAL "Python executable for testing." FORCE ) - - # configure a scripts which creates the virtualenv and installs numpy - configure_file( - "${CMAKE_CURRENT_SOURCE_DIR}/PythonVirtualEnvInstall.cmake.in" - "${CMAKE_CURRENT_BINARY_DIR}/PythonVirtualEnvInstall.cmake" - @ONLY ) - - set( PythonVirtualEnv_ALL "" ) - if ( BUILD_TESTING ) - set( PythonVirtualEnv_ALL "ALL" ) - endif() - - add_custom_target( PythonVirtualEnv ${PythonVirtualEnv_ALL} - DEPENDS "${VIRTUAL_PYTHON_EXECUTABLE}" - SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/PythonVirtualEnvInstall.cmake.in ) - - add_custom_command( OUTPUT "${VIRTUAL_PYTHON_EXECUTABLE}" - COMMAND ${CMAKE_COMMAND} -P "${CMAKE_CURRENT_BINARY_DIR}/PythonVirtualEnvInstall.cmake" - DEPENDS - "${SWIG_MODULE_SimpleITKPython_TARGET_NAME}" - "${CMAKE_CURRENT_BINARY_DIR}/PythonVirtualEnvInstall.cmake" - ConfigureFileBuildtime - "${CMAKE_CURRENT_BINARY_DIR}/PythonPackage/ez_setup.py" - COMMENT "Creating python virtual enviroment..." - ) - else() - set(TEST_PYTHON_EXECUTABLE "${PYTHON_EXECUTABLE}" - CACHE INTERNAL "Python executable for testing." FORCE ) - endif() - + add_subdirectory ( Python ) endif() # diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt new file mode 100644 index 000000000..25ada2d51 --- /dev/null +++ b/Wrapping/Python/CMakeLists.txt @@ -0,0 +1,144 @@ +find_package ( PythonLibs REQUIRED ) +find_package ( PythonInterp REQUIRED ) +include_directories ( ${PYTHON_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ) + +option ( SimpleITK_PYTHON_THREADS "Enable threaded python usage by unlocking the GIL." ON ) +mark_as_advanced( SimpleITK_PYTHON_THREADS ) +option ( SimpleITK_PYTHON_WHEEL "Add building of python wheels to the dist target." OFF ) +mark_as_advanced( SimpleITK_PYTHON_WHEEL ) + + +set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) + +# Run swig +set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_GLOBAL_FLAGS} -I${CMAKE_CURRENT_SOURCE_DIR} -features autodoc=1 -keyword ) +if( SimpleITK_PYTHON_THREADS ) + set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_FLAGS} -threads) +endif() +set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) +set(SWIG_MODULE_SimpleITK_EXTRA_DEPS ${SWIG_EXTRA_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/Python.i ) +SWIG_add_module ( SimpleITK python + ../SimpleITK.i + sitkPyCommand.cxx ) +SWIG_link_libraries ( SimpleITK ${SimpleITK_LIBRARIES} ${PYTHON_LIBRARIES}) +set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/SimpleITKPYTHON_wrap.cxx PROPERTIES COMPILE_FLAGS "-w") +sitk_strip_target( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ) + +set(SWIG_MODULE_SimpleITKPython_TARGET_NAME "${SWIG_MODULE_SimpleITK_TARGET_NAME}") + +# Installation +set( SIMPLEITK_PYTHON_PACKAGE_DIR "${SimpleITK_BINARY_DIR}/Wrapping/Python" ) +file( TO_NATIVE_PATH "${SIMPLEITK_PYTHON_PACKAGE_DIR}" SIMPLEITK_PYTHON_PACKAGE_DIR ) +get_target_property( SWIG_MODULE_SimpleITKPython_TARGET_LOCATION ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} OUTPUT_NAME ) +add_custom_command( + TARGET ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy "$" "${CMAKE_CURRENT_BINARY_DIR}" + ) +get_target_property( SIMPLEITK_RELATIVE_BINARY_MODULE ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} LOCATION ) +get_filename_component( SIMPLEITK_RELATIVE_BINARY_MODULE "${SIMPLEITK_RELATIVE_BINARY_MODULE}" NAME ) + + +if ( SimpleITK_DOC_FILES ) + # create a python list for the import documents to include in + # packaging + + # This string is targed for setup.py. It will be passed through + # the build-time configuration script and as a command line + # argument. This sequence is having portability issues with + # quote. So Windows needs separate handling from Unix-like + # platforms. + if( WIN32 ) + set( _q "'" ) + else() + set( _q "\\'") + endif() + + # specially handle the first element + list( GET SimpleITK_DOC_FILES 0 d ) + file(TO_NATIVE_PATH "${d}" d ) + set( SimpleITK_DOC_FILES_AS_LIST "[r${_q}${d}${_q}") + set( _doc_list "${SimpleITK_DOC_FILES}" ) + list( REMOVE_AT _doc_list 0 ) + + foreach( d ${_doc_list} ) + file(TO_NATIVE_PATH "${d}" d ) + set( SimpleITK_DOC_FILES_AS_LIST "${SimpleITK_DOC_FILES_AS_LIST},r${_q}${d}${_q}") + endforeach() + set( SimpleITK_DOC_FILES_AS_LIST "${SimpleITK_DOC_FILES_AS_LIST}]") + +endif() + +include( sitkConfigureFileBuildtime ) +configure_file_buildtime( "${CMAKE_CURRENT_SOURCE_DIR}/Packaging/setup.py.in" + "${CMAKE_CURRENT_BINARY_DIR}/Packaging/setup.py" ) + +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/Packaging/setupegg.py" + "${CMAKE_CURRENT_BINARY_DIR}/Packaging/setupegg.py" + COPYONLY ) + +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/Packaging/ez_setup.py" + "${CMAKE_CURRENT_BINARY_DIR}/Packaging/ez_setup.py" + COPYONLY ) + +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/Packaging/__init__.py" + "${CMAKE_CURRENT_BINARY_DIR}/__init__.py" + COPYONLY ) + +option(SITK_PYTHON_USE_VIRTUALENV "Create a Python Virtual Environment for testing." ON) +mark_as_advanced(SITK_PYTHON_USE_VIRTUALENV) + +if (SITK_PYTHON_USE_VIRTUALENV) + sitk_enforce_forbid_downloads( SITK_PYTHON_USE_VIRTUALENV ) + # + # Setup Python Virtual Enviroment for testing and packaging + # + set( PythonVirtualenvHome "${SimpleITK_BINARY_DIR}/Testing/Installation/PythonVirtualenv" ) + + # virtualenv places the python executable in different + # locations. Also note than on windows installations where python is + # installed only for a single user the may be a missing dll issue. + if( WIN32 ) + set( VIRTUAL_PYTHON_EXECUTABLE + "${PythonVirtualenvHome}/Scripts/python") + else( ) + set( VIRTUAL_PYTHON_EXECUTABLE "${PythonVirtualenvHome}/bin/python" ) + endif() + set(TEST_PYTHON_EXECUTABLE "${VIRTUAL_PYTHON_EXECUTABLE}" + CACHE INTERNAL "Python executable for testing." FORCE ) + + # configure a scripts which creates the virtualenv and installs numpy + configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/PythonVirtualEnvInstall.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/PythonVirtualEnvInstall.cmake" + @ONLY ) + + set( PythonVirtualEnv_ALL "" ) + if ( BUILD_TESTING ) + set( PythonVirtualEnv_ALL "ALL" ) + endif() + + add_custom_target( PythonVirtualEnv ${PythonVirtualEnv_ALL} + DEPENDS "${VIRTUAL_PYTHON_EXECUTABLE}" + SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/PythonVirtualEnvInstall.cmake.in ) + + add_custom_command( OUTPUT "${VIRTUAL_PYTHON_EXECUTABLE}" + COMMAND ${CMAKE_COMMAND} -P "${CMAKE_CURRENT_BINARY_DIR}/PythonVirtualEnvInstall.cmake" + DEPENDS + "${SWIG_MODULE_SimpleITKPython_TARGET_NAME}" + "${CMAKE_CURRENT_BINARY_DIR}/PythonVirtualEnvInstall.cmake" + ConfigureFileBuildtime + "${CMAKE_CURRENT_BINARY_DIR}/Packaging/ez_setup.py" + COMMENT "Creating python virtual enviroment..." + ) +else() + set(TEST_PYTHON_EXECUTABLE "${PYTHON_EXECUTABLE}" + CACHE INTERNAL "Python executable for testing." FORCE ) +endif() + +# Packaging for distribution +add_subdirectory(dist) diff --git a/Wrapping/PythonPackage/__init__.py b/Wrapping/Python/Packaging/__init__.py similarity index 100% rename from Wrapping/PythonPackage/__init__.py rename to Wrapping/Python/Packaging/__init__.py diff --git a/Wrapping/PythonPackage/ez_setup.py b/Wrapping/Python/Packaging/ez_setup.py similarity index 100% rename from Wrapping/PythonPackage/ez_setup.py rename to Wrapping/Python/Packaging/ez_setup.py diff --git a/Wrapping/PythonPackage/setup.py.in b/Wrapping/Python/Packaging/setup.py.in similarity index 100% rename from Wrapping/PythonPackage/setup.py.in rename to Wrapping/Python/Packaging/setup.py.in diff --git a/Wrapping/PythonPackage/setupegg.py b/Wrapping/Python/Packaging/setupegg.py similarity index 100% rename from Wrapping/PythonPackage/setupegg.py rename to Wrapping/Python/Packaging/setupegg.py diff --git a/Wrapping/Python.i b/Wrapping/Python/Python.i similarity index 100% rename from Wrapping/Python.i rename to Wrapping/Python/Python.i diff --git a/Wrapping/PythonDocstrings.i b/Wrapping/Python/PythonDocstrings.i similarity index 100% rename from Wrapping/PythonDocstrings.i rename to Wrapping/Python/PythonDocstrings.i diff --git a/Wrapping/PythonVirtualEnvInstall.cmake.in b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in similarity index 97% rename from Wrapping/PythonVirtualEnvInstall.cmake.in rename to Wrapping/Python/PythonVirtualEnvInstall.cmake.in index a75d2ab52..b441aa8f6 100644 --- a/Wrapping/PythonVirtualEnvInstall.cmake.in +++ b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in @@ -21,7 +21,7 @@ endif() message(STATUS "Installing Python Package: SimpleITK") execute_process( - COMMAND "@VIRTUAL_PYTHON_EXECUTABLE@" "@CMAKE_CURRENT_BINARY_DIR@/PythonPackage/setup.py" install + COMMAND "@VIRTUAL_PYTHON_EXECUTABLE@" "@CMAKE_CURRENT_BINARY_DIR@/Packaging/setup.py" install RESULT_VARIABLE failed ERROR_VARIABLE error ) @@ -43,7 +43,7 @@ if not(sys.modules.get(\"wheel\")): execute_process( COMMAND @VIRTUAL_PYTHON_EXECUTABLE@ -c "${install_wheel_script}" - WORKING_DIRECTORY "PythonPackage" + WORKING_DIRECTORY "Packaging" ERROR_VARIABLE error RESULT_VARIABLE failed ) diff --git a/Wrapping/Python/dist/CMakeLists.txt b/Wrapping/Python/dist/CMakeLists.txt new file mode 100644 index 000000000..50a43019c --- /dev/null +++ b/Wrapping/Python/dist/CMakeLists.txt @@ -0,0 +1,25 @@ +# +# Packaging +# + +if( WRAP_PYTHON ) + + set(bdist_commands "bdist_egg") + if( SimpleITK_PYTHON_WHEEL ) + set(bdist_commands ${bdist_commands} bdist_wheel) + endif() + + if(SITK_PYTHON_USE_VIRTUALENV) + add_custom_target( dist.Python + ${VIRTUAL_PYTHON_EXECUTABLE} ${SimpleITK_BINARY_DIR}/Wrapping/Python/Packaging/setupegg.py ${bdist_commands} + WORKING_DIRECTORY ${SimpleITK_BINARY_DIR}/Wrapping/Python + DEPENDS ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} + COMMENT "Creating Python binary distribution" ) + + add_dependencies( dist.Python PythonVirtualEnv) + add_dependencies( dist dist.Python ) + elseif() + message( STATUS "Not creating dist.Python target since SITK_FORBID_DOWNLOADS is enabled" ) + endif() + +endif() diff --git a/Wrapping/dist/install_wheel.py b/Wrapping/Python/dist/install_wheel.py similarity index 100% rename from Wrapping/dist/install_wheel.py rename to Wrapping/Python/dist/install_wheel.py diff --git a/Wrapping/sitkNumpyArrayConversion.cxx b/Wrapping/Python/sitkNumpyArrayConversion.cxx similarity index 100% rename from Wrapping/sitkNumpyArrayConversion.cxx rename to Wrapping/Python/sitkNumpyArrayConversion.cxx diff --git a/Wrapping/sitkPyCommand.cxx b/Wrapping/Python/sitkPyCommand.cxx similarity index 100% rename from Wrapping/sitkPyCommand.cxx rename to Wrapping/Python/sitkPyCommand.cxx diff --git a/Wrapping/sitkPyCommand.h b/Wrapping/Python/sitkPyCommand.h similarity index 100% rename from Wrapping/sitkPyCommand.h rename to Wrapping/Python/sitkPyCommand.h diff --git a/Wrapping/SimpleITK.i b/Wrapping/SimpleITK.i index 1681cb9f8..62a8b333e 100644 --- a/Wrapping/SimpleITK.i +++ b/Wrapping/SimpleITK.i @@ -83,7 +83,9 @@ %include CSharp.i %include Java.i %include Tcl.i +#if SWIGPYTHON %include Python.i +#endif %include Lua.i %include R.i %include Ruby.i diff --git a/Wrapping/dist/CMakeLists.txt b/Wrapping/dist/CMakeLists.txt index e2c44e252..180ee6674 100644 --- a/Wrapping/dist/CMakeLists.txt +++ b/Wrapping/dist/CMakeLists.txt @@ -1,32 +1,3 @@ -# -# Packaging -# - -# A general packaging target, not built by default, to build packages for each -# language. This should depend on all language specific targets. -add_custom_target( dist cmake -E echo "Finished generating wrapped packages for distribution..." ) - -if( WRAP_PYTHON ) - - set(bdist_commands "bdist_egg") - if( SimpleITK_PYTHON_WHEEL ) - set(bdist_commands ${bdist_commands} bdist_wheel) - endif() - - if(SITK_PYTHON_USE_VIRTUALENV) - add_custom_target( dist.Python - ${VIRTUAL_PYTHON_EXECUTABLE} ${SimpleITK_BINARY_DIR}/Wrapping/PythonPackage/setupegg.py ${bdist_commands} - WORKING_DIRECTORY ${SimpleITK_BINARY_DIR}/Wrapping - DEPENDS ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} - COMMENT "Creating Python binary distribution" ) - - add_dependencies( dist.Python PythonVirtualEnv) - add_dependencies( dist dist.Python ) - elseif() - message( STATUS "Not creating dist.Python target since SITK_FORBID_DOWNLOADS is enabled" ) - endif() - -endif() # # JAVA Packaging From 571d4ae24b523766b7eaa3176576f351bc0da105 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 28 Oct 2015 10:00:24 -0400 Subject: [PATCH 098/412] Moving Ruby wrapping to sub-directory Change-Id: Ia8447d87000ccad54a6299697972a4e95e99ff2a --- Wrapping/CMakeLists.txt | 15 +-------------- Wrapping/Ruby/CMakeLists.txt | 16 ++++++++++++++++ Wrapping/{ => Ruby}/Ruby.i | 0 Wrapping/SimpleITK.i | 4 +++- 4 files changed, 20 insertions(+), 15 deletions(-) create mode 100644 Wrapping/Ruby/CMakeLists.txt rename Wrapping/{ => Ruby}/Ruby.i (100%) diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index 63e49cd25..9bc141af7 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -84,20 +84,7 @@ endif() # ruby SWIG configuration # if ( WRAP_RUBY ) - find_package ( Ruby REQUIRED ) - include_directories ( ${RUBY_INCLUDE_DIRS} ) - - # Run swig - set(CMAKE_SWIG_FLAGS -autorename -module simpleitk ${CMAKE_SWIG_GLOBAL_FLAGS}) - set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) - set(SWIG_MODULE_simpleitk_EXTRA_DEPS ${SWIG_EXTRA_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/Ruby.i) - - SWIG_add_module ( simpleitk ruby SimpleITK.i SimpleITKRUBY_wrap.cxx ) - SWIG_link_libraries ( simpleitk ${SimpleITK_LIBRARIES} ${RUBY_LIBRARY}) - set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/SimpleITKRUBY_wrap.cxx PROPERTIES COMPILE_FLAGS "-w") - sitk_strip_target( ${SWIG_MODULE_simpleitk_TARGET_NAME} ) - + add_subdirectory ( Ruby ) endif() # diff --git a/Wrapping/Ruby/CMakeLists.txt b/Wrapping/Ruby/CMakeLists.txt new file mode 100644 index 000000000..4a8d69d3f --- /dev/null +++ b/Wrapping/Ruby/CMakeLists.txt @@ -0,0 +1,16 @@ + +find_package ( Ruby REQUIRED ) +include_directories ( ${RUBY_INCLUDE_DIRS} ) + +set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) + +# Run swig +set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} -autorename -module simpleitk ${CMAKE_SWIG_GLOBAL_FLAGS}) +set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) +set(SWIG_MODULE_simpleitk_EXTRA_DEPS ${SWIG_EXTRA_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/Ruby.i) + +SWIG_add_module ( simpleitk ruby ../SimpleITK.i ) +SWIG_link_libraries ( simpleitk ${SimpleITK_LIBRARIES} ${RUBY_LIBRARY}) +set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/SimpleITKRUBY_wrap.cxx PROPERTIES COMPILE_FLAGS "-w") +sitk_strip_target( ${SWIG_MODULE_simpleitk_TARGET_NAME} ) diff --git a/Wrapping/Ruby.i b/Wrapping/Ruby/Ruby.i similarity index 100% rename from Wrapping/Ruby.i rename to Wrapping/Ruby/Ruby.i diff --git a/Wrapping/SimpleITK.i b/Wrapping/SimpleITK.i index 62a8b333e..d06c02312 100644 --- a/Wrapping/SimpleITK.i +++ b/Wrapping/SimpleITK.i @@ -88,7 +88,9 @@ #endif %include Lua.i %include R.i -%include Ruby.i +#if SWIGRUBY + %include Ruby.i +#endif // Help SWIG handle std vectors namespace std From 9942b99062c3d603ac5848117d62b96337a2d5ad Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 28 Oct 2015 11:13:54 -0400 Subject: [PATCH 099/412] Moving Tcl and Lua wrapping for sub-directories Change-Id: I275259579d210a35f04127ba12f7cdea609755e6 --- Wrapping/CMakeLists.txt | 44 ++----------------------- Wrapping/Lua/CMakeLists.txt | 22 +++++++++++++ Wrapping/{ => Lua}/Lua.i | 1 - Wrapping/{ => Lua}/SimpleITKLuaMain.cxx | 2 -- Wrapping/SimpleITK.i | 4 +++ Wrapping/Tcl/CMakeLists.txt | 23 +++++++++++++ Wrapping/{ => Tcl}/Tcl.i | 0 7 files changed, 51 insertions(+), 45 deletions(-) create mode 100644 Wrapping/Lua/CMakeLists.txt rename Wrapping/{ => Lua}/Lua.i (99%) rename Wrapping/{ => Lua}/SimpleITKLuaMain.cxx (99%) create mode 100644 Wrapping/Tcl/CMakeLists.txt rename Wrapping/{ => Tcl}/Tcl.i (100%) diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index 9bc141af7..a366604a5 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -50,27 +50,7 @@ add_custom_target( dist cmake -E echo "Finished generating wrapped packages for # lua SWIG configuration # if ( WRAP_LUA ) - - if (CMAKE_VERSION VERSION_LESS "3") - find_package ( Lua51 REQUIRED ) - else() - find_package ( Lua REQUIRED ) - endif() - include_directories ( ${LUA_INCLUDE_DIR} ) - - # Run swig - set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_GLOBAL_FLAGS}) - set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) - set(SWIG_MODULE_SimpleITKLua_EXTRA_DEPS ${SWIG_EXTRA_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/Lua.i ) - SWIG_module_initialize ( SimpleITKLua lua ) - SWIG_add_source_to_module ( SimpleITKLua swig_generated_source SimpleITK.i ${SWIG_EXTRA_DEPS} ) - set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/SimpleITKLUA_wrap.cxx PROPERTIES COMPILE_FLAGS "-w" ) - - add_executable ( SimpleITKLua SimpleITKLuaMain.cxx SimpleITKLUA_wrap.cxx ) - target_link_libraries ( SimpleITKLua ${SimpleITK_LIBRARIES} ${LUA_LIBRARIES} ${LUA_ADDITIONAL_LIBRARIES} ) - sitk_strip_target( SimpleITKLua ) - + add_subdirectory ( Lua ) endif() # @@ -235,27 +215,7 @@ endif() # TCL SWIG configuration # if ( WRAP_TCL ) - find_package ( TCL REQUIRED ) - include_directories ( ${TCL_INCLUDE_PATH} ) - - # Run swig - set(CMAKE_SWIG_FLAGS "-nosafe" ${CMAKE_SWIG_GLOBAL_FLAGS}) - set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) - set(SWIG_MODULE_SimpleITKTCL_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/Tcl.i ) - set(SWIG_MODULE_SimpleITKTcl_EXTRA_DEPS ${SWIG_MODULE_SimpleITKTCL_EXTRA_DEPS}) -# SWIG_add_module ( SimpleITKTcl tcl SimpleITK.i SimpleITKTCL_wrap.cxx ) -# SWIG_link_libraries ( SimpleITKTcl ${SimpleITK_LIBRARIES} ${TCL_LIBRARY}) -# set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/SimpleITKTCL_wrap.cxx PROPERTIES COMPILE_FLAGS "-w") -# add_executable ( SimpleITKTclsh SimpleITKTCL_wrap.cxx ) -# target_link_libraries ( SimpleITKTclsh ${SimpleITK_LIBRARIES} ${TCL_LIBRARY}) - - SWIG_module_initialize ( SimpleITKTCL tcl ) - SWIG_add_source_to_module ( SimpleITKTCL swig_generated_source SimpleITK.i ${SWIG_EXTRA_DEPS} ) - set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/SimpleITKTCL_wrap.cxx PROPERTIES COMPILE_FLAGS "-w" ) - add_executable ( SimpleITKTclsh SimpleITKTCL_wrap.cxx ) - target_link_libraries ( SimpleITKTclsh ${SimpleITK_LIBRARIES} ${TCL_LIBRARY} ) - sitk_strip_target( SimpleITKTclsh ) - + add_subdirectory ( Tcl ) endif() # diff --git a/Wrapping/Lua/CMakeLists.txt b/Wrapping/Lua/CMakeLists.txt new file mode 100644 index 000000000..89a27e126 --- /dev/null +++ b/Wrapping/Lua/CMakeLists.txt @@ -0,0 +1,22 @@ + +if (CMAKE_VERSION VERSION_LESS "3") + find_package ( Lua51 REQUIRED ) +else() + find_package ( Lua REQUIRED ) +endif() +include_directories ( ${LUA_INCLUDE_DIR} ) + +set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) + +# Run swig +set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_SWIG_GLOBAL_FLAGS}) +set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) +set(SWIG_MODULE_SimpleITKLua_EXTRA_DEPS ${SWIG_EXTRA_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/Lua.i ) +SWIG_module_initialize ( SimpleITKLua lua ) +SWIG_add_source_to_module ( SimpleITKLua swig_generated_source ../SimpleITK.i ${SWIG_EXTRA_DEPS} ) +set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w" ) + +add_executable ( SimpleITKLua SimpleITKLuaMain.cxx ${swig_generated_file_fullname} ) +target_link_libraries ( SimpleITKLua ${SimpleITK_LIBRARIES} ${LUA_LIBRARIES} ${LUA_ADDITIONAL_LIBRARIES} ) +sitk_strip_target( SimpleITKLua ) diff --git a/Wrapping/Lua.i b/Wrapping/Lua/Lua.i similarity index 99% rename from Wrapping/Lua.i rename to Wrapping/Lua/Lua.i index 133d7a951..d7fc95110 100644 --- a/Wrapping/Lua.i +++ b/Wrapping/Lua/Lua.i @@ -24,4 +24,3 @@ %ignore itk::simple::GetPixelIDValueAsString( PixelIDValueType type ); #endif - diff --git a/Wrapping/SimpleITKLuaMain.cxx b/Wrapping/Lua/SimpleITKLuaMain.cxx similarity index 99% rename from Wrapping/SimpleITKLuaMain.cxx rename to Wrapping/Lua/SimpleITKLuaMain.cxx index 5b9391bbe..29ff6aa9f 100644 --- a/Wrapping/SimpleITKLuaMain.cxx +++ b/Wrapping/Lua/SimpleITKLuaMain.cxx @@ -427,5 +427,3 @@ int main (int argc, char **argv) { #endif return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS; } - - diff --git a/Wrapping/SimpleITK.i b/Wrapping/SimpleITK.i index d06c02312..50c97fd3c 100644 --- a/Wrapping/SimpleITK.i +++ b/Wrapping/SimpleITK.i @@ -82,11 +82,15 @@ // Language Specific Sections %include CSharp.i %include Java.i +#if SWIGTCL %include Tcl.i +#endif #if SWIGPYTHON %include Python.i #endif +#if SWIGLUA %include Lua.i +#endif %include R.i #if SWIGRUBY %include Ruby.i diff --git a/Wrapping/Tcl/CMakeLists.txt b/Wrapping/Tcl/CMakeLists.txt new file mode 100644 index 000000000..282f890ea --- /dev/null +++ b/Wrapping/Tcl/CMakeLists.txt @@ -0,0 +1,23 @@ + +find_package ( TCL REQUIRED ) +include_directories ( ${TCL_INCLUDE_PATH} ) + +set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) + +# Run swig +set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} "-nosafe" ${CMAKE_SWIG_GLOBAL_FLAGS}) +set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) +set(SWIG_MODULE_SimpleITKTCL_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/Tcl.i ) +set(SWIG_MODULE_SimpleITKTcl_EXTRA_DEPS ${SWIG_MODULE_SimpleITKTCL_EXTRA_DEPS}) +# SWIG_add_module ( SimpleITKTcl tcl SimpleITK.i SimpleITKTCL_wrap.cxx ) +# SWIG_link_libraries ( SimpleITKTcl ${SimpleITK_LIBRARIES} ${TCL_LIBRARY}) +# set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") +# add_executable ( SimpleITKTclsh ${swig_generated_file_fullname} ) +# target_link_libraries ( SimpleITKTclsh ${SimpleITK_LIBRARIES} ${TCL_LIBRARY}) + +SWIG_module_initialize ( SimpleITKTCL tcl ) +SWIG_add_source_to_module ( SimpleITKTCL swig_generated_source ../SimpleITK.i ${SWIG_EXTRA_DEPS} ) +set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w" ) +add_executable ( SimpleITKTclsh ${swig_generated_file_fullname} ) +target_link_libraries ( SimpleITKTclsh ${SimpleITK_LIBRARIES} ${TCL_LIBRARY} ) +sitk_strip_target( SimpleITKTclsh ) diff --git a/Wrapping/Tcl.i b/Wrapping/Tcl/Tcl.i similarity index 100% rename from Wrapping/Tcl.i rename to Wrapping/Tcl/Tcl.i From c6d74722beece6851a2b3105e58c3868b7c80a7b Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 28 Oct 2015 11:43:18 -0400 Subject: [PATCH 100/412] Move CSharp wrapping to sub-directory Change-Id: I7387545c255e71ca44002a7f2fb20d2faf53a81f --- Wrapping/CMakeLists.txt | 83 +------------------- Wrapping/{ => CSharp}/AssemblyInfo.cs.in | 0 Wrapping/CSharp/CMakeLists.txt | 87 +++++++++++++++++++++ Wrapping/{ => CSharp}/CSharp.i | 0 Wrapping/{ => CSharp}/CSharpTypemapHelper.i | 0 Wrapping/CSharp/dist/CMakeLists.txt | 66 ++++++++++++++++ Wrapping/SimpleITK.i | 2 + Wrapping/dist/CMakeLists.txt | 66 ---------------- 8 files changed, 156 insertions(+), 148 deletions(-) rename Wrapping/{ => CSharp}/AssemblyInfo.cs.in (100%) create mode 100644 Wrapping/CSharp/CMakeLists.txt rename Wrapping/{ => CSharp}/CSharp.i (100%) rename Wrapping/{ => CSharp}/CSharpTypemapHelper.i (100%) create mode 100644 Wrapping/CSharp/dist/CMakeLists.txt diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index a366604a5..3b8b19430 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -127,88 +127,7 @@ endif() # C# SWIG configuration # if ( WRAP_CSHARP ) - - # Find C# - find_package( CSharp REQUIRED ) - include( ${CSHARP_USE_FILE} ) - - # CSharp version requirements: http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.aspx - # major.minor[.build[.revision]] where all components are 16-bit unsigned integers - set(_build 0) - if(DEFINED SimpleITK_VERSION_POST) - math(EXPR _build "${SimpleITK_VERSION_POST}") - elseif(DEFINED SimpleITK_VERSION_DEV) - math(EXPR _build "32768+${SimpleITK_VERSION_DEV}") - endif() - if(_build GREATER 65535) - message(WARNING "CSharp build component overflowed, setting to 65535 instead of ${_build}.") - set(_build 65535) - endif() - - set(_revision 0) - if(DEFINED SimpleITK_VERSION_PATCH) - math(EXPR _revision "${SimpleITK_VERSION_PATCH}<<8") - if(DEFINED SimpleITK_VERSION_TWEAK) - math(EXPR _revision "_revision+${SimpleITK_VERSION_TWEAK}") - endif() - endif() - if(_revision GREATER 65535) - message(WARNING "CSharp revision component overflowed, setting to 65535 instead of ${_revision}.") - set(_revision 65535) - endif() - - set(SimpleITK_VERSION_CSHARP_AssemblyVersion "${SimpleITK_VERSION_MAJOR}.${SimpleITK_VERSION_MINOR}.${_build}.${_revision}") - - # Make sure the nested directory structure exists - set(CSHARP_SOURCE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/CSharpSources CACHE INTERNAL "") - set(CSHARP_BINARY_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/CSharpBinaries CACHE INTERNAL "") - file(MAKE_DIRECTORY ${CSHARP_SOURCE_DIRECTORY}) - file(MAKE_DIRECTORY ${CSHARP_BINARY_DIRECTORY}) - - # Create swig target - set(CMAKE_SWIG_OUTDIR ${CSHARP_SOURCE_DIRECTORY}) - if ( UNIX ) - set(CMAKE_SWIG_FLAGS -dllimport \"libSimpleITKCSharpNative\") - else (WIN32 ) - set(CMAKE_SWIG_FLAGS -dllimport \"SimpleITKCSharpNative\") - endif ( UNIX ) - set(CMAKE_SWIG_FLAGS -namespace \"itk.simple\" ${CMAKE_SWIG_GLOBAL_FLAGS} ${CMAKE_SWIG_FLAGS}) - set(SWIG_MODULE_SimpleITKCSharpNative_EXTRA_DEPS ${SWIG_EXTRA_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/CSharp.i - ${CMAKE_CURRENT_SOURCE_DIR}/CSharpTypemapHelper.i ) - swig_add_module(SimpleITKCSharpNative csharp SimpleITK.i) - swig_link_libraries(SimpleITKCSharpNative ${SimpleITK_LIBRARIES}) - set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CSHARP_BINARY_DIRECTORY}) - if ( UNIX ) - set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} PROPERTIES PREFIX "lib") - set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} PROPERTIES SUFFIX ".so") - else ( WIN32 ) - set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} PROPERTIES PREFIX "") - set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} PROPERTIES SUFFIX ".dll") - foreach ( CMAKE_CONFIGURATION_TYPE ${CMAKE_CONFIGURATION_TYPES} ) - string(TOUPPER ${CMAKE_CONFIGURATION_TYPE} CMAKE_CONFIGURATION_TYPE) - set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} - PROPERTIES LIBRARY_OUTPUT_DIRECTORY_${CMAKE_CONFIGURATION_TYPE} "${CSHARP_BINARY_DIRECTORY}") - set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} - PROPERTIES RUNTIME_OUTPUT_DIRECTORY_${CMAKE_CONFIGURATION_TYPE} "${CSHARP_BINARY_DIRECTORY}") - endforeach( ) - endif( UNIX ) - sitk_strip_target( ${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} ) - - # Configure AssemblyInfo.cs - configure_file( - ${CMAKE_CURRENT_SOURCE_DIR}/AssemblyInfo.cs.in - ${CSHARP_SOURCE_DIRECTORY}/AssemblyInfo.cs - @ONLY - ) - - # Add managed wrapper - csharp_add_library( - SimpleITKCSharpManaged - ${CSHARP_SOURCE_DIRECTORY}/*.cs - ) - add_dependencies(SimpleITKCSharpManaged ${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME}) - + add_subdirectory ( CSharp ) endif() # diff --git a/Wrapping/AssemblyInfo.cs.in b/Wrapping/CSharp/AssemblyInfo.cs.in similarity index 100% rename from Wrapping/AssemblyInfo.cs.in rename to Wrapping/CSharp/AssemblyInfo.cs.in diff --git a/Wrapping/CSharp/CMakeLists.txt b/Wrapping/CSharp/CMakeLists.txt new file mode 100644 index 000000000..3cb0bc5fb --- /dev/null +++ b/Wrapping/CSharp/CMakeLists.txt @@ -0,0 +1,87 @@ + +# Find C# +find_package( CSharp REQUIRED ) +include( ${CSHARP_USE_FILE} ) + +set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) + +# CSharp version requirements: http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.aspx +# major.minor[.build[.revision]] where all components are 16-bit unsigned integers +set(_build 0) +if(DEFINED SimpleITK_VERSION_POST) + math(EXPR _build "${SimpleITK_VERSION_POST}") + elseif(DEFINED SimpleITK_VERSION_DEV) + math(EXPR _build "32768+${SimpleITK_VERSION_DEV}") + endif() + if(_build GREATER 65535) + message(WARNING "CSharp build component overflowed, setting to 65535 instead of ${_build}.") + set(_build 65535) + endif() + + set(_revision 0) + if(DEFINED SimpleITK_VERSION_PATCH) + math(EXPR _revision "${SimpleITK_VERSION_PATCH}<<8") + if(DEFINED SimpleITK_VERSION_TWEAK) + math(EXPR _revision "_revision+${SimpleITK_VERSION_TWEAK}") + endif() + endif() + if(_revision GREATER 65535) + message(WARNING "CSharp revision component overflowed, setting to 65535 instead of ${_revision}.") + set(_revision 65535) + endif() + + set(SimpleITK_VERSION_CSHARP_AssemblyVersion "${SimpleITK_VERSION_MAJOR}.${SimpleITK_VERSION_MINOR}.${_build}.${_revision}") + + # Make sure the nested directory structure exists + set(CSHARP_SOURCE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/CSharpSources CACHE INTERNAL "") + set(CSHARP_BINARY_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/CSharpBinaries CACHE INTERNAL "") + file(MAKE_DIRECTORY ${CSHARP_SOURCE_DIRECTORY}) + file(MAKE_DIRECTORY ${CSHARP_BINARY_DIRECTORY}) + + # Create swig target + set(CMAKE_SWIG_OUTDIR ${CSHARP_SOURCE_DIRECTORY}) + if ( UNIX ) + set(CMAKE_SWIG_FLAGS -dllimport \"libSimpleITKCSharpNative\") + else (WIN32 ) + set(CMAKE_SWIG_FLAGS -dllimport \"SimpleITKCSharpNative\") + endif ( UNIX ) + set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} -namespace \"itk.simple\" ${CMAKE_SWIG_GLOBAL_FLAGS} ${CMAKE_SWIG_FLAGS}) + set(SWIG_MODULE_SimpleITKCSharpNative_EXTRA_DEPS ${SWIG_EXTRA_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/CSharp.i + ${CMAKE_CURRENT_SOURCE_DIR}/CSharpTypemapHelper.i ) + swig_add_module(SimpleITKCSharpNative csharp ../SimpleITK.i) + swig_link_libraries(SimpleITKCSharpNative ${SimpleITK_LIBRARIES}) + set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CSHARP_BINARY_DIRECTORY}) + if ( UNIX ) + set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} PROPERTIES PREFIX "lib") + set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} PROPERTIES SUFFIX ".so") + else ( WIN32 ) + set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} PROPERTIES PREFIX "") + set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} PROPERTIES SUFFIX ".dll") + foreach ( CMAKE_CONFIGURATION_TYPE ${CMAKE_CONFIGURATION_TYPES} ) + string(TOUPPER ${CMAKE_CONFIGURATION_TYPE} CMAKE_CONFIGURATION_TYPE) + set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} + PROPERTIES LIBRARY_OUTPUT_DIRECTORY_${CMAKE_CONFIGURATION_TYPE} "${CSHARP_BINARY_DIRECTORY}") + set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} + PROPERTIES RUNTIME_OUTPUT_DIRECTORY_${CMAKE_CONFIGURATION_TYPE} "${CSHARP_BINARY_DIRECTORY}") + endforeach( ) + endif( UNIX ) + sitk_strip_target( ${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} ) + + # Configure AssemblyInfo.cs + configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/AssemblyInfo.cs.in + ${CSHARP_SOURCE_DIRECTORY}/AssemblyInfo.cs + @ONLY + ) + + # Add managed wrapper + csharp_add_library( + SimpleITKCSharpManaged + ${CSHARP_SOURCE_DIRECTORY}/*.cs + ) + add_dependencies(SimpleITKCSharpManaged ${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME}) + + +# Packaging for distribution +add_subdirectory(dist) diff --git a/Wrapping/CSharp.i b/Wrapping/CSharp/CSharp.i similarity index 100% rename from Wrapping/CSharp.i rename to Wrapping/CSharp/CSharp.i diff --git a/Wrapping/CSharpTypemapHelper.i b/Wrapping/CSharp/CSharpTypemapHelper.i similarity index 100% rename from Wrapping/CSharpTypemapHelper.i rename to Wrapping/CSharp/CSharpTypemapHelper.i diff --git a/Wrapping/CSharp/dist/CMakeLists.txt b/Wrapping/CSharp/dist/CMakeLists.txt new file mode 100644 index 000000000..154c28bd7 --- /dev/null +++ b/Wrapping/CSharp/dist/CMakeLists.txt @@ -0,0 +1,66 @@ + +# +# CSharp Packaging +# +if( WRAP_CSHARP AND Java_JAR_EXECUTABLE ) + + set(_files "") + list( APPEND _files + ${SimpleITK_DOC_FILES} + "${CSHARP_BINARY_DIRECTORY}/SimpleITKCSharpManaged.dll" + ) + + if(NOT DEFINED SIMPLEITK_CSHARP_ARCH) + if(MSVC) + if (CMAKE_CL_64) + set(SIMPLEITK_CSHARP_ARCH "win64") + else() + set(SIMPLEITK_CSHARP_ARCH "win32") + endif() + else() + set(SIMPLEITK_CSHARP_ARCH "unknown") + endif() + + if(CSHARP_PLATFORM) + set(SIMPLEITK_CSHARP_ARCH "${SIMPLEITK_CSHARP_ARCH}-${CSHARP_PLATFORM}") + endif() + endif() + + set( CSHARP_PACKAGE_STAGE_DIR "SimpleITK-${SimpleITK_VERSION}-CSharp-${SIMPLEITK_CSHARP_ARCH}") + + add_custom_target( dist.CSharp + COMMENT "Creating CSharp package ${CSHARP_PACKAGE_STAGE_DIR}.zip" + DEPENDS SimpleITKCSharpManaged + ) + + add_custom_command( TARGET dist.CSharp + PRE_BUILD + COMMAND ${CMAKE_COMMAND} -E remove_directory "${CSHARP_PACKAGE_STAGE_DIR}" + COMMAND ${CMAKE_COMMAND} -E make_directory "${CSHARP_PACKAGE_STAGE_DIR}" + COMMENT "Creating CSharp staging directory..." + ) + + foreach(_f ${_files}) + get_filename_component(_f_name ${_f} NAME ) + add_custom_command( TARGET dist.CSharp + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_f}" "${CSHARP_PACKAGE_STAGE_DIR}/${_f_name}" + COMMENT "Copying ${_f_name} to CSharp stage..." + ) + endforeach() + + add_custom_command( TARGET dist.CSharp + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy "$" "${CSHARP_PACKAGE_STAGE_DIR}" + COMMENT "Copying $ to CSharp stage..." +# COMMAND ${CMAKE_COMMAND} -E copy "$" "${CSHARP_PACKAGE_STAGE_DIR}" +# COMMENT "Copying $ to CSharp stage..." + + SimpleITKCSharpManaged + COMMAND ${Java_JAR_EXECUTABLE} cfM "${CSHARP_PACKAGE_STAGE_DIR}.zip" "${CSHARP_PACKAGE_STAGE_DIR}" + COMMENT "Packaging CSHARP distribution..." + ) + + add_dependencies( dist dist.CSharp ) + +endif() diff --git a/Wrapping/SimpleITK.i b/Wrapping/SimpleITK.i index 50c97fd3c..da633113a 100644 --- a/Wrapping/SimpleITK.i +++ b/Wrapping/SimpleITK.i @@ -80,7 +80,9 @@ %} // Language Specific Sections +#if SWIGCSHARP %include CSharp.i +#endif %include Java.i #if SWIGTCL %include Tcl.i diff --git a/Wrapping/dist/CMakeLists.txt b/Wrapping/dist/CMakeLists.txt index 180ee6674..bfcc14f7e 100644 --- a/Wrapping/dist/CMakeLists.txt +++ b/Wrapping/dist/CMakeLists.txt @@ -77,69 +77,3 @@ if( WRAP_JAVA ) add_dependencies( dist dist.Java ) endif() - -# -# CSharp Packaging -# -if( WRAP_CSHARP AND Java_JAR_EXECUTABLE ) - - set(_files "") - list( APPEND _files - ${SimpleITK_DOC_FILES} - "${CSHARP_BINARY_DIRECTORY}/SimpleITKCSharpManaged.dll" - ) - - if(NOT DEFINED SIMPLEITK_CSHARP_ARCH) - if(MSVC) - if (CMAKE_CL_64) - set(SIMPLEITK_CSHARP_ARCH "win64") - else() - set(SIMPLEITK_CSHARP_ARCH "win32") - endif() - else() - set(SIMPLEITK_CSHARP_ARCH "unknown") - endif() - - if(CSHARP_PLATFORM) - set(SIMPLEITK_CSHARP_ARCH "${SIMPLEITK_CSHARP_ARCH}-${CSHARP_PLATFORM}") - endif() - endif() - - set( CSHARP_PACKAGE_STAGE_DIR "SimpleITK-${SimpleITK_VERSION}-CSharp-${SIMPLEITK_CSHARP_ARCH}") - - add_custom_target( dist.CSharp - COMMENT "Creating CSharp package ${CSHARP_PACKAGE_STAGE_DIR}.zip" - DEPENDS SimpleITKCSharpManaged - ) - - add_custom_command( TARGET dist.CSharp - PRE_BUILD - COMMAND ${CMAKE_COMMAND} -E remove_directory "${CSHARP_PACKAGE_STAGE_DIR}" - COMMAND ${CMAKE_COMMAND} -E make_directory "${CSHARP_PACKAGE_STAGE_DIR}" - COMMENT "Creating CSharp staging directory..." - ) - - foreach(_f ${_files}) - get_filename_component(_f_name ${_f} NAME ) - add_custom_command( TARGET dist.CSharp - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_f}" "${CSHARP_PACKAGE_STAGE_DIR}/${_f_name}" - COMMENT "Copying ${_f_name} to CSharp stage..." - ) - endforeach() - - add_custom_command( TARGET dist.CSharp - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy "$" "${CSHARP_PACKAGE_STAGE_DIR}" - COMMENT "Copying $ to CSharp stage..." -# COMMAND ${CMAKE_COMMAND} -E copy "$" "${CSHARP_PACKAGE_STAGE_DIR}" -# COMMENT "Copying $ to CSharp stage..." - - SimpleITKCSharpManaged - COMMAND ${Java_JAR_EXECUTABLE} cfM "${CSHARP_PACKAGE_STAGE_DIR}.zip" "${CSHARP_PACKAGE_STAGE_DIR}" - COMMENT "Packaging CSHARP distribution..." - ) - - add_dependencies( dist dist.CSharp ) - -endif() From 6aa66993f69e98e55bc519c18a1738a895ae57f6 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 28 Oct 2015 15:20:54 -0400 Subject: [PATCH 101/412] Moving Java wrapping to separate directory Change-Id: I7c6afd09b5a01375d8f58aa6d0c43d7a783942a1 --- CMake/sitkAddTest.cmake | 4 +- Testing/Unit/CMakeLists.txt | 2 +- .../Unit/sitkImageFilterTestTemplate.cxx.in | 2 +- Wrapping/CMakeLists.txt | 54 +------------ Wrapping/Java/CMakeLists.txt | 52 ++++++++++++ Wrapping/{ => Java}/Java.i | 0 Wrapping/{ => Java}/JavaDoc.i | 0 Wrapping/Java/dist/CMakeLists.txt | 75 ++++++++++++++++++ Wrapping/SimpleITK.i | 2 + Wrapping/dist/CMakeLists.txt | 79 ------------------- 10 files changed, 134 insertions(+), 136 deletions(-) create mode 100644 Wrapping/Java/CMakeLists.txt rename Wrapping/{ => Java}/Java.i (100%) rename Wrapping/{ => Java}/JavaDoc.i (100%) create mode 100644 Wrapping/Java/dist/CMakeLists.txt delete mode 100644 Wrapping/dist/CMakeLists.txt diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index b83ab9f93..98379f385 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -165,10 +165,10 @@ function(sitk_add_java_test name java_file) if(WIN32) set( _JAVA_LIBRARY_PATH "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/$" ) # Note: on windows this is a semi-colon separated list - set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/${JAR_FILE};${CMAKE_CURRENT_BINARY_DIR}" ) + set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE};${CMAKE_CURRENT_BINARY_DIR}" ) else(WIN32) set( _JAVA_LIBRARY_PATH "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}" ) - set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/${JAR_FILE}:${CMAKE_CURRENT_BINARY_DIR}" ) + set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}:${CMAKE_CURRENT_BINARY_DIR}" ) endif(WIN32) add_custom_command( diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index 34f2ea533..e27154b64 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -182,7 +182,7 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) OUTPUT "${OUTPUT_TEST_FILENAME}" COMMAND ${CMAKE_COMMAND} -E remove -f "${OUTPUT_TEST_FILENAME}" COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Java ${template_include_dir} TestTemplate.java.in "${OUTPUT_TEST_FILENAME}" - COMMAND ${Java_JAVAC_EXECUTABLE} -classpath ${SimpleITK_BINARY_DIR}/Wrapping/${JAR_FILE} ${SimpleITK_BINARY_DIR}/Testing/Unit/JavaTests/org/itk/simple/testing/${FILTERNAME}Test.java + COMMAND ${Java_JAVAC_EXECUTABLE} -classpath ${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE} ${SimpleITK_BINARY_DIR}/Testing/Unit/JavaTests/org/itk/simple/testing/${FILTERNAME}Test.java DEPENDS ${filter_json_file} ${JAVA_TEMPLATE_FILES} ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} ) add_test( NAME Java.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=Java.${FILTERNAME} ) diff --git a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in index 01546651c..1ccc72882 100644 --- a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in +++ b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in @@ -610,7 +610,7 @@ TEST_F(Java,${name}) { end) std::string Classpath = dataFinder.GetBuildDirectory() + "/Testing/Unit/JavaTests" - + dataFinder.GetPathSeparator() + dataFinder.GetBuildDirectory() + "/Wrapping/simpleitk-" + itk::simple::Version::VersionString() + ".jar"; + + dataFinder.GetPathSeparator() + dataFinder.GetBuildDirectory() + "/Wrapping/Java/simpleitk-" + itk::simple::Version::VersionString() + ".jar"; std::string JavaPath = dataFinder.GetLibraryDirectory(); std::string Script = "org.itk.simple.testing.${name}Test"; $(foreach tests diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index 3b8b19430..5e868cbc0 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -71,56 +71,7 @@ endif() # JAVA SWIG configuration # if ( WRAP_JAVA ) - find_package ( Java REQUIRED ) - find_package ( JNI REQUIRED ) - include_directories ( ${JAVA_INCLUDE_PATH} ${JNI_INCLUDE_DIRS} ) - - FIND_PROGRAM(Java_JAVADOC_EXECUTABLE - NAMES javadoc - HINTS ${_JAVA_HINTS} - PATHS ${_JAVA_PATHS} - ) - - # Make sure the nested directory structure exists - set(JAVA_SOURCE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/) - set(JAVA_BINARY_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/build) - file(MAKE_DIRECTORY ${JAVA_SOURCE_DIRECTORY}) - file(MAKE_DIRECTORY ${JAVA_BINARY_DIRECTORY}) - - # Nicely write the bridge code in org/itk/simple - set(CMAKE_SWIG_OUTDIR ${JAVA_SOURCE_DIRECTORY}/org/itk/simple/) - set(CMAKE_SWIG_FLAGS -package "org.itk.simple" ${CMAKE_SWIG_GLOBAL_FLAGS}) - set(SWIG_MODULE_SimpleITKJava_EXTRA_DEPS ${SWIG_EXTRA_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/Java.i ) - SWIG_add_module ( SimpleITKJava java SimpleITK.i SimpleITKJAVA_wrap.cxx) - SWIG_link_libraries(SimpleITKJava ${SimpleITK_LIBRARIES}) - set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/SimpleITKJAVA_wrap.cxx PROPERTIES COMPILE_FLAGS "-w") - sitk_strip_target( ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} ) - - # Add target for org.itk.simple.jar - add_custom_target(org_itk_simple_jar ALL DEPENDS ${JAR_FILE}) - set(JAVA_SOURCE_CODE ${JAVA_SOURCE_DIRECTORY}/org/itk/simple/*.java) - - # Add custom command and target to compile the generated files and put them in a jar file - # Make sure the commands depend on the output library from SWIG - add_custom_command( - OUTPUT ${JAR_FILE} - COMMENT "Creating jar file..." - COMMAND ${Java_JAVAC_EXECUTABLE} -d ${JAVA_BINARY_DIRECTORY} ${JAVA_SOURCE_CODE} - COMMAND ${Java_JAR_EXECUTABLE} cf ${CMAKE_CURRENT_BINARY_DIR}/${JAR_FILE} -C ${JAVA_BINARY_DIRECTORY} org - COMMAND ${Java_JAVADOC_EXECUTABLE} -quiet -d ${JAVA_BINARY_DIRECTORY}/javadoc -sourcepath ${JAVA_SOURCE_DIRECTORY} org.itk.simple - COMMAND ${Java_JAR_EXECUTABLE} cf ${CMAKE_CURRENT_BINARY_DIR}/${JAVADOC_FILE} -C ${JAVA_BINARY_DIRECTORY}/javadoc org - COMMAND ${Java_JAR_EXECUTABLE} cf ${CMAKE_CURRENT_BINARY_DIR}/${JAVA_SOURCE_FILE} org - DEPENDS ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} - ) - - # Get the location of the extension directory - string(REGEX REPLACE "include" "jre/lib/ext" JAVA_EXTENSION_DIR ${JAVA_INCLUDE_PATH} ) - - # TODO: add new target to install simpleitk java - # Add the install target - # install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${JAR_FILE} DESTINATION ${JAVA_EXTENSION_DIR}) - + add_subdirectory( Java ) endif() # @@ -190,6 +141,3 @@ if ( WRAP_R ) ) endif() - -# Packaging for distribution -add_subdirectory(dist) diff --git a/Wrapping/Java/CMakeLists.txt b/Wrapping/Java/CMakeLists.txt new file mode 100644 index 000000000..12f80bfd3 --- /dev/null +++ b/Wrapping/Java/CMakeLists.txt @@ -0,0 +1,52 @@ +find_package ( Java REQUIRED ) +find_package ( JNI REQUIRED ) +include_directories ( ${JAVA_INCLUDE_PATH} ${JNI_INCLUDE_DIRS} ) + +set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) + +FIND_PROGRAM(Java_JAVADOC_EXECUTABLE + NAMES javadoc + HINTS ${_JAVA_HINTS} + PATHS ${_JAVA_PATHS} + ) + +# Make sure the nested directory structure exists +set(JAVA_SOURCE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/) +set(JAVA_BINARY_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/build) +file(MAKE_DIRECTORY ${JAVA_SOURCE_DIRECTORY}) +file(MAKE_DIRECTORY ${JAVA_BINARY_DIRECTORY}) + +# Nicely write the bridge code in org/itk/simple +set(CMAKE_SWIG_OUTDIR ${JAVA_SOURCE_DIRECTORY}/org/itk/simple/) +set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} -package "org.itk.simple" ${CMAKE_SWIG_GLOBAL_FLAGS}) +set(SWIG_MODULE_SimpleITKJava_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/Java.i ${CMAKE_CURRENT_SOURCE_DIR}/JavaDoc.i) +SWIG_add_module ( SimpleITKJava java ../SimpleITK.i ) +SWIG_link_libraries(SimpleITKJava ${SimpleITK_LIBRARIES}) +set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") +sitk_strip_target( ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} ) + +# Add target for org.itk.simple.jar +add_custom_target(org_itk_simple_jar ALL DEPENDS ${JAR_FILE}) +set(JAVA_SOURCE_CODE ${JAVA_SOURCE_DIRECTORY}/org/itk/simple/*.java) + +# Add custom command and target to compile the generated files and put them in a jar file +# Make sure the commands depend on the output library from SWIG +add_custom_command( + OUTPUT ${JAR_FILE} + COMMENT "Creating jar file..." + COMMAND ${Java_JAVAC_EXECUTABLE} -d ${JAVA_BINARY_DIRECTORY} ${JAVA_SOURCE_CODE} + COMMAND ${Java_JAR_EXECUTABLE} cf ${CMAKE_CURRENT_BINARY_DIR}/${JAR_FILE} -C ${JAVA_BINARY_DIRECTORY} org + COMMAND ${Java_JAVADOC_EXECUTABLE} -quiet -d ${JAVA_BINARY_DIRECTORY}/javadoc -sourcepath ${JAVA_SOURCE_DIRECTORY} org.itk.simple + COMMAND ${Java_JAR_EXECUTABLE} cf ${CMAKE_CURRENT_BINARY_DIR}/${JAVADOC_FILE} -C ${JAVA_BINARY_DIRECTORY}/javadoc org + COMMAND ${Java_JAR_EXECUTABLE} cf ${CMAKE_CURRENT_BINARY_DIR}/${JAVA_SOURCE_FILE} org + DEPENDS ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} + ) + +# Get the location of the extension directory +string(REGEX REPLACE "include" "jre/lib/ext" JAVA_EXTENSION_DIR ${JAVA_INCLUDE_PATH} ) + +# TODO: add new target to install simpleitk java +# Add the install target +# install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${JAR_FILE} DESTINATION ${JAVA_EXTENSION_DIR}) + +add_subdirectory(dist) diff --git a/Wrapping/Java.i b/Wrapping/Java/Java.i similarity index 100% rename from Wrapping/Java.i rename to Wrapping/Java/Java.i diff --git a/Wrapping/JavaDoc.i b/Wrapping/Java/JavaDoc.i similarity index 100% rename from Wrapping/JavaDoc.i rename to Wrapping/Java/JavaDoc.i diff --git a/Wrapping/Java/dist/CMakeLists.txt b/Wrapping/Java/dist/CMakeLists.txt new file mode 100644 index 000000000..f637493a3 --- /dev/null +++ b/Wrapping/Java/dist/CMakeLists.txt @@ -0,0 +1,75 @@ + +# +# JAVA Packaging +# +set(_files "") +list( APPEND _files + ${SimpleITK_DOC_FILES} + ${SimpleITK_BINARY_DIR}/Wrapping/${JAR_FILE} + ${SimpleITK_BINARY_DIR}/Wrapping/${JAVA_SOURCE_FILE} + ${SimpleITK_BINARY_DIR}/Wrapping/${JAVADOC_FILE} + ) + +if(NOT DEFINED SIMPLEITK_JAVA_ARCH) + if(MSVC) + if (CMAKE_CL_64) + set(SIMPLEITK_JAVA_ARCH "win64") + else() + set(SIMPLEITK_JAVA_ARCH "win32") + endif() + elseif(APPLE) + # assemble macosx-OSX_DEPLOYMENT_TARGET-OSX_ARCHITECTURE + set(SIMPLEITK_JAVA_ARCH "macosx") + if(CMAKE_OSX_DEPLOYMENT_TARGET) + set(SIMPLEITK_JAVA_ARCH "${SIMPLEITK_JAVA_ARCH}-${CMAKE_OSX_DEPLOYMENT_TARGET}") + endif() + if(CMAKE_OSX_ARCHITECTURES MATCHES "i386" AND CMAKE_OSX_ARCHITECTURES MATCHES "x86_64") + if (CMAKE_OSX_ARCHITECTURES MATCHES "ppc") + set(SIMPLEITK_JAVA_ARCH "${SIMPLEITK_JAVA_ARCH}-universal") + else() + set(SIMPLEITK_JAVA_ARCH "${SIMPLEITK_JAVA_ARCH}-intel") + set(_OSX_ARCHITECTURES "intel") + endif() + elseif(CMAKE_OSX_ARCHITECTURES) + string(REPLACE ";" "_" _OSX_ARCHITECTURES "${CMAKE_OSX_ARCHITECTURES}") + set(SIMPLEITK_JAVA_ARCH "${SIMPLEITK_JAVA_ARCH}-${_OSX_ARCHITECTURES}") + else() + set(SIMPLEITK_JAVA_ARCH "${SIMPLEITK_JAVA_ARCH}-unknown") + endif() + else() + set(SIMPLEITK_JAVA_ARCH "unknown") + endif() +endif() + +set( JAVA_PACKAGE_STAGE_DIR "SimpleITK-${SimpleITK_VERSION}-Java-${SIMPLEITK_JAVA_ARCH}") + +add_custom_target( dist.Java + COMMENT "Creating Java package ${JAVA_PACKAGE_STAGE_DIR}.zip" + DEPENDS org_itk_simple_jar + ) + +add_custom_command( TARGET dist.Java + PRE_BUILD + COMMAND ${CMAKE_COMMAND} -E remove_directory "${JAVA_PACKAGE_STAGE_DIR}" + COMMAND ${CMAKE_COMMAND} -E make_directory "${JAVA_PACKAGE_STAGE_DIR}" + COMMENT "Creating Java staging directory..." + ) + +foreach(_f ${_files}) + get_filename_component(_f_name ${_f} NAME ) + add_custom_command( TARGET dist.Java + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_f}" "${JAVA_PACKAGE_STAGE_DIR}/${_f_name}" + COMMENT "Copying ${_f_name} to Java stage..." + ) +endforeach() + +add_custom_command( TARGET dist.Java + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy "$" "${JAVA_PACKAGE_STAGE_DIR}" + COMMENT "Copying $ to Java stage..." + COMMAND ${Java_JAR_EXECUTABLE} cfM "${JAVA_PACKAGE_STAGE_DIR}.zip" "${JAVA_PACKAGE_STAGE_DIR}" + COMMENT "Packaging JAVA distribution..." + ) + +add_dependencies( dist dist.Java ) diff --git a/Wrapping/SimpleITK.i b/Wrapping/SimpleITK.i index da633113a..b5340b06c 100644 --- a/Wrapping/SimpleITK.i +++ b/Wrapping/SimpleITK.i @@ -83,7 +83,9 @@ #if SWIGCSHARP %include CSharp.i #endif +#if SWIGJAVA %include Java.i +#endif #if SWIGTCL %include Tcl.i #endif diff --git a/Wrapping/dist/CMakeLists.txt b/Wrapping/dist/CMakeLists.txt deleted file mode 100644 index bfcc14f7e..000000000 --- a/Wrapping/dist/CMakeLists.txt +++ /dev/null @@ -1,79 +0,0 @@ - -# -# JAVA Packaging -# -if( WRAP_JAVA ) - - set(_files "") - list( APPEND _files - ${SimpleITK_DOC_FILES} - ${SimpleITK_BINARY_DIR}/Wrapping/${JAR_FILE} - ${SimpleITK_BINARY_DIR}/Wrapping/${JAVA_SOURCE_FILE} - ${SimpleITK_BINARY_DIR}/Wrapping/${JAVADOC_FILE} - ) - - if(NOT DEFINED SIMPLEITK_JAVA_ARCH) - if(MSVC) - if (CMAKE_CL_64) - set(SIMPLEITK_JAVA_ARCH "win64") - else() - set(SIMPLEITK_JAVA_ARCH "win32") - endif() - elseif(APPLE) - # assemble macosx-OSX_DEPLOYMENT_TARGET-OSX_ARCHITECTURE - set(SIMPLEITK_JAVA_ARCH "macosx") - if(CMAKE_OSX_DEPLOYMENT_TARGET) - set(SIMPLEITK_JAVA_ARCH "${SIMPLEITK_JAVA_ARCH}-${CMAKE_OSX_DEPLOYMENT_TARGET}") - endif() - if(CMAKE_OSX_ARCHITECTURES MATCHES "i386" AND CMAKE_OSX_ARCHITECTURES MATCHES "x86_64") - if (CMAKE_OSX_ARCHITECTURES MATCHES "ppc") - set(SIMPLEITK_JAVA_ARCH "${SIMPLEITK_JAVA_ARCH}-universal") - else() - set(SIMPLEITK_JAVA_ARCH "${SIMPLEITK_JAVA_ARCH}-intel") - set(_OSX_ARCHITECTURES "intel") - endif() - elseif(CMAKE_OSX_ARCHITECTURES) - string(REPLACE ";" "_" _OSX_ARCHITECTURES "${CMAKE_OSX_ARCHITECTURES}") - set(SIMPLEITK_JAVA_ARCH "${SIMPLEITK_JAVA_ARCH}-${_OSX_ARCHITECTURES}") - else() - set(SIMPLEITK_JAVA_ARCH "${SIMPLEITK_JAVA_ARCH}-unknown") - endif() - else() - set(SIMPLEITK_JAVA_ARCH "unknown") - endif() - endif() - - set( JAVA_PACKAGE_STAGE_DIR "SimpleITK-${SimpleITK_VERSION}-Java-${SIMPLEITK_JAVA_ARCH}") - - add_custom_target( dist.Java - COMMENT "Creating Java package ${JAVA_PACKAGE_STAGE_DIR}.zip" - DEPENDS org_itk_simple_jar - ) - - add_custom_command( TARGET dist.Java - PRE_BUILD - COMMAND ${CMAKE_COMMAND} -E remove_directory "${JAVA_PACKAGE_STAGE_DIR}" - COMMAND ${CMAKE_COMMAND} -E make_directory "${JAVA_PACKAGE_STAGE_DIR}" - COMMENT "Creating Java staging directory..." - ) - - foreach(_f ${_files}) - get_filename_component(_f_name ${_f} NAME ) - add_custom_command( TARGET dist.Java - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_f}" "${JAVA_PACKAGE_STAGE_DIR}/${_f_name}" - COMMENT "Copying ${_f_name} to Java stage..." - ) - endforeach() - - add_custom_command( TARGET dist.Java - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy "$" "${JAVA_PACKAGE_STAGE_DIR}" - COMMENT "Copying $ to Java stage..." - COMMAND ${Java_JAR_EXECUTABLE} cfM "${JAVA_PACKAGE_STAGE_DIR}.zip" "${JAVA_PACKAGE_STAGE_DIR}" - COMMENT "Packaging JAVA distribution..." - ) - - add_dependencies( dist dist.Java ) - -endif() From 5649f8fb72675d792880f71b75e8caa750998fa4 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 29 Oct 2015 09:21:35 -0400 Subject: [PATCH 102/412] Move R wrapping to sub-directory Renamed R library directory to R_libs, which follows R conventions. Change-Id: I472d80986beda679f5766133a615666086d98cfd --- CMake/sitkAddTest.cmake | 2 +- .../Unit/sitkImageFilterTestTemplate.cxx.in | 2 +- Wrapping/CMakeLists.txt | 51 +----------------- Wrapping/R/CMakeLists.txt | 46 ++++++++++++++++ .../Packaging}/SimpleITK/DESCRIPTION | 0 .../Packaging}/SimpleITK/NAMESPACE | 0 .../Packaging}/SimpleITK/R/zA.R | 0 .../Packaging}/SimpleITK/R/zOps.R | 0 .../SimpleITK/inst/doc/SimpleITK_tutorial.pdf | Bin .../Packaging}/SimpleITK/src/Makefile | 0 .../SimpleITK/vignettes/InsightArticle.cls | 0 .../SimpleITK/vignettes/InsightJournal.sty | 0 .../vignettes/SimpleITK_tutorial.Rnw | 0 .../SimpleITK/vignettes/algorithm.sty | 0 .../SimpleITK/vignettes/algorithmic.sty | 0 .../SimpleITK/vignettes/amssymb.sty | 0 .../SimpleITK/vignettes/fancyhdr.sty | 0 .../SimpleITK/vignettes/floatflt.sty | 0 .../SimpleITK/vignettes/fncychap.sty | 0 .../Packaging}/SimpleITK/vignettes/jss.cls | 0 .../Packaging}/SimpleITK/vignettes/times.sty | 0 .../SimpleITK/vignettes/upquote.sty | 0 Wrapping/{ => R}/R.i | 0 Wrapping/SimpleITK.i | 2 + 24 files changed, 52 insertions(+), 51 deletions(-) create mode 100644 Wrapping/R/CMakeLists.txt rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/DESCRIPTION (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/NAMESPACE (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/R/zA.R (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/R/zOps.R (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/inst/doc/SimpleITK_tutorial.pdf (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/src/Makefile (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/vignettes/InsightArticle.cls (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/vignettes/InsightJournal.sty (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/vignettes/SimpleITK_tutorial.Rnw (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/vignettes/algorithm.sty (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/vignettes/algorithmic.sty (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/vignettes/amssymb.sty (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/vignettes/fancyhdr.sty (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/vignettes/floatflt.sty (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/vignettes/fncychap.sty (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/vignettes/jss.cls (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/vignettes/times.sty (100%) rename Wrapping/{Rpackaging => R/Packaging}/SimpleITK/vignettes/upquote.sty (100%) rename Wrapping/{ => R}/R.i (100%) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index 98379f385..57fb02e67 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -219,7 +219,7 @@ function(sitk_add_r_test name) ) set_property(TEST R.${name} - PROPERTY ENVIRONMENT R_LIBS=${SimpleITK_BINARY_DIR}/Wrapping/RLib/ + PROPERTY ENVIRONMENT R_LIBS=${SimpleITK_BINARY_DIR}/Wrapping/R/R_libs/ ) endfunction() diff --git a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in index 1ccc72882..5688e7caa 100644 --- a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in +++ b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in @@ -537,7 +537,7 @@ TEST_F(R,${name}) { // Set-up the R enviroment to include the SimpleITK R library in the // build directory. - SetEnvironment ( "R_LIBS", dataFinder.GetBuildDirectory()+"/Wrapping/RLib" ); + SetEnvironment ( "R_LIBS", dataFinder.GetBuildDirectory()+"/Wrapping/R/R_libs" ); std::string Script = dataFinder.GetBuildDirectory() + "/Testing/Unit/RTests/${name}Test.R"; diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index 5e868cbc0..2feddea33 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -85,59 +85,12 @@ endif() # TCL SWIG configuration # if ( WRAP_TCL ) - add_subdirectory ( Tcl ) + add_subdirectory ( Tcl ) endif() # # R SWIG configuration # if ( WRAP_R ) - find_package ( R REQUIRED ) - include_directories ( ${R_INCLUDE_DIR} ) - - # Run swig - set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_GLOBAL_FLAGS}) - set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) - set(SWIG_MODULE_SimpleITK_EXTRA_DEPS ${SWIG_EXTRA_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/R.i ) - SWIG_add_module ( SimpleITK r SimpleITK.i SimpleITKR_wrap.cxx ) - SWIG_link_libraries ( SimpleITK ${SimpleITK_LIBRARIES} ) - - # on some platforms the r libraries are not required at link time... - if(R_LIBRARIES) - SWIG_link_libraries ( SimpleITK ${R_LIBRARIES} ) - endif() - - set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/SimpleITKR_wrap.cxx PROPERTIES COMPILE_FLAGS "-w") - - get_target_property( SIMPLEITKR_BINARY_MODULE ${SWIG_MODULE_SimpleITK_TARGET_NAME} LOCATION ) - file(TO_NATIVE_PATH "${SIMPLEITKR_BINARY_MODULE}" SIMPLEITKR_NATIVE_BINARY_MODULE ) - - - add_dependencies( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ConfigureFileBuildtime ) - - # set the output directory for the R library to the binary packaging location - set_target_properties( ${SWIG_MODULE_SimpleITK_TARGET_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/Rpackaging/SimpleITK/src/) - - sitk_strip_target( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ) - - # copy the R files a binary package - add_custom_command( TARGET ${SWIG_MODULE_SimpleITK_TARGET_NAME} - PRE_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_directory ${SimpleITK_SOURCE_DIR}/Wrapping/Rpackaging ${CMAKE_CURRENT_BINARY_DIR}/Rpackaging - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/Rpackaging/SimpleITK/data/ - ) - add_custom_command( TARGET ${SWIG_MODULE_SimpleITK_TARGET_NAME} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/RLib - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/SimpleITK.R ${CMAKE_CURRENT_BINARY_DIR}/Rpackaging/SimpleITK/R/ - # copy sample images - COMMAND ${CMAKE_COMMAND} -E copy ${SimpleITK_BINARY_DIR}/ExternalData/Testing/Data/Input/cthead1.png ${CMAKE_CURRENT_BINARY_DIR}/Rpackaging/SimpleITK/data/ - COMMAND ${CMAKE_COMMAND} -E copy ${SimpleITK_BINARY_DIR}/ExternalData/Testing/Data/Input/cthead1-Float.mha ${CMAKE_CURRENT_BINARY_DIR}/Rpackaging/SimpleITK/data/ - # install for running tests and create binary package - COMMAND ${R_COMMAND} CMD INSTALL --build ${CMAKE_CURRENT_BINARY_DIR}/Rpackaging/SimpleITK --library=${CMAKE_CURRENT_BINARY_DIR}/RLib - - COMMENT "Installing R package for testing and building binary version for distribution" - ) - + add_subdirectory( R ) endif() diff --git a/Wrapping/R/CMakeLists.txt b/Wrapping/R/CMakeLists.txt new file mode 100644 index 000000000..4955d4a2f --- /dev/null +++ b/Wrapping/R/CMakeLists.txt @@ -0,0 +1,46 @@ +find_package ( R REQUIRED ) +include_directories ( ${R_INCLUDE_DIR} ) + +set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) + +# Run swig +set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_SWIG_GLOBAL_FLAGS}) +set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) +set(SWIG_MODULE_SimpleITK_EXTRA_DEPS ${SWIG_EXTRA_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/R.i ) +SWIG_add_module ( SimpleITK r ../SimpleITK.i ) +SWIG_link_libraries ( SimpleITK ${SimpleITK_LIBRARIES} ) + +# on some platforms the r libraries are not required at link time... +if(R_LIBRARIES) + SWIG_link_libraries ( SimpleITK ${R_LIBRARIES} ) +endif() + +set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") + +get_target_property( SIMPLEITKR_BINARY_MODULE ${SWIG_MODULE_SimpleITK_TARGET_NAME} LOCATION ) +file(TO_NATIVE_PATH "${SIMPLEITKR_BINARY_MODULE}" SIMPLEITKR_NATIVE_BINARY_MODULE ) + + +# set the output directory for the R library to the binary packaging location +set_target_properties( ${SWIG_MODULE_SimpleITK_TARGET_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/src/) + +sitk_strip_target( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ) + +# copy the R files a binary package +add_custom_command( TARGET ${SWIG_MODULE_SimpleITK_TARGET_NAME} + PRE_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_directory ${SimpleITK_SOURCE_DIR}/Wrapping/R/Packaging ${CMAKE_CURRENT_BINARY_DIR}/Packaging + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/data/ + ) +add_custom_command( TARGET ${SWIG_MODULE_SimpleITK_TARGET_NAME} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/R_libs + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/SimpleITK.R ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/R/ + # copy sample images + COMMAND ${CMAKE_COMMAND} -E copy ${SimpleITK_BINARY_DIR}/ExternalData/Testing/Data/Input/cthead1.png ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/data/ + COMMAND ${CMAKE_COMMAND} -E copy ${SimpleITK_BINARY_DIR}/ExternalData/Testing/Data/Input/cthead1-Float.mha ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/data/ + # install for running tests and create binary package + COMMAND ${R_COMMAND} CMD INSTALL --build ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK --library=${CMAKE_CURRENT_BINARY_DIR}/R_libs + COMMENT "Installing R package for testing and building binary version for distribution" + ) diff --git a/Wrapping/Rpackaging/SimpleITK/DESCRIPTION b/Wrapping/R/Packaging/SimpleITK/DESCRIPTION similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/DESCRIPTION rename to Wrapping/R/Packaging/SimpleITK/DESCRIPTION diff --git a/Wrapping/Rpackaging/SimpleITK/NAMESPACE b/Wrapping/R/Packaging/SimpleITK/NAMESPACE similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/NAMESPACE rename to Wrapping/R/Packaging/SimpleITK/NAMESPACE diff --git a/Wrapping/Rpackaging/SimpleITK/R/zA.R b/Wrapping/R/Packaging/SimpleITK/R/zA.R similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/R/zA.R rename to Wrapping/R/Packaging/SimpleITK/R/zA.R diff --git a/Wrapping/Rpackaging/SimpleITK/R/zOps.R b/Wrapping/R/Packaging/SimpleITK/R/zOps.R similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/R/zOps.R rename to Wrapping/R/Packaging/SimpleITK/R/zOps.R diff --git a/Wrapping/Rpackaging/SimpleITK/inst/doc/SimpleITK_tutorial.pdf b/Wrapping/R/Packaging/SimpleITK/inst/doc/SimpleITK_tutorial.pdf similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/inst/doc/SimpleITK_tutorial.pdf rename to Wrapping/R/Packaging/SimpleITK/inst/doc/SimpleITK_tutorial.pdf diff --git a/Wrapping/Rpackaging/SimpleITK/src/Makefile b/Wrapping/R/Packaging/SimpleITK/src/Makefile similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/src/Makefile rename to Wrapping/R/Packaging/SimpleITK/src/Makefile diff --git a/Wrapping/Rpackaging/SimpleITK/vignettes/InsightArticle.cls b/Wrapping/R/Packaging/SimpleITK/vignettes/InsightArticle.cls similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/vignettes/InsightArticle.cls rename to Wrapping/R/Packaging/SimpleITK/vignettes/InsightArticle.cls diff --git a/Wrapping/Rpackaging/SimpleITK/vignettes/InsightJournal.sty b/Wrapping/R/Packaging/SimpleITK/vignettes/InsightJournal.sty similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/vignettes/InsightJournal.sty rename to Wrapping/R/Packaging/SimpleITK/vignettes/InsightJournal.sty diff --git a/Wrapping/Rpackaging/SimpleITK/vignettes/SimpleITK_tutorial.Rnw b/Wrapping/R/Packaging/SimpleITK/vignettes/SimpleITK_tutorial.Rnw similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/vignettes/SimpleITK_tutorial.Rnw rename to Wrapping/R/Packaging/SimpleITK/vignettes/SimpleITK_tutorial.Rnw diff --git a/Wrapping/Rpackaging/SimpleITK/vignettes/algorithm.sty b/Wrapping/R/Packaging/SimpleITK/vignettes/algorithm.sty similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/vignettes/algorithm.sty rename to Wrapping/R/Packaging/SimpleITK/vignettes/algorithm.sty diff --git a/Wrapping/Rpackaging/SimpleITK/vignettes/algorithmic.sty b/Wrapping/R/Packaging/SimpleITK/vignettes/algorithmic.sty similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/vignettes/algorithmic.sty rename to Wrapping/R/Packaging/SimpleITK/vignettes/algorithmic.sty diff --git a/Wrapping/Rpackaging/SimpleITK/vignettes/amssymb.sty b/Wrapping/R/Packaging/SimpleITK/vignettes/amssymb.sty similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/vignettes/amssymb.sty rename to Wrapping/R/Packaging/SimpleITK/vignettes/amssymb.sty diff --git a/Wrapping/Rpackaging/SimpleITK/vignettes/fancyhdr.sty b/Wrapping/R/Packaging/SimpleITK/vignettes/fancyhdr.sty similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/vignettes/fancyhdr.sty rename to Wrapping/R/Packaging/SimpleITK/vignettes/fancyhdr.sty diff --git a/Wrapping/Rpackaging/SimpleITK/vignettes/floatflt.sty b/Wrapping/R/Packaging/SimpleITK/vignettes/floatflt.sty similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/vignettes/floatflt.sty rename to Wrapping/R/Packaging/SimpleITK/vignettes/floatflt.sty diff --git a/Wrapping/Rpackaging/SimpleITK/vignettes/fncychap.sty b/Wrapping/R/Packaging/SimpleITK/vignettes/fncychap.sty similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/vignettes/fncychap.sty rename to Wrapping/R/Packaging/SimpleITK/vignettes/fncychap.sty diff --git a/Wrapping/Rpackaging/SimpleITK/vignettes/jss.cls b/Wrapping/R/Packaging/SimpleITK/vignettes/jss.cls similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/vignettes/jss.cls rename to Wrapping/R/Packaging/SimpleITK/vignettes/jss.cls diff --git a/Wrapping/Rpackaging/SimpleITK/vignettes/times.sty b/Wrapping/R/Packaging/SimpleITK/vignettes/times.sty similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/vignettes/times.sty rename to Wrapping/R/Packaging/SimpleITK/vignettes/times.sty diff --git a/Wrapping/Rpackaging/SimpleITK/vignettes/upquote.sty b/Wrapping/R/Packaging/SimpleITK/vignettes/upquote.sty similarity index 100% rename from Wrapping/Rpackaging/SimpleITK/vignettes/upquote.sty rename to Wrapping/R/Packaging/SimpleITK/vignettes/upquote.sty diff --git a/Wrapping/R.i b/Wrapping/R/R.i similarity index 100% rename from Wrapping/R.i rename to Wrapping/R/R.i diff --git a/Wrapping/SimpleITK.i b/Wrapping/SimpleITK.i index b5340b06c..0e7200b17 100644 --- a/Wrapping/SimpleITK.i +++ b/Wrapping/SimpleITK.i @@ -95,7 +95,9 @@ #if SWIGLUA %include Lua.i #endif +#if SWIGR %include R.i +#endif #if SWIGRUBY %include Ruby.i #endif From 90a597d5f26be7920d1c91f69431a7dfcf5b3733 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 29 Oct 2015 14:46:16 -0400 Subject: [PATCH 103/412] Adding SimpleITK.i to each language Change-Id: I6e9445980f9fc05733f5ba4a7410a8990ccecb51 --- Wrapping/CMakeLists.txt | 7 +++++-- Wrapping/CSharp/CMakeLists.txt | 6 +++--- Wrapping/CSharp/SimpleITK.i | 1 + .../{SimpleITK.i => Common/SimpleITK_Common.i} | 0 Wrapping/Java/CMakeLists.txt | 4 ++-- Wrapping/Java/SimpleITK.i | 1 + Wrapping/Lua/CMakeLists.txt | 6 +++--- Wrapping/Lua/SimpleITK.i | 1 + Wrapping/Python/CMakeLists.txt | 8 ++++---- Wrapping/Python/SimpleITK.i | 1 + Wrapping/R/CMakeLists.txt | 6 +++--- Wrapping/R/SimpleITK.i | 1 + Wrapping/Ruby/CMakeLists.txt | 14 +++++++------- Wrapping/Ruby/SimpleITK.i | 1 + Wrapping/Tcl/CMakeLists.txt | 6 +++--- Wrapping/Tcl/SimpleITK.i | 1 + 16 files changed, 37 insertions(+), 27 deletions(-) create mode 100644 Wrapping/CSharp/SimpleITK.i rename Wrapping/{SimpleITK.i => Common/SimpleITK_Common.i} (100%) create mode 100644 Wrapping/Java/SimpleITK.i create mode 100644 Wrapping/Lua/SimpleITK.i create mode 100644 Wrapping/Python/SimpleITK.i create mode 100644 Wrapping/R/SimpleITK.i create mode 100644 Wrapping/Ruby/SimpleITK.i create mode 100644 Wrapping/Tcl/SimpleITK.i diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index 2feddea33..7ceedc45a 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -15,8 +15,6 @@ if ( WRAP_LUA OR WRAP_PYTHON OR WRAP_JAVA OR WRAP_CSHARP OR WRAP_TCL OR WRAP_R O include (UseSWIGLocal) - set_source_files_properties ( SimpleITK.i PROPERTIES CPLUSPLUS ON ) - file(GLOB SWIG_EXTRA_DEPS "${SimpleITK_SOURCE_DIR}/Code/Common/include/*.h" "${SimpleITK_SOURCE_DIR}/Code/Registration/include/*.h" @@ -38,6 +36,11 @@ if ( WRAP_LUA OR WRAP_PYTHON OR WRAP_JAVA OR WRAP_CSHARP OR WRAP_TCL OR WRAP_R O set ( CMAKE_SWIG_GLOBAL_FLAGS "-DSWIGWORDSIZE64" ) endif() + set(SIMPLEITK_WRAPPING_COMMON_DIR + ${SimpleITK_SOURCE_DIR}/Wrapping/Common) + +set ( CMAKE_SWIG_GLOBAL_FLAGS -I${SIMPLEITK_WRAPPING_COMMON_DIR} ${CMAKE_SWIG_GLOBAL_FLAGS} ) + endif() diff --git a/Wrapping/CSharp/CMakeLists.txt b/Wrapping/CSharp/CMakeLists.txt index 3cb0bc5fb..30f763d66 100644 --- a/Wrapping/CSharp/CMakeLists.txt +++ b/Wrapping/CSharp/CMakeLists.txt @@ -3,7 +3,7 @@ find_package( CSharp REQUIRED ) include( ${CSHARP_USE_FILE} ) -set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) +set_source_files_properties ( SimpleITK.i PROPERTIES CPLUSPLUS ON ) # CSharp version requirements: http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.aspx # major.minor[.build[.revision]] where all components are 16-bit unsigned integers @@ -45,11 +45,11 @@ if(DEFINED SimpleITK_VERSION_POST) else (WIN32 ) set(CMAKE_SWIG_FLAGS -dllimport \"SimpleITKCSharpNative\") endif ( UNIX ) - set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} -namespace \"itk.simple\" ${CMAKE_SWIG_GLOBAL_FLAGS} ${CMAKE_SWIG_FLAGS}) + set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} -namespace \"itk.simple\" ${CMAKE_SWIG_GLOBAL_FLAGS} ${CMAKE_SWIG_FLAGS}) set(SWIG_MODULE_SimpleITKCSharpNative_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/CSharp.i ${CMAKE_CURRENT_SOURCE_DIR}/CSharpTypemapHelper.i ) - swig_add_module(SimpleITKCSharpNative csharp ../SimpleITK.i) + swig_add_module(SimpleITKCSharpNative csharp SimpleITK.i) swig_link_libraries(SimpleITKCSharpNative ${SimpleITK_LIBRARIES}) set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CSHARP_BINARY_DIRECTORY}) if ( UNIX ) diff --git a/Wrapping/CSharp/SimpleITK.i b/Wrapping/CSharp/SimpleITK.i new file mode 100644 index 000000000..74635c2ab --- /dev/null +++ b/Wrapping/CSharp/SimpleITK.i @@ -0,0 +1 @@ +%include SimpleITK_Common.i diff --git a/Wrapping/SimpleITK.i b/Wrapping/Common/SimpleITK_Common.i similarity index 100% rename from Wrapping/SimpleITK.i rename to Wrapping/Common/SimpleITK_Common.i diff --git a/Wrapping/Java/CMakeLists.txt b/Wrapping/Java/CMakeLists.txt index 12f80bfd3..0dc5591a0 100644 --- a/Wrapping/Java/CMakeLists.txt +++ b/Wrapping/Java/CMakeLists.txt @@ -2,7 +2,7 @@ find_package ( Java REQUIRED ) find_package ( JNI REQUIRED ) include_directories ( ${JAVA_INCLUDE_PATH} ${JNI_INCLUDE_DIRS} ) -set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) +set_source_files_properties ( SimpleITK.i PROPERTIES CPLUSPLUS ON ) FIND_PROGRAM(Java_JAVADOC_EXECUTABLE NAMES javadoc @@ -20,7 +20,7 @@ file(MAKE_DIRECTORY ${JAVA_BINARY_DIRECTORY}) set(CMAKE_SWIG_OUTDIR ${JAVA_SOURCE_DIRECTORY}/org/itk/simple/) set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} -package "org.itk.simple" ${CMAKE_SWIG_GLOBAL_FLAGS}) set(SWIG_MODULE_SimpleITKJava_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/Java.i ${CMAKE_CURRENT_SOURCE_DIR}/JavaDoc.i) -SWIG_add_module ( SimpleITKJava java ../SimpleITK.i ) +SWIG_add_module ( SimpleITKJava java SimpleITK.i ) SWIG_link_libraries(SimpleITKJava ${SimpleITK_LIBRARIES}) set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") sitk_strip_target( ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} ) diff --git a/Wrapping/Java/SimpleITK.i b/Wrapping/Java/SimpleITK.i new file mode 100644 index 000000000..74635c2ab --- /dev/null +++ b/Wrapping/Java/SimpleITK.i @@ -0,0 +1 @@ +%include SimpleITK_Common.i diff --git a/Wrapping/Lua/CMakeLists.txt b/Wrapping/Lua/CMakeLists.txt index 89a27e126..37f3660d8 100644 --- a/Wrapping/Lua/CMakeLists.txt +++ b/Wrapping/Lua/CMakeLists.txt @@ -6,15 +6,15 @@ else() endif() include_directories ( ${LUA_INCLUDE_DIR} ) -set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) +set_source_files_properties ( SimpleITK.i PROPERTIES CPLUSPLUS ON ) # Run swig -set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_SWIG_GLOBAL_FLAGS}) +set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_GLOBAL_FLAGS}) set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) set(SWIG_MODULE_SimpleITKLua_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/Lua.i ) SWIG_module_initialize ( SimpleITKLua lua ) -SWIG_add_source_to_module ( SimpleITKLua swig_generated_source ../SimpleITK.i ${SWIG_EXTRA_DEPS} ) +SWIG_add_source_to_module ( SimpleITKLua swig_generated_source SimpleITK.i ${SWIG_EXTRA_DEPS} ) set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w" ) add_executable ( SimpleITKLua SimpleITKLuaMain.cxx ${swig_generated_file_fullname} ) diff --git a/Wrapping/Lua/SimpleITK.i b/Wrapping/Lua/SimpleITK.i new file mode 100644 index 000000000..74635c2ab --- /dev/null +++ b/Wrapping/Lua/SimpleITK.i @@ -0,0 +1 @@ +%include SimpleITK_Common.i diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index 25ada2d51..878f64de1 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -8,10 +8,10 @@ option ( SimpleITK_PYTHON_WHEEL "Add building of python wheels to the dist targe mark_as_advanced( SimpleITK_PYTHON_WHEEL ) -set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) +set_source_files_properties ( SimpleITK.i PROPERTIES CPLUSPLUS ON ) # Run swig -set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_GLOBAL_FLAGS} -I${CMAKE_CURRENT_SOURCE_DIR} -features autodoc=1 -keyword ) +set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_GLOBAL_FLAGS} -features autodoc=1 -keyword ) if( SimpleITK_PYTHON_THREADS ) set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_FLAGS} -threads) endif() @@ -19,10 +19,10 @@ set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) set(SWIG_MODULE_SimpleITK_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/Python.i ) SWIG_add_module ( SimpleITK python - ../SimpleITK.i + SimpleITK.i sitkPyCommand.cxx ) SWIG_link_libraries ( SimpleITK ${SimpleITK_LIBRARIES} ${PYTHON_LIBRARIES}) -set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/SimpleITKPYTHON_wrap.cxx PROPERTIES COMPILE_FLAGS "-w") +set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") sitk_strip_target( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ) set(SWIG_MODULE_SimpleITKPython_TARGET_NAME "${SWIG_MODULE_SimpleITK_TARGET_NAME}") diff --git a/Wrapping/Python/SimpleITK.i b/Wrapping/Python/SimpleITK.i new file mode 100644 index 000000000..74635c2ab --- /dev/null +++ b/Wrapping/Python/SimpleITK.i @@ -0,0 +1 @@ +%include SimpleITK_Common.i diff --git a/Wrapping/R/CMakeLists.txt b/Wrapping/R/CMakeLists.txt index 4955d4a2f..04674f299 100644 --- a/Wrapping/R/CMakeLists.txt +++ b/Wrapping/R/CMakeLists.txt @@ -1,14 +1,14 @@ find_package ( R REQUIRED ) include_directories ( ${R_INCLUDE_DIR} ) -set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) +set_source_files_properties ( SimpleITK.i PROPERTIES CPLUSPLUS ON ) # Run swig -set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_SWIG_GLOBAL_FLAGS}) +set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_GLOBAL_FLAGS}) set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) set(SWIG_MODULE_SimpleITK_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/R.i ) -SWIG_add_module ( SimpleITK r ../SimpleITK.i ) +SWIG_add_module ( SimpleITK r SimpleITK.i ) SWIG_link_libraries ( SimpleITK ${SimpleITK_LIBRARIES} ) # on some platforms the r libraries are not required at link time... diff --git a/Wrapping/R/SimpleITK.i b/Wrapping/R/SimpleITK.i new file mode 100644 index 000000000..74635c2ab --- /dev/null +++ b/Wrapping/R/SimpleITK.i @@ -0,0 +1 @@ +%include SimpleITK_Common.i diff --git a/Wrapping/Ruby/CMakeLists.txt b/Wrapping/Ruby/CMakeLists.txt index 4a8d69d3f..243da30b5 100644 --- a/Wrapping/Ruby/CMakeLists.txt +++ b/Wrapping/Ruby/CMakeLists.txt @@ -1,16 +1,16 @@ -find_package ( Ruby REQUIRED ) -include_directories ( ${RUBY_INCLUDE_DIRS} ) +find_package( Ruby REQUIRED ) +include_directories( ${RUBY_INCLUDE_DIRS} ) -set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) +set_source_files_properties( SimpleITK.i PROPERTIES CPLUSPLUS ON ) # Run swig -set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} -autorename -module simpleitk ${CMAKE_SWIG_GLOBAL_FLAGS}) +set(CMAKE_SWIG_FLAGS -autorename -module simpleitk ${CMAKE_SWIG_GLOBAL_FLAGS}) set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) set(SWIG_MODULE_simpleitk_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/Ruby.i) -SWIG_add_module ( simpleitk ruby ../SimpleITK.i ) -SWIG_link_libraries ( simpleitk ${SimpleITK_LIBRARIES} ${RUBY_LIBRARY}) -set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/SimpleITKRUBY_wrap.cxx PROPERTIES COMPILE_FLAGS "-w") +SWIG_add_module( simpleitk ruby SimpleITK.i ) +SWIG_link_libraries( simpleitk ${SimpleITK_LIBRARIES} ${RUBY_LIBRARY}) +set_source_files_properties( ${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") sitk_strip_target( ${SWIG_MODULE_simpleitk_TARGET_NAME} ) diff --git a/Wrapping/Ruby/SimpleITK.i b/Wrapping/Ruby/SimpleITK.i new file mode 100644 index 000000000..74635c2ab --- /dev/null +++ b/Wrapping/Ruby/SimpleITK.i @@ -0,0 +1 @@ +%include SimpleITK_Common.i diff --git a/Wrapping/Tcl/CMakeLists.txt b/Wrapping/Tcl/CMakeLists.txt index 282f890ea..2b38ac2ea 100644 --- a/Wrapping/Tcl/CMakeLists.txt +++ b/Wrapping/Tcl/CMakeLists.txt @@ -2,10 +2,10 @@ find_package ( TCL REQUIRED ) include_directories ( ${TCL_INCLUDE_PATH} ) -set_source_files_properties ( ../SimpleITK.i PROPERTIES CPLUSPLUS ON ) +set_source_files_properties ( SimpleITK.i PROPERTIES CPLUSPLUS ON ) # Run swig -set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} "-nosafe" ${CMAKE_SWIG_GLOBAL_FLAGS}) +set(CMAKE_SWIG_FLAGS "-nosafe" ${CMAKE_SWIG_GLOBAL_FLAGS}) set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) set(SWIG_MODULE_SimpleITKTCL_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/Tcl.i ) set(SWIG_MODULE_SimpleITKTcl_EXTRA_DEPS ${SWIG_MODULE_SimpleITKTCL_EXTRA_DEPS}) @@ -16,7 +16,7 @@ set(SWIG_MODULE_SimpleITKTcl_EXTRA_DEPS ${SWIG_MODULE_SimpleITKTCL_EXTRA_DEPS}) # target_link_libraries ( SimpleITKTclsh ${SimpleITK_LIBRARIES} ${TCL_LIBRARY}) SWIG_module_initialize ( SimpleITKTCL tcl ) -SWIG_add_source_to_module ( SimpleITKTCL swig_generated_source ../SimpleITK.i ${SWIG_EXTRA_DEPS} ) +SWIG_add_source_to_module ( SimpleITKTCL swig_generated_source SimpleITK.i ${SWIG_EXTRA_DEPS} ) set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w" ) add_executable ( SimpleITKTclsh ${swig_generated_file_fullname} ) target_link_libraries ( SimpleITKTclsh ${SimpleITK_LIBRARIES} ${TCL_LIBRARY} ) diff --git a/Wrapping/Tcl/SimpleITK.i b/Wrapping/Tcl/SimpleITK.i new file mode 100644 index 000000000..74635c2ab --- /dev/null +++ b/Wrapping/Tcl/SimpleITK.i @@ -0,0 +1 @@ +%include SimpleITK_Common.i From e1ee2a796348ddc7dd9051b098fe9fd75042a332 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 5 Nov 2015 11:35:30 -0500 Subject: [PATCH 104/412] Adding script using to build anaconda distributions Change-Id: Ifebdb884a6c554869c3039869eb1b0467088f5b2 --- Utilities/Maintenance/AnacondaBuild.sh | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100755 Utilities/Maintenance/AnacondaBuild.sh diff --git a/Utilities/Maintenance/AnacondaBuild.sh b/Utilities/Maintenance/AnacondaBuild.sh new file mode 100755 index 000000000..26d1f98b3 --- /dev/null +++ b/Utilities/Maintenance/AnacondaBuild.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +ANACONDA_ROOT=${ANACONDA_ROOT:-${HOME}/anaconda} +CONDA_RECIPES=${CONDA_RECIPES:-${HOME}/src/conda-recipes} + +(${ANACONDA_ROOT}/bin/conda update conda -y && + ${ANACONDA_ROOT}/bin/conda update -n root conda-build -y ) || exit 1 + +cd ${CONDA_RECIPES} && git fetch origin && git checkout origin/build + + +( ${ANACONDA_ROOT}/bin/conda build simpleitk && + CONDA_PY=34 ${ANACONDA_ROOT}/bin/conda build simpleitk && + CONDA_PY=35 ${ANACONDA_ROOT}/bin/conda build simpleitk) || exit 1 + +find ${ANACONDA_ROOT}/conda-bld -name simpleitk.\*tar.bz2 + +#${ANACONDA_ROOT}/bin/binstar upload --user simpleitk --channel dev /home/blowekamp/anaconda/conda-bld/linux-32/simpleitk-0.9.0b01-py34_0.tar.bz2 From 5a553661daec8b07e913da745f4eab3fb7ab0db2 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 13 Nov 2015 13:58:23 -0500 Subject: [PATCH 105/412] Update to new CMake policies to reduce warnings Always set MACOSX_RPATH to true, for forwards compatibility with CMP0042. New behavior CMP0042 ------- ``MACOSX_RPATH`` is enabled by default. Change-Id: I173d8f641c873508fa5e164c58470804db4e335f --- CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 543a4fc8a..008e5c0b8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9,6 +9,9 @@ project ( SimpleITK ) cmake_policy( VERSION 2.8.1 ) +# NEW CMP0042 +set( CMAKE_MACOSX_RPATH 1) + # Include extra CMake files list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/CMake") From c9aa17f5ba4fd831a748d5390a5c291a313eef3d Mon Sep 17 00:00:00 2001 From: Ziv Yaniv Date: Fri, 13 Nov 2015 14:34:39 -0500 Subject: [PATCH 106/412] BUG: Fixed bug converting between vector and set of ITK points. Change-Id: I55cb4f8878762af5e138939eab1c008b1a61300a --- ...andmarkBasedTransformInitializerFilter.cxx | 12 ++-------- Code/Common/include/sitkTemplateFunctions.h | 18 ++++++++++++++ Testing/Unit/sitkBasicFiltersTests.cxx | 24 ++++++++++++++++--- 3 files changed, 41 insertions(+), 13 deletions(-) diff --git a/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx b/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx index 91a556ed1..228592ca9 100644 --- a/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx +++ b/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx @@ -173,19 +173,11 @@ Transform LandmarkBasedTransformInitializerFilter::ExecuteInternal ( const Trans typedef typename FilterType::LandmarkPointContainer PointContainer; PointContainer fixedITKPoints; - for( unsigned int i = 0; i < m_FixedLandmarks.size()- Dimension - 1; i += Dimension) - { - typename FilterType::LandmarkPointType pt(&m_FixedLandmarks[i]); - fixedITKPoints.push_back(pt); - } + fixedITKPoints = sitkSTLVectorToITKPointVector(m_FixedLandmarks); filter->SetFixedLandmarks(fixedITKPoints); PointContainer movingITKPoints; - for( unsigned int i = 0; i < m_MovingLandmarks.size()- Dimension - 1; i += Dimension) - { - typename FilterType::LandmarkPointType pt(&m_MovingLandmarks[i]); - movingITKPoints.push_back(pt); - } + movingITKPoints = sitkSTLVectorToITKPointVector(m_MovingLandmarks); filter->SetMovingLandmarks(movingITKPoints); filter->SetLandmarkWeight ( this->m_LandmarkWeight ); diff --git a/Code/Common/include/sitkTemplateFunctions.h b/Code/Common/include/sitkTemplateFunctions.h index c9a5ea074..a3866f161 100644 --- a/Code/Common/include/sitkTemplateFunctions.h +++ b/Code/Common/include/sitkTemplateFunctions.h @@ -60,6 +60,24 @@ SITKCommon_HIDDEN std::ostream & operator<<( std::ostream & os, const std::vecto return os << v.back() << " ]"; } +template< typename TITKPointVector, typename TType> +TITKPointVector SITKCommon_HIDDEN sitkSTLVectorToITKPointVector( const std::vector< TType > & in ) +{ + + typedef TITKPointVector itkPointVectorType; + itkPointVectorType out; + + unsigned int Dimension = itkPointVectorType::value_type::GetPointDimension(); + + for( unsigned int i = 0; i <= in.size()- Dimension; i += Dimension ) + { + typename itkPointVectorType::value_type pt(&in[i]); + out.push_back(pt); + } + return out; + +} + /** \brief Copy the elements of an std::vector into an ITK fixed width vector * * If there are more elements in paramter "in" than the templated ITK diff --git a/Testing/Unit/sitkBasicFiltersTests.cxx b/Testing/Unit/sitkBasicFiltersTests.cxx index 9e6e22be1..c63ac9892 100644 --- a/Testing/Unit/sitkBasicFiltersTests.cxx +++ b/Testing/Unit/sitkBasicFiltersTests.cxx @@ -665,12 +665,30 @@ TEST(BasicFilters,LandmarkBasedTransformInitializer) { out = filter.Execute( sitk::AffineTransform(2) ); - EXPECT_VECTOR_DOUBLE_NEAR(v6(1.0, 0.0, 0.0, 1.0, 0.0, 0.0), out.GetParameters(), 1e-15); - - + EXPECT_VECTOR_DOUBLE_NEAR(v6(1.0, 0.0, 0.0, 1.0, 0.0, 0.0), out.GetParameters(), 1e-8); + + const double fixedImagePoints3d[] = {127.53915086334257, 102.12639903012848, 44.0, + 198.641578144495, 101.59971438360141, 44.0, + 156.82957119036902, 215.70110997158648, 48.0, + 176.63477775277258, 144.97363079485118, 64.0}; + + const double movingImagePoints3d[] = {181.40169895047495, 242.55513079230616, 24.0, + 112.90638157274341, 246.938831104481, 24.0, + 141.07588005861425, 134.62809649982117, 28.0, + 126.66162032855607, 208.7334122120106, 44.0}; + fixedPoints.clear(); + fixedPoints.insert(fixedPoints.begin(), &fixedImagePoints3d[0], &fixedImagePoints3d[12]); + movingPoints.clear(); + movingPoints.insert(movingPoints.begin(), &movingImagePoints3d[0], &movingImagePoints3d[12]); + filter.SetFixedLandmarks( fixedPoints ); + filter.SetMovingLandmarks( movingPoints ); out = filter.Execute( sitk::AffineTransform(3) ); + EXPECT_VECTOR_DOUBLE_NEAR(v12(-9.64081213e-01, -1.01003445e-01, -1.54009453e-01, + 5.44421946e-02, -9.73501195e-01, 2.60861955e-01, + -2.64945988e-14, -3.95920761e-14, 1.00000000e+00, + 321.45133233, 323.55386506, -20.0), out.GetParameters(), 1e-8); } From 4a56576c4be94e4644deb598c3724ca0390fc74d Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Mon, 23 Nov 2015 15:43:55 -0500 Subject: [PATCH 107/412] Fix for CMake CMP0064 warning CMake 3.4 gives a warning when ${test_type} is equal to "TEST". This is because TEST is now a operator in if() statements. The fix matches the version of this file that will be part of CMake 3.4.1. Change-Id: I7cac7affa3c1a2fe451b3e00f85f8c63b7e4c64b --- CMake/FindGTest.cmake | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CMake/FindGTest.cmake b/CMake/FindGTest.cmake index 1940b5af8..55b0edfbc 100644 --- a/CMake/FindGTest.cmake +++ b/CMake/FindGTest.cmake @@ -124,11 +124,11 @@ function(GTEST_ADD_TESTS executable extra_args) string(REGEX MATCH "${gtest_test_type_regex}" test_type ${hit}) # Parameterized tests have a different signature for the filter - if(${test_type} STREQUAL "TEST_P") + if("x${test_type}" STREQUAL "xTEST_P") string(REGEX REPLACE ${gtest_case_name_regex} "*/\\1.\\2/*" test_name ${hit}) - elseif(${test_type} STREQUAL "TEST_F" OR ${test_type} STREQUAL "TEST") + elseif("x${test_type}" STREQUAL "xTEST_F" OR "x${test_type}" STREQUAL "xTEST") string(REGEX REPLACE ${gtest_case_name_regex} "\\1.\\2" test_name ${hit}) - elseif(${test_type} STREQUAL "TYPED_TEST") + elseif("x${test_type}" STREQUAL "xTYPED_TEST") string(REGEX REPLACE ${gtest_case_name_regex} "\\1/*.\\2" test_name ${hit}) else() message(WARNING "Could not parse GTest ${hit} for adding to CTest.") From 79b147a0193e37886d333d4b49be3690aa9528f4 Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Fri, 13 Nov 2015 16:20:26 +1100 Subject: [PATCH 108/412] Use ExternalData for R data Adding new SimpleITKRPackageData target to download data with the ExternalData CMake module. Change-Id: I5d424d7719c077e2018fffa8c039e6bfdbf33ebc --- CMakeLists.txt | 6 ++++-- Wrapping/R/CMakeLists.txt | 35 ++++++++++++++++++++++++++++++++--- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 008e5c0b8..bc439e9e5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -551,6 +551,8 @@ set(CPACK_PACKAGE_VERSION_PATCH "${SimpleITK_Patch}") include( CPack ) -if(COMMAND ExternalData_Add_Target ) - ExternalData_Add_Target( SimpleITKData ) +if(BUILD_TESTING) + if(COMMAND ExternalData_Add_Target ) + ExternalData_Add_Target( SimpleITKData ) + endif() endif() diff --git a/Wrapping/R/CMakeLists.txt b/Wrapping/R/CMakeLists.txt index 04674f299..3a647d662 100644 --- a/Wrapping/R/CMakeLists.txt +++ b/Wrapping/R/CMakeLists.txt @@ -26,6 +26,8 @@ file(TO_NATIVE_PATH "${SIMPLEITKR_BINARY_MODULE}" SIMPLEITKR_NATIVE_BINARY_MODUL set_target_properties( ${SWIG_MODULE_SimpleITK_TARGET_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/src/) sitk_strip_target( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ) +set(SWIG_MODULE_SimpleITKR_TARGET_NAME "${SWIG_MODULE_SimpleITK_TARGET_NAME}") + # copy the R files a binary package add_custom_command( TARGET ${SWIG_MODULE_SimpleITK_TARGET_NAME} @@ -33,13 +35,40 @@ add_custom_command( TARGET ${SWIG_MODULE_SimpleITK_TARGET_NAME} COMMAND ${CMAKE_COMMAND} -E copy_directory ${SimpleITK_SOURCE_DIR}/Wrapping/R/Packaging ${CMAKE_CURRENT_BINARY_DIR}/Packaging COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/data/ ) + +# download sample images, if allowed +if(NOT SITK_FORBID_DOWNLOADS) + include(sitkExternalData) + + foreach(link ${SimpleITK_SOURCE_DIR}/Testing/Data/Input/cthead1.png.md5 ${SimpleITK_SOURCE_DIR}/Testing/Data/Input/cthead1-Float.mha.md5) + string( REGEX REPLACE "\\.md5$" "" link ${link} ) + ExternalData_Expand_Arguments( SimpleITKRpackageData + link_location + DATA{${link}} + ) + set( COPY_DATA_COMMAND ${COPY_DATA_COMMAND} COMMAND ${CMAKE_COMMAND} -E copy ${link_location} ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/data/ ) + + endforeach() + + if(COMMAND ExternalData_Add_Target ) + ExternalData_Add_Target( SimpleITKRpackageData ) + endif() + add_dependencies( ${SWIG_MODULE_SimpleITK_TARGET_NAME} SimpleITKRpackageData ) + + # copy sample images - used in vignette + ## can't use file(copy as the sources are symbolic links + add_custom_command( TARGET ${SWIG_MODULE_SimpleITK_TARGET_NAME} + PRE_BUILD + ${COPY_DATA_COMMAND} + ) + +endif() + + add_custom_command( TARGET ${SWIG_MODULE_SimpleITK_TARGET_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/R_libs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/SimpleITK.R ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/R/ - # copy sample images - COMMAND ${CMAKE_COMMAND} -E copy ${SimpleITK_BINARY_DIR}/ExternalData/Testing/Data/Input/cthead1.png ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/data/ - COMMAND ${CMAKE_COMMAND} -E copy ${SimpleITK_BINARY_DIR}/ExternalData/Testing/Data/Input/cthead1-Float.mha ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/data/ # install for running tests and create binary package COMMAND ${R_COMMAND} CMD INSTALL --build ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK --library=${CMAKE_CURRENT_BINARY_DIR}/R_libs COMMENT "Installing R package for testing and building binary version for distribution" From 9d4d3f4c967475827b1c2018b6e98e258b56d64b Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 30 Nov 2015 14:27:11 -0500 Subject: [PATCH 109/412] Adding script to run doxyall for generate SWIG .i files Adding driver script to help generate SWIG .i documentation files Change-Id: Ifc146c97cf133afdd78a540b4aa1944db1d55b17 --- Utilities/BuildDocs | 23 ----------------------- Utilities/UpdateSwigFromDoxygen.sh | 6 ++++++ 2 files changed, 6 insertions(+), 23 deletions(-) delete mode 100755 Utilities/BuildDocs create mode 100755 Utilities/UpdateSwigFromDoxygen.sh diff --git a/Utilities/BuildDocs b/Utilities/BuildDocs deleted file mode 100755 index 300ddc5ee..000000000 --- a/Utilities/BuildDocs +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/sh - -# Sanity -if [ ! -e Code/BasicFilters/json/ ]; then - echo "This script must be run for the root of SimpleITK's checkout (Utilities/BuildDocs )" - exit 1 -fi - -if [ ! -e $1/Utilities/Doxygen/xml/itkImage_8h.xml ]; then - echo "The first argument must be the root of an ITK build with XML documentation generated" - exit 1 -fi - -rm -f Wrapping/PythonDocstrings.i -rm -f Wrapping/JavaDoc.i - -# Find all the JSON, re-write it -for f in Code/BasicFilters/json/*.json; do - Utilities/GenerateDocumentation.groovy $f $1 Wrapping/PythonDocstrings.i Wrapping/JavaDoc.i - - # run the python script to return to standard formatting - Utilities/JSONInputAToInputs.py $f -done diff --git a/Utilities/UpdateSwigFromDoxygen.sh b/Utilities/UpdateSwigFromDoxygen.sh new file mode 100755 index 000000000..2bc757028 --- /dev/null +++ b/Utilities/UpdateSwigFromDoxygen.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +SITK_BUILD_DIR="/dev/shm/SimpleITK/SimpleITK-build" + +Doxygen/doxyall.py ${SITK_BUILD_DIR}/Documentation/xml/ ../Wrapping/Python/PythonDocstrings.i +Doxygen/doxyall.py -j ${SITK_BUILD_DIR}/Documentation/xml/ ../Wrapping/Java/JavaDoc.i From a05e158822bf0262d75429724dc855cfc7f49484 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 30 Nov 2015 15:30:08 -0500 Subject: [PATCH 110/412] Adding script to update JSON with ITK doxygen Change-Id: I824d42566363115e6a816ea4f2ebd81ea6e8a8cb --- Utilities/JSONBeautify.py | 25 +++++++++++++++++++++++++ Utilities/JSONDocUpdate.sh | 10 ++++++++++ 2 files changed, 35 insertions(+) create mode 100755 Utilities/JSONBeautify.py create mode 100755 Utilities/JSONDocUpdate.sh diff --git a/Utilities/JSONBeautify.py b/Utilities/JSONBeautify.py new file mode 100755 index 000000000..4fb985e9b --- /dev/null +++ b/Utilities/JSONBeautify.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +import json +import sys +try: + from collections import OrderedDict +except ImportError: + import ordereddict as OrderedDict + +# This script takes one argument the name of a json file. +# + + +fname = sys.argv[1] + +print "Processing ", fname + +fp = file( fname, "r" ) +j = json.load( fp,object_pairs_hook=OrderedDict ) +fp.close() + + +fp = file( fname, "w" ) +json.dump( j, fp, indent=2, separators=(',',' : ') ) +print >>fp, "" +fp.close() diff --git a/Utilities/JSONDocUpdate.sh b/Utilities/JSONDocUpdate.sh new file mode 100755 index 000000000..bf7aaa554 --- /dev/null +++ b/Utilities/JSONDocUpdate.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + + +GROOVEY="/usr/bin/groovy" +SIMPLEITK="${HOME}/src/SimpleITK" +ITK_XML="${HOME}/temp/xml" + + +${GROOVEY} "${SIMPLEITK}/Utilities/GenerateDocumentation.groovy" "$1" ${ITK_XML} +python "${SIMPLEITK}/Utilities/JSONBeautify.py" $1 From 667d90838f6e73135272ad9b357b009c759271cf Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 1 Dec 2015 13:15:14 -0500 Subject: [PATCH 111/412] Moving documentation generations scripts to separate directory --- Utilities/{ => GenerateDocs}/GenerateDocumentation.groovy | 0 Utilities/{ => GenerateDocs}/JSONDocUpdate.sh | 0 Utilities/{ => GenerateDocs}/UpdateSwigFromDoxygen.sh | 0 Utilities/{Doxygen => GenerateDocs}/doxy2swig.py | 0 Utilities/{Doxygen => GenerateDocs}/doxyall.py | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename Utilities/{ => GenerateDocs}/GenerateDocumentation.groovy (100%) rename Utilities/{ => GenerateDocs}/JSONDocUpdate.sh (100%) rename Utilities/{ => GenerateDocs}/UpdateSwigFromDoxygen.sh (100%) rename Utilities/{Doxygen => GenerateDocs}/doxy2swig.py (100%) rename Utilities/{Doxygen => GenerateDocs}/doxyall.py (100%) diff --git a/Utilities/GenerateDocumentation.groovy b/Utilities/GenerateDocs/GenerateDocumentation.groovy similarity index 100% rename from Utilities/GenerateDocumentation.groovy rename to Utilities/GenerateDocs/GenerateDocumentation.groovy diff --git a/Utilities/JSONDocUpdate.sh b/Utilities/GenerateDocs/JSONDocUpdate.sh similarity index 100% rename from Utilities/JSONDocUpdate.sh rename to Utilities/GenerateDocs/JSONDocUpdate.sh diff --git a/Utilities/UpdateSwigFromDoxygen.sh b/Utilities/GenerateDocs/UpdateSwigFromDoxygen.sh similarity index 100% rename from Utilities/UpdateSwigFromDoxygen.sh rename to Utilities/GenerateDocs/UpdateSwigFromDoxygen.sh diff --git a/Utilities/Doxygen/doxy2swig.py b/Utilities/GenerateDocs/doxy2swig.py similarity index 100% rename from Utilities/Doxygen/doxy2swig.py rename to Utilities/GenerateDocs/doxy2swig.py diff --git a/Utilities/Doxygen/doxyall.py b/Utilities/GenerateDocs/doxyall.py similarity index 100% rename from Utilities/Doxygen/doxyall.py rename to Utilities/GenerateDocs/doxyall.py From e88addd78eaec31bd1b344f5b417d6311665962d Mon Sep 17 00:00:00 2001 From: Ziv Yaniv Date: Tue, 1 Dec 2015 13:34:55 -0500 Subject: [PATCH 112/412] BUG: Fixed crash when reference image is not set for BSpline initialization. The SimpleITK filter checks that the reference image is set if we are initializing a BSplineTransform. Also updated the interface so that the data is passed by reference and not value. Change-Id: I0ab20d9e39994667f7defda3f376498d14713a86 --- ...kLandmarkBasedTransformInitializerFilter.h | 14 +++--- ...andmarkBasedTransformInitializerFilter.cxx | 23 +++++---- Testing/Unit/sitkBasicFiltersTests.cxx | 50 +++++++++++++++++++ 3 files changed, 70 insertions(+), 17 deletions(-) diff --git a/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h b/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h index 3162f3071..4d7dc2c22 100644 --- a/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h +++ b/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h @@ -76,7 +76,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co /** * Set the Fixed landmark point containers */ - Self& SetFixedLandmarks ( std::vector FixedLandmarks ) { this->m_FixedLandmarks = FixedLandmarks; return *this; } + Self& SetFixedLandmarks ( const std::vector & FixedLandmarks ) { this->m_FixedLandmarks = FixedLandmarks; return *this; } /** * @@ -86,7 +86,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co /** * Set the Moving landmark point containers */ - Self& SetMovingLandmarks ( std::vector MovingLandmarks ) { this->m_MovingLandmarks = MovingLandmarks; return *this; } + Self& SetMovingLandmarks ( const std::vector & MovingLandmarks ) { this->m_MovingLandmarks = MovingLandmarks; return *this; } /** * Get the shrink factors. @@ -96,7 +96,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co /** * Set the landmark weight point containers Weight includes diagonal elements of weight matrix */ - Self& SetLandmarkWeight ( std::vector LandmarkWeight ) { this->m_LandmarkWeight = LandmarkWeight; return *this; } + Self& SetLandmarkWeight ( const std::vector & LandmarkWeight ) { this->m_LandmarkWeight = LandmarkWeight; return *this; } /** * @@ -106,19 +106,19 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co /** * Set the reference image to define the parametric domain for the BSpline transform */ - Self& SetReferenceImage ( Image ReferenceImage ) { this->m_ReferenceImage = ReferenceImage; return *this; } + Self& SetReferenceImage ( const Image & ReferenceImage ) { this->m_ReferenceImage = ReferenceImage; return *this; } /** */ Image GetReferenceImage() const { return this->m_ReferenceImage; } /** - * Set/Get the number of iterations + * Set/Get the number of control points */ Self& SetBSplineNumberOfControlPoints ( unsigned int BSplineNumberOfControlPoints ) { this->m_BSplineNumberOfControlPoints = BSplineNumberOfControlPoints; return *this; } /** - * Set/Get the number of iterations + * Set/Get the number of control points */ unsigned int GetBSplineNumberOfControlPoints() const { return this->m_BSplineNumberOfControlPoints; } /** Name of this class */ @@ -133,7 +133,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co /** Execute the filter on the input image with the given parameters */ - Transform Execute ( const Transform & transform, std::vector fixedLandmarks, std::vector movingLandmarks, std::vector landmarkWeight, Image referenceImage, unsigned int numberOfControlPoints ); + Transform Execute ( const Transform & transform, const std::vector & fixedLandmarks, const std::vector & movingLandmarks, const std::vector & landmarkWeight, const Image & referenceImage, unsigned int numberOfControlPoints ); private: diff --git a/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx b/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx index 228592ca9..ddd82e957 100644 --- a/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx +++ b/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx @@ -58,9 +58,6 @@ LandmarkBasedTransformInitializerFilter::LandmarkBasedTransformInitializerFilter this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > (); this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > (); - - - } // @@ -103,7 +100,7 @@ std::string LandmarkBasedTransformInitializerFilter::ToString() const // // Execute // -Transform LandmarkBasedTransformInitializerFilter::Execute ( const Transform & transform, std::vector fixedLandmarks, std::vector movingLandmarks, std::vector landmarkWeight, Image referenceImage, unsigned int numberOfControlPoints ) +Transform LandmarkBasedTransformInitializerFilter::Execute ( const Transform & transform, const std::vector & fixedLandmarks, const std::vector & movingLandmarks, const std::vector & landmarkWeight, const Image & referenceImage, unsigned int numberOfControlPoints ) { this->SetFixedLandmarks ( fixedLandmarks ); this->SetMovingLandmarks ( movingLandmarks ); @@ -119,6 +116,8 @@ Transform LandmarkBasedTransformInitializerFilter::Execute ( const Transform & t { unsigned int dimension = transform.GetDimension(); + // The dimension of the reference image which the user explicitly + // set (GetSize()!=[0...0]), and the dimension of the transform do not match if ( this->m_ReferenceImage.GetSize() != std::vector(this->m_ReferenceImage.GetDimension(), 0u) && dimension != this->m_ReferenceImage.GetDimension() ) { @@ -163,6 +162,7 @@ Transform LandmarkBasedTransformInitializerFilter::ExecuteInternal ( const Trans const typename FilterType::TransformType *itkTx = dynamic_cast(copyTransform.GetITKBase()); + if ( !itkTx ) { sitkExceptionMacro( "Unexpected error converting transform! Possible miss matching dimensions!" ); @@ -182,16 +182,19 @@ Transform LandmarkBasedTransformInitializerFilter::ExecuteInternal ( const Trans filter->SetLandmarkWeight ( this->m_LandmarkWeight ); - if ( this->m_ReferenceImage.GetSize() != std::vector(this->m_ReferenceImage.GetDimension(), 0u) ) + // BSpline specific setup + if( itkTx->GetTransformCategory() == itkTx->BSpline ) { + if ( this->m_ReferenceImage.GetSize() == std::vector(this->m_ReferenceImage.GetDimension(), 0u) ) + { + sitkExceptionMacro( "Image not set for BSplineTransform initializer." ); + } // Get the pointer to the ITK image contained in image1 typename InputImageType::ConstPointer referenceImage = this->CastImageToITK( this->m_ReferenceImage ); - ////filter->SetReferenceImage ( referenceImage.GetPointer() ); + filter->SetReferenceImage ( referenceImage.GetPointer() ); + filter->SetBSplineNumberOfControlPoints ( this->m_BSplineNumberOfControlPoints ); } - filter->SetBSplineNumberOfControlPoints ( this->m_BSplineNumberOfControlPoints ); - - if (this->GetDebug()) { std::cout << "Executing ITK filter:" << std::endl; @@ -210,7 +213,7 @@ Transform LandmarkBasedTransformInitializerFilter::ExecuteInternal ( const Trans // // Function to run the Execute method of this filter // -Transform LandmarkBasedTransformInitializer ( const Transform & transform, std::vector fixedLandmarks, std::vector movingLandmarks, std::vector landmarkWeight, Image referenceImage, unsigned int numberOfControlPoints ) +Transform LandmarkBasedTransformInitializer ( const Transform & transform, const std::vector & fixedLandmarks, const std::vector & movingLandmarks, const std::vector & landmarkWeight, Image referenceImage, unsigned int numberOfControlPoints ) { LandmarkBasedTransformInitializerFilter filter; return filter.Execute ( transform, fixedLandmarks, movingLandmarks, landmarkWeight, referenceImage, numberOfControlPoints ); diff --git a/Testing/Unit/sitkBasicFiltersTests.cxx b/Testing/Unit/sitkBasicFiltersTests.cxx index c63ac9892..af8ff1606 100644 --- a/Testing/Unit/sitkBasicFiltersTests.cxx +++ b/Testing/Unit/sitkBasicFiltersTests.cxx @@ -689,6 +689,56 @@ TEST(BasicFilters,LandmarkBasedTransformInitializer) { 5.44421946e-02, -9.73501195e-01, 2.60861955e-01, -2.64945988e-14, -3.95920761e-14, 1.00000000e+00, 321.45133233, 323.55386506, -20.0), out.GetParameters(), 1e-8); + + const double pointsBSplineTest2D[] = {0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.1, 1.0, 2.34, 10.98}; + fixedPoints.clear(); + fixedPoints.insert(fixedPoints.begin(), &pointsBSplineTest2D[0], &pointsBSplineTest2D[10]); + movingPoints.clear(); + movingPoints.insert(movingPoints.begin(), &pointsBSplineTest2D[0], &pointsBSplineTest2D[10]); + filter.SetFixedLandmarks( fixedPoints ); + filter.SetMovingLandmarks( movingPoints ); + filter.SetBSplineNumberOfControlPoints( 5 ); + + // Image isn't set so we expect an exception + EXPECT_ANY_THROW( filter.Execute( sitk::BSplineTransform( 2 ) ) ); + + std::vector< double > spacing; + spacing.push_back(0.5); + spacing.push_back(1); + std::vector< double > origin; + origin.push_back(-5.0); + origin.push_back(-5.0); + sitk::Image referenceImage( 25, 50, sitk::sitkFloat32 ); + referenceImage.SetSpacing( spacing ); + referenceImage.SetOrigin( origin ); + filter.SetReferenceImage( referenceImage ); + + // Expecting the identity transform (BSpline parameters are all zero) + out = filter.Execute(sitk::BSplineTransform(2)); + EXPECT_VECTOR_DOUBLE_NEAR(std::vector(out.GetParameters().size(), 0.0), out.GetParameters(), 1e-25); + + // Translate the moving points in the x direction + double dxSize = 3.5; + for( unsigned int i = 0; i Date: Wed, 2 Dec 2015 16:22:54 -0500 Subject: [PATCH 113/412] COMP: fixed failed wrapping due to method signature differences The parameters were passed as const references in the implementation but forgot to update this in the header. Change-Id: I3bb026b058cbd02848c00562f4077aa1f01d561a --- .../include/sitkLandmarkBasedTransformInitializerFilter.h | 2 +- .../src/sitkLandmarkBasedTransformInitializerFilter.cxx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h b/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h index 4d7dc2c22..62723214f 100644 --- a/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h +++ b/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h @@ -170,7 +170,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co * * \sa itk::simple::LandmarkBasedTransformInitializerFilter for the object oriented interface */ - SITKBasicFilters_EXPORT Transform LandmarkBasedTransformInitializer ( const Transform & transform, std::vector fixedLandmarks = std::vector(), std::vector movingLandmarks = std::vector(), std::vector landmarkWeight = std::vector(), Image referenceImage = Image(), unsigned int numberOfControlPoints = 4u ); + SITKBasicFilters_EXPORT Transform LandmarkBasedTransformInitializer ( const Transform & transform, const std::vector & fixedLandmarks = std::vector(), const std::vector & movingLandmarks = std::vector(), const std::vector & landmarkWeight = std::vector(), const Image & referenceImage = Image(), unsigned int numberOfControlPoints = 4u ); } } diff --git a/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx b/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx index ddd82e957..535b249f3 100644 --- a/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx +++ b/Code/BasicFilters/src/sitkLandmarkBasedTransformInitializerFilter.cxx @@ -213,7 +213,7 @@ Transform LandmarkBasedTransformInitializerFilter::ExecuteInternal ( const Trans // // Function to run the Execute method of this filter // -Transform LandmarkBasedTransformInitializer ( const Transform & transform, const std::vector & fixedLandmarks, const std::vector & movingLandmarks, const std::vector & landmarkWeight, Image referenceImage, unsigned int numberOfControlPoints ) +Transform LandmarkBasedTransformInitializer ( const Transform & transform, const std::vector & fixedLandmarks, const std::vector & movingLandmarks, const std::vector & landmarkWeight, const Image & referenceImage, unsigned int numberOfControlPoints ) { LandmarkBasedTransformInitializerFilter filter; return filter.Execute ( transform, fixedLandmarks, movingLandmarks, landmarkWeight, referenceImage, numberOfControlPoints ); From e5941a6b24742e5fa76b22e28a0f3f755e2661f8 Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Tue, 27 Oct 2015 10:41:22 +1100 Subject: [PATCH 114/412] Use member function syntax to call member functions Fixes to avoid garbage collection problems. The use of the return of "this" may cause garbage collection issues. Change-Id: Ia74b234a76e09801bca6cb665a30c4431d3126c8 --- Examples/SimpleGaussian.R | 18 +++++++++--------- Testing/Unit/RImageFilterTestTemplate.R.in | 15 ++++++++------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/Examples/SimpleGaussian.R b/Examples/SimpleGaussian.R index 0ee4de518..11173a8b5 100644 --- a/Examples/SimpleGaussian.R +++ b/Examples/SimpleGaussian.R @@ -25,20 +25,20 @@ library(SimpleITK) args <- commandArgs( TRUE ) myreader <- ImageFileReader() -myreader <- ImageFileReader_SetFileName( myreader, args[[1]] ) -myimage <- ImageFileReader_Execute( myreader ) +myreader$SetFileName(args[[1]] ) +myimage <- myreader$Execute() -pixeltype <- Image_GetPixelID( myimage ) +pixeltype <- myimage$GetPixelID() myfilter <- SmoothingRecursiveGaussianImageFilter() -myfilter <- SmoothingRecursiveGaussianImageFilter_SetSigma( myfilter, as.numeric(args[2]) ) -smoothedimage <- SmoothingRecursiveGaussianImageFilter_Execute( myfilter, myimage ) +myfilter$SetSigma(as.numeric(args[2]) ) +smoothedimage <- myfilter$Execute(myimage ) mycaster <- CastImageFilter() -mycaster <- CastImageFilter_SetOutputPixelType( mycaster, pixeltype ) -castedimage <- CastImageFilter_Execute( mycaster, smoothedimage ) +mycaster$SetOutputPixelType(pixeltype ) +castedimage <- mycaster$Execute(smoothedimage ) mywriter <- ImageFileWriter() -mywriter <- ImageFileWriter_SetFileName( mywriter, args[[3]] ) -mywriter <- ImageFileWriter_Execute( mywriter, castedimage ) +mywriter$SetFileName(args[[3]] ) +mywriter$Execute(castedimage ) diff --git a/Testing/Unit/RImageFilterTestTemplate.R.in b/Testing/Unit/RImageFilterTestTemplate.R.in index 5bd5f5e07..37a227c6b 100644 --- a/Testing/Unit/RImageFilterTestTemplate.R.in +++ b/Testing/Unit/RImageFilterTestTemplate.R.in @@ -44,7 +44,8 @@ if ( numberOfArguments < inputs + 2) { } tag <- args[[1]] - +# Turn this on for a slow but through testing +#gctorture() writer <- ImageFileWriter() filter <- ${name}() @@ -63,14 +64,14 @@ if(tag == "${tag}") { $(foreach settings $(if parameter == "SeedList" then OUT=[[ - filter <- filter$$ClearSeeds() + filter$$ClearSeeds() $(for i=1,#value do - OUT=OUT .. "filter <- filter$$AddSeed( " .. R_value[i] .. " )\n" + OUT=OUT .. "filter$$AddSeed( " .. R_value[i] .. " )\n" end) ]] elseif R_value then OUT=[[ - filter <- filter$$Set${parameter}( ${R_value} ) + filter$$Set${parameter}( ${R_value} ) ]] elseif dim_vec and dim_vec==1 then OUT=[[ @@ -81,7 +82,7 @@ OUT=[[ OUT=OUT..value[#value]..' ) )' else OUT=[[ - filter <- filter$$Set${parameter}( ${value} ) + filter$$Set${parameter}( ${value} ) ]] end) ) @@ -114,8 +115,8 @@ OUT=[[ output <- LabelMapToLabel(output) } - writer <- writer$$SetFileName( lastargument ) - writer <- writer$$Execute( output ) + writer$$SetFileName( lastargument ) + writer$$Execute( output ) ]] end) From 4f3b8a42d17b603f892e48c0b2b20bc6dd25b01b Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 2 Dec 2015 09:10:59 -0500 Subject: [PATCH 115/412] Adding common variable/config file for scripts Enable download of the nightly ITK Doxygen XML if needed. Change-Id: Iebda3e86af80cab0e0675cd0a9db4b927850e9db --- Utilities/GenerateDocs/JSONDocUpdate.sh | 38 +++++++++++++++++++++---- Utilities/GenerateDocs/config_vars.sh | 12 ++++++++ 2 files changed, 45 insertions(+), 5 deletions(-) create mode 100644 Utilities/GenerateDocs/config_vars.sh diff --git a/Utilities/GenerateDocs/JSONDocUpdate.sh b/Utilities/GenerateDocs/JSONDocUpdate.sh index bf7aaa554..05c4ad724 100755 --- a/Utilities/GenerateDocs/JSONDocUpdate.sh +++ b/Utilities/GenerateDocs/JSONDocUpdate.sh @@ -1,10 +1,38 @@ #!/usr/bin/env bash +# Updates the documentation strings in the JSON files from the ITK Doxygen. +# +# Configuration for directories need to be manually done in the +# config_vars.sh file. The ITK Doxygen XML will automatically be +# downloaded if needed. +# +# Usage: JSONDocUpdate.sh Code/BasicFilters/json/SomeFilter.json +# -GROOVEY="/usr/bin/groovy" -SIMPLEITK="${HOME}/src/SimpleITK" -ITK_XML="${HOME}/temp/xml" +die() { + echo "$@" 1>&2 + exit 1 +} +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -${GROOVEY} "${SIMPLEITK}/Utilities/GenerateDocumentation.groovy" "$1" ${ITK_XML} -python "${SIMPLEITK}/Utilities/JSONBeautify.py" $1 +# Load configuration variable from file +. ${DIR}/config_vars.sh || die 'Unable to find local \"config_vars.sh\" configuration file.' + +# Download the nightly Doxygen XML if needed +[ -e ${ITK_XML}/itkImage_8h.xml ] || + ( cd ${ITK_XML} && + echo "Downloading ITK Doxygen XML..." && + curl -O http://public.kitware.com/pub/itk/NightlyDoxygen/InsightDoxygenDocXml.tar.gz && + cd .. && + tar -zxf xml/InsightDoxygenDocXml.tar.gz ) || + die 'Unable to get ITK Doxygen XML' + +# Does the work of extracting the string from the XML, and putting them into the JSON +${GROOVEY_EXECUTABLE} "${DIR}/GenerateDocumentation.groovy" "$1" ${ITK_XML} || + die 'Error running GenerateDocumentation.groovy' + + +# Perform standard formatting of the JSON file +${PYTHON_EXECUTABLE} "${SIMPLEITK}/Utilities/JSONBeautify.py" $1 || + die 'Error Beautifying json file $1' diff --git a/Utilities/GenerateDocs/config_vars.sh b/Utilities/GenerateDocs/config_vars.sh new file mode 100644 index 000000000..640874134 --- /dev/null +++ b/Utilities/GenerateDocs/config_vars.sh @@ -0,0 +1,12 @@ +#! /bin/sh + + +GROOVEY_EXECUTABLE="groovy" + +SIMPLEITK="${HOME}/src/SimpleITK" + +ITK_XML="${HOME}/temp/xml" + +SITK_BUILD_DIR="/dev/shm/SimpleITK/SimpleITK-build" + +PYTHON_EXECUTABLE="python" From 42fd317858880ef598b81c50faa734df5af0b2a7 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 4 Dec 2015 15:46:30 -0500 Subject: [PATCH 116/412] Generalizing script to generate Swig .i documentation files Change-Id: I870900501e4cfcef01cc479d3a3b982c8ff8eaf3 --- Utilities/GenerateDocs/SwigDocUpdate.sh | 29 +++++++++++++++++++ .../GenerateDocs/UpdateSwigFromDoxygen.sh | 6 ---- 2 files changed, 29 insertions(+), 6 deletions(-) create mode 100755 Utilities/GenerateDocs/SwigDocUpdate.sh delete mode 100755 Utilities/GenerateDocs/UpdateSwigFromDoxygen.sh diff --git a/Utilities/GenerateDocs/SwigDocUpdate.sh b/Utilities/GenerateDocs/SwigDocUpdate.sh new file mode 100755 index 000000000..a2e520597 --- /dev/null +++ b/Utilities/GenerateDocs/SwigDocUpdate.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash + + +# Updates Swig .i documentation files from SimpleITK's Doxygen XML. +# +# To generate the input to this script, the SimpleITK Doxygen must be built. +# +# Configuration for directories need to be manually done in the +# config_vars.sh file. The ITK Doxygen XML will automatically be +# downloaded if needed. +# +# Usage: SWigDocUpdate.sh +# + +die() { + echo "$@" 1>&2 + exit 1 +} + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +# Load configuration variable from file +. ${DIR}/config_vars.sh || die 'Unable to find local \"config_vars.sh\" configuration file.' + +[ -e ${SITK_BUILD_DIR}/Documentation/xml/sitkImage_8h.xml ] || + die "Uable to find SimpleITK Doxygen XML! SimpleITK Doxygen needs to be generated with the Documentation target!" + +${PYTHON_EXECUTABLE} doxyall.py ${SITK_BUILD_DIR}/Documentation/xml/ ${SIMPLEITK}/Wrapping/Python/PythonDocstrings.i +${PYTHON_EXECUTABLE} doxyall.py -j ${SITK_BUILD_DIR}/Documentation/xml/ ${SIMPLEITK}/Wrapping/Java/JavaDoc.i diff --git a/Utilities/GenerateDocs/UpdateSwigFromDoxygen.sh b/Utilities/GenerateDocs/UpdateSwigFromDoxygen.sh deleted file mode 100755 index 2bc757028..000000000 --- a/Utilities/GenerateDocs/UpdateSwigFromDoxygen.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash - -SITK_BUILD_DIR="/dev/shm/SimpleITK/SimpleITK-build" - -Doxygen/doxyall.py ${SITK_BUILD_DIR}/Documentation/xml/ ../Wrapping/Python/PythonDocstrings.i -Doxygen/doxyall.py -j ${SITK_BUILD_DIR}/Documentation/xml/ ../Wrapping/Java/JavaDoc.i From 2469b8ccc2a231c1e116855ddb2e81135c273136 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 4 Dec 2015 16:03:06 -0500 Subject: [PATCH 117/412] Adding README for the GenerateDocs directory Change-Id: I1c822fcd002cd478a88bb947b84c792b05f8e5e6 --- Utilities/GenerateDocs/README | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Utilities/GenerateDocs/README diff --git a/Utilities/GenerateDocs/README b/Utilities/GenerateDocs/README new file mode 100644 index 000000000..e90a4bfc3 --- /dev/null +++ b/Utilities/GenerateDocs/README @@ -0,0 +1,10 @@ +This directory contains scripts used to process and generate documentation for SimpleITK. + +Important end use scripts: + JSONDocUpdate.sh - Copies ITK Doxygen into SimpleITK JSON + SwigDocUpdate.sh - Copies SimpleITK Doxygen into Swig .i files + +Configuration: + The config_vars.sh file needs to be manually modified for the system and build configuration. + +These scripts are manually run to modify and create files in the source tree with the derived documentation. From a1728981f39a3a6f38339995d892dcec9b5b2457 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 8 Dec 2015 11:42:17 -0500 Subject: [PATCH 118/412] Add comments and working directories to Py VirtualEnv script Change-Id: Ie1b01db35c9e0ab0ef070572f68eb8b352f5485d --- .../Python/PythonVirtualEnvInstall.cmake.in | 29 ++++++++++++++++--- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/Wrapping/Python/PythonVirtualEnvInstall.cmake.in b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in index b441aa8f6..3a043f5fe 100644 --- a/Wrapping/Python/PythonVirtualEnvInstall.cmake.in +++ b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in @@ -3,6 +3,9 @@ if(POLICY CMP0012) cmake_policy(SET CMP0012 NEW) endif() +# +# Create the Python virtual environment. +# execute_process( COMMAND "@PYTHON_EXECUTABLE@" "@SimpleITK_SOURCE_DIR@/Utilities/virtualenv/virtualenv.py" @@ -11,6 +14,7 @@ execute_process( --no-setuptools --clear "@PythonVirtualenvHome@" + WORKING_DIRECTORY "@SimpleITK_SOURCE_DIR@/Wrapping/Python" RESULT_VARIABLE failed ERROR_VARIABLE error ) @@ -19,19 +23,28 @@ if ( failed ) message( FATAL_ERROR "Creation of Python virtual enviroment failed.\n${error}" ) endif() +# +# Install the SimpleITK Package into the virtual environment. +# message(STATUS "Installing Python Package: SimpleITK") + +# The working directory for the installation and packaging with +# setup.py is very important. As if the setup is run from another +# directory files will not be correctly execute_process. execute_process( COMMAND "@VIRTUAL_PYTHON_EXECUTABLE@" "@CMAKE_CURRENT_BINARY_DIR@/Packaging/setup.py" install + WORKING_DIRECTORY "@SimpleITK_SOURCE_DIR@/Wrapping/Python" RESULT_VARIABLE failed ERROR_VARIABLE error ) + if ( failed ) message( FATAL_ERROR "Installation of SimpleITK into Python virutal enviroment failed.\n${error}" ) endif() if ( "@SimpleITK_PYTHON_WHEEL@" ) - message(STATUS "Installing Python Package: wheel") + set(install_wheel_script " import sys from ez_setup import use_setuptools @@ -41,6 +54,10 @@ if not(sys.modules.get(\"wheel\")): easy_install.main([\"wheel\"]) ") + # + # Install Python wheel package. + # + message(STATUS "Installing Python Package: wheel") execute_process( COMMAND @VIRTUAL_PYTHON_EXECUTABLE@ -c "${install_wheel_script}" WORKING_DIRECTORY "Packaging" @@ -54,6 +71,9 @@ if not(sys.modules.get(\"wheel\")): endif() +# +# Get Python library directory. +# execute_process( COMMAND "@VIRTUAL_PYTHON_EXECUTABLE@" -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())" OUTPUT_VARIABLE PythonVirtualenvLib @@ -63,11 +83,12 @@ execute_process( ) if ( failed ) - message( SEND_ERROR "Determining python library patch failed.\n${error}" ) + message( SEND_ERROR "Determining python library path failed.\n${error}" ) endif() - -# Manual numpy installation +# +# Manual copy the numpy installation into the virtual environment. +# execute_process( COMMAND "@PYTHON_EXECUTABLE@" -c "import numpy; import os; print(os.path.dirname(numpy.__file__))" OUTPUT_VARIABLE numpy_dir From 2d8d1eae2af7c483f242c9019baf4c6bb0cb9227 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 9 Dec 2015 10:27:10 -0500 Subject: [PATCH 119/412] Correct path for Java packaging for the dist target. Change-Id: I1351ecc648fa7cb277371b897cf9bb8713285144 --- Wrapping/Java/dist/CMakeLists.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Wrapping/Java/dist/CMakeLists.txt b/Wrapping/Java/dist/CMakeLists.txt index f637493a3..afbfcf33d 100644 --- a/Wrapping/Java/dist/CMakeLists.txt +++ b/Wrapping/Java/dist/CMakeLists.txt @@ -5,9 +5,9 @@ set(_files "") list( APPEND _files ${SimpleITK_DOC_FILES} - ${SimpleITK_BINARY_DIR}/Wrapping/${JAR_FILE} - ${SimpleITK_BINARY_DIR}/Wrapping/${JAVA_SOURCE_FILE} - ${SimpleITK_BINARY_DIR}/Wrapping/${JAVADOC_FILE} + ${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE} + ${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAVA_SOURCE_FILE} + ${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAVADOC_FILE} ) if(NOT DEFINED SIMPLEITK_JAVA_ARCH) From a9756f857c552dfa9e81e702a0f23130930311e1 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 10 Dec 2015 10:26:53 -0500 Subject: [PATCH 120/412] Adding overview of the documentation process Change-Id: If909b3844c608648eb62048c2dba82f059138853 --- Utilities/GenerateDocs/README | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Utilities/GenerateDocs/README b/Utilities/GenerateDocs/README index e90a4bfc3..f6e9e50ee 100644 --- a/Utilities/GenerateDocs/README +++ b/Utilities/GenerateDocs/README @@ -1,6 +1,21 @@ + This directory contains scripts used to process and generate documentation for SimpleITK. -Important end use scripts: +Overview: +Much of the SimpleITK documentation that is in the form of doxygen strings and +API language docs is derived from ITK's Doxygen. The process starts +when Doxygen is run on ITK and it produces the ITK Doxygen in XML +format. This can either be generated locally or the nightly can be +automatically downloaded. Next the JSONDocUpdate.sh script can be run +to extract the strings from the ITK XML Doxygen and update the +SimpleITK JSON filter descriptions. When SimpleITK is built the JSON +is used as source for the C++ code. Then when SimpleITK's Documentation +target is made, the SimpleITK Doxygen in XML will be generated. Lastly +the SwigDocUpdate.sh script can be run to convert the SimpleITK +Doxygen XML into Swig .i files so that when SimpleITK is built, inline +documenation for some wrapped languages will be available. + +Important end use scripts (see script files for more details: JSONDocUpdate.sh - Copies ITK Doxygen into SimpleITK JSON SwigDocUpdate.sh - Copies SimpleITK Doxygen into Swig .i files From 3d38e220df38caa89a70bc9536e650f601aa3819 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 29 Dec 2015 15:05:53 -0500 Subject: [PATCH 121/412] Increase tolerance for MaskedFFTNormazliedCorrelationImageFilter Based on report from Dmitry Mikhirev building SimpleITK for Fedora when using the system ITK with FFTW enabled. Change-Id: I2b3c51dff6970f55701f2f9d8f4d2dbcbdaf46a9 --- .../json/MaskedFFTNormalizedCorrelationImageFilter.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/BasicFilters/json/MaskedFFTNormalizedCorrelationImageFilter.json b/Code/BasicFilters/json/MaskedFFTNormalizedCorrelationImageFilter.json index 1db9ca330..0911b1313 100644 --- a/Code/BasicFilters/json/MaskedFFTNormalizedCorrelationImageFilter.json +++ b/Code/BasicFilters/json/MaskedFFTNormalizedCorrelationImageFilter.json @@ -32,7 +32,7 @@ "tag" : "defaults", "description" : "Basic xcorr with and odd kernel", "settings" : [], - "tolerance" : "0.01", + "tolerance" : "0.02", "inputs" : [ "Input/DeconvolutionInput.nrrd", "Input/Gaussian_1.5.nrrd", From cfb9b222f9eb64ef86f786bddfdafc67e5ee7c67 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 30 Dec 2015 14:29:24 -0500 Subject: [PATCH 122/412] Update ITK Superbuild version to 4.9rc3 Change-Id: I13ea0b05c2b8f42ec9de14f639b6b26586c4a5f7 --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 1fde644e5..08b5b64ec 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY git://itk.org/ITK.git) # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG 189385780861b4a1ced5702a13f796d355255577) +set(ITK_TAG_COMMAND GIT_TAG v4.9rc03 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 090c29eb3d031f3cd3ee22cfb7588e4fa2b5397d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 6 Jan 2016 13:08:08 -0500 Subject: [PATCH 123/412] Updated SWIG superbuild version to 3.0.9 Change-Id: Iabf6b29f6eb01b192ac4e16e847c75341d474253 --- SuperBuild/External_Swig.cmake | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SuperBuild/External_Swig.cmake b/SuperBuild/External_Swig.cmake index d52968b81..a70638ba5 100644 --- a/SuperBuild/External_Swig.cmake +++ b/SuperBuild/External_Swig.cmake @@ -12,9 +12,9 @@ endif() if(NOT SWIG_DIR) - set(SWIG_TARGET_VERSION 3.0.7) - set(SWIG_DOWNLOAD_SOURCE_HASH "7fff46c84b8c630ede5b0f0827e3d90a") - set(SWIG_DOWNLOAD_WIN_HASH "d8b5a9ce49c819cc1bfc1e797b85ba7a") + set(SWIG_TARGET_VERSION 3.0.8) + set(SWIG_DOWNLOAD_SOURCE_HASH "c96a1d5ecb13d38604d7e92148c73c97") + set(SWIG_DOWNLOAD_WIN_HASH "07bc00f7511b7d57516c50f59d705efa") if(WIN32) From 4d19fc3b8950760f244b6a20b2f96b3c5afa9ecc Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 7 Jan 2016 18:03:57 -0500 Subject: [PATCH 124/412] Updating ImageCompare to find alternate baseline images. SimpleITK regression testing of images now follows ITK convention for looking for additional image to compare with the ".#." the original baseline file name. Change-Id: I56ec382493ad9deb6bded5059168434e544499f0 --- Testing/Unit/sitkImageCompare.cxx | 269 +++++++++++++++++++----------- Testing/Unit/sitkImageCompare.h | 6 + 2 files changed, 179 insertions(+), 96 deletions(-) diff --git a/Testing/Unit/sitkImageCompare.cxx b/Testing/Unit/sitkImageCompare.cxx index 29969789d..b46c9e709 100644 --- a/Testing/Unit/sitkImageCompare.cxx +++ b/Testing/Unit/sitkImageCompare.cxx @@ -17,6 +17,7 @@ *=========================================================================*/ #include #include +#include #include "sitkImageCompare.h" @@ -78,6 +79,131 @@ ImageCompare::ImageCompare() mMessage = ""; } +float ImageCompare::testImages( const itk::simple::Image& testImage, + const itk::simple::Image& baselineImage, + bool reportErrors, + const std::string &baselineImageFilename) +{ + + const std::string OutputDir = dataFinder.GetOutputDirectory(); + + const std::string shortFilename = itksys::SystemTools::GetFilenameName( baselineImageFilename ); + + // verify they have the same size + if ( baselineImage.GetHeight() != testImage.GetHeight() + || baselineImage.GetWidth() != testImage.GetWidth() + || baselineImage.GetDepth() != testImage.GetDepth() ) + { + mMessage = "ImageCompare: Image dimensions are different"; + return -1; + } + + + // Compute image difference squared + sitk::Image diffSquared( 0, 0, itk::simple::sitkUInt8 ); + try + { + + if ( baselineImage.GetPixelID() == sitk::sitkComplexFloat32 || + baselineImage.GetPixelID() == sitk::sitkComplexFloat64 ) + { + + const sitk::Image diff = sitk::Subtract( testImage, baselineImage ); + // for complex number we multiply the image by it's complex + // conjugate, this will produce only a real value result + const sitk::Image conj = sitk::RealAndImaginaryToComplex( sitk::ComplexToReal( diff ), + sitk::Multiply( sitk::ComplexToImaginary( diff ), -1.0 ) ); + diffSquared = sitk::ComplexToReal( sitk::Multiply( diff, conj ) ); + } + else if ( baselineImage.GetNumberOfComponentsPerPixel() > 1 ) + { + const sitk::Image diff = sitk::Subtract( sitk::Cast( testImage, sitk::sitkVectorFloat32 ), sitk::Cast( baselineImage, sitk::sitkVectorFloat32 ) ); + + // for vector image just do a sum of the components + diffSquared = sitk::Pow( sitk::VectorIndexSelectionCast( diff, 0 ), 2.0 ); + for ( unsigned int i = 1; i < diff.GetNumberOfComponentsPerPixel(); ++i ) + { + const sitk::Image temp = sitk::Pow( sitk::VectorIndexSelectionCast( diff, i ), 2.0 ); + diffSquared = sitk::Add( temp, diffSquared ); + } + + diffSquared = sitk::Divide( diffSquared, diff.GetNumberOfComponentsPerPixel() ); + } + else + { + sitk::Image diff = sitk::Subtract( sitk::Cast( testImage, sitk::sitkFloat32 ), sitk::Cast( baselineImage, sitk::sitkFloat32 ) ); + diffSquared = sitk::Multiply( diff, diff ); + } + + } + catch ( std::exception& e ) + { + mMessage = "ImageCompare: Failed to subtract image " + baselineImageFilename + " because: " + e.what(); + return -1; + } + + + + sitk::StatisticsImageFilter stats; + stats.Execute ( diffSquared ); + const double rms = std::sqrt ( stats.GetMean() ); + + if ( !reportErrors ) + { + // The measurement errors should be reported for both success and errors + // to facilitate setting tight tolerances of tests. + std::cout << "" << rms << "" << std::endl; + } + else + { + std::ostringstream msg; + msg << "ImageCompare: image Root Mean Square (RMS) difference was " << rms << " which exceeds the tolerance of " << mTolerance; + msg << "\n"; + mMessage = msg.str(); + + std::cout << "" << rms << "" << std::endl; + std::cout << "" << mTolerance << "" << std::endl; + + std::string volumeName = OutputDir + "/" + shortFilename + ".nrrd"; + sitk::ImageFileWriter().SetFileName ( volumeName ).Execute ( testImage ); + + // Save pngs + std::string ExpectedImageFilename = OutputDir + "/" + shortFilename + "_Expected.png"; + std::string ActualImageFilename = OutputDir + "/" + shortFilename + "_Actual.png"; + std::string DifferenceImageFilename = OutputDir + "/" + shortFilename + "_Difference.png"; + + try + { + NormalizeAndSave ( baselineImage, ExpectedImageFilename ); + NormalizeAndSave ( testImage, ActualImageFilename ); + NormalizeAndSave ( sitk::Sqrt(diffSquared), DifferenceImageFilename ); + + // Let ctest know about it + std::cout << ""; + std::cout << ExpectedImageFilename << "" << std::endl; + std::cout << ""; + std::cout << ActualImageFilename << "" << std::endl; + std::cout << ""; + std::cout << DifferenceImageFilename << "" << std::endl; + + } + catch( std::exception &e ) + { + std::cerr << "Exception encountered while trying to normalize and save images for dashboard!" << std::endl; + std::cerr << e.what() << std::endl; + } + catch(...) + { + std::cerr << "Unexpected error while trying to normalize and save images for dashboard!" << std::endl; + } + + + } + + return (rms > fabs ( mTolerance )) ? rms : 0.0; +} + + bool ImageCompare::compare ( const sitk::Image& image, std::string inTestCase, std::string inTag ) { sitk::Image centerSlice( 0, 0, sitk::sitkUInt8 ); @@ -90,7 +216,6 @@ bool ImageCompare::compare ( const sitk::Image& image, std::string inTestCase, s testCase = ::testing::UnitTest::GetInstance()->current_test_info()->test_case_name(); } - std::cout << "Starting image compare on " << testCase << "_" << testName << "_" << tag << std::endl; // Does the baseline exist? std::string extension = ".nrrd"; std::string OutputDir = dataFinder.GetOutputDirectory(); @@ -104,7 +229,8 @@ bool ImageCompare::compare ( const sitk::Image& image, std::string inTestCase, s name.append("_").append ( tag ); } - // Extract the center slice of our image + + // Extract the center slice of our test image if ( image.GetDimension() == 3 ) { std::vector idx( 3, 0 ); @@ -120,9 +246,11 @@ bool ImageCompare::compare ( const sitk::Image& image, std::string inTestCase, s centerSlice = image; } - std::string baselineFileName = dataFinder.GetFile( "Baseline/" + name + extension ); + const std::string baselineFileName = dataFinder.GetFile( "Baseline/" + name + extension ); - if ( !itksys::SystemTools::FileExists ( baselineFileName.c_str() ) ) + + + if ( !itksys::SystemTools::FileExists ( baselineFileName.c_str(), true ) ) { // Baseline does not exist, write out what we've been given std::string newBaselineDir = OutputDir + "/Newbaseline/"; @@ -134,122 +262,71 @@ bool ImageCompare::compare ( const sitk::Image& image, std::string inTestCase, s return false; } - sitk::Image baseline( 0, 0, sitk::sitkUInt8 ); - std::cout << "Loading baseline " << baselineFileName << std::endl; + // Generate all possible baseline filenames + std::vector baselineFileNames; - try - { - baseline = sitk::ImageFileReader().SetFileName ( baselineFileName ).Execute(); - } - catch ( std::exception& e ) - { - mMessage = "ImageCompare: Failed to load image " + baselineFileName + " because: " + e.what(); - return false; - } + { + int x = 0; - // verify they have the same size - if ( baseline.GetHeight() != centerSlice.GetHeight() - || baseline.GetWidth() != centerSlice.GetWidth() - || baseline.GetDepth() != centerSlice.GetDepth() ) - { - mMessage = "ImageCompare: Image dimensions are different"; - return false; - } + baselineFileNames.push_back(baselineFileName); - // Get the center slices - sitk::Image diffSquared( 0, 0, itk::simple::sitkUInt8 ); - try - { - if ( baseline.GetPixelID() == sitk::sitkComplexFloat32 || - baseline.GetPixelID() == sitk::sitkComplexFloat64 ) - { - - sitk::Image diff = sitk::Subtract( centerSlice, baseline ); - // for complex number we multiply the image by it's complex - // conjugate, this will produce only a real value result - sitk::Image conj = sitk::RealAndImaginaryToComplex( sitk::ComplexToReal( diff ), - sitk::Multiply( sitk::ComplexToImaginary( diff ), -1.0 ) ); - diffSquared = sitk::ComplexToReal( sitk::Multiply( diff, conj ) ); - } - else if ( baseline.GetNumberOfComponentsPerPixel() > 1 ) - { - sitk::Image diff = sitk::Subtract( sitk::Cast( centerSlice, sitk::sitkVectorFloat32 ), sitk::Cast( baseline, sitk::sitkVectorFloat32 ) ); + while ( ++x ) + { + std::ostringstream filename_stream; + filename_stream << "Baseline/" << name << "." << x << extension; - // for vector image just do a sum of the components - diffSquared = sitk::Pow( sitk::VectorIndexSelectionCast( diff, 0 ), 2.0 ); - for ( unsigned int i = 1; i < diff.GetNumberOfComponentsPerPixel(); ++i ) - { - sitk::Image temp = sitk::Pow( sitk::VectorIndexSelectionCast( diff, i ), 2.0 ); - diffSquared = sitk::Add( temp, diffSquared ); - } + std::string filename = dataFinder.GetFile( filename_stream.str() ); - diffSquared = sitk::Divide( diffSquared, diff.GetNumberOfComponentsPerPixel() ); - } - else + if (!itksys::SystemTools::FileExists ( filename, true ) ) { - sitk::Image diff = sitk::Subtract( sitk::Cast( centerSlice, sitk::sitkFloat32 ), sitk::Cast( baseline, sitk::sitkFloat32 ) ); - diffSquared = sitk::Multiply( diff, diff ); + break; } - - } - catch ( std::exception& e ) - { - mMessage = "ImageCompare: Failed to subtract image " + baselineFileName + " because: " + e.what(); - return false; + baselineFileNames.push_back(filename); } + } - sitk::StatisticsImageFilter stats; - stats.Execute ( diffSquared ); - double rms = std::sqrt ( stats.GetMean() ); - - if ( rms > fabs ( mTolerance ) ) - { - std::ostringstream msg; - msg << "ImageCompare: image Root Mean Square (RMS) difference was " << rms << " which exceeds the tolerance of " << mTolerance; - msg << "\n"; - mMessage = msg.str(); + std::vector::const_iterator iterName; - std::cout << "" << rms << "" << std::endl; - std::cout << "" << mTolerance << "" << std::endl; + std::string bestBaselineName = *baselineFileNames.begin(); + float bestRMS = std::numeric_limits::max(); - std::string volumeName = OutputDir + "/" + name + ".nrrd"; - sitk::ImageFileWriter().SetFileName ( volumeName ).Execute ( centerSlice ); + for ( iterName = baselineFileNames.begin(); iterName != baselineFileNames.end(); ++iterName ) + { - // Save pngs - std::string ExpectedImageFilename = OutputDir + "/" + name + "_Expected.png"; - std::string ActualImageFilename = OutputDir + "/" + name + "_Actual.png"; - std::string DifferenceImageFilename = OutputDir + "/" + name + "_Difference.png"; + sitk::Image baseline( 0, 0, sitk::sitkUInt8 ); try { - NormalizeAndSave ( baseline, ExpectedImageFilename ); - NormalizeAndSave ( centerSlice, ActualImageFilename ); - NormalizeAndSave ( sitk::Sqrt(diffSquared), DifferenceImageFilename ); - - // Let ctest know about it - std::cout << ""; - std::cout << ExpectedImageFilename << "" << std::endl; - std::cout << ""; - std::cout << ActualImageFilename << "" << std::endl; - std::cout << ""; - std::cout << DifferenceImageFilename << "" << std::endl; - + baseline = sitk::ImageFileReader().SetFileName (*iterName ).Execute(); } - catch( std::exception &e ) + catch ( std::exception& e ) { - std::cerr << "Exception encountered while trying to normalize and save images for dashboard!" << std::endl; - std::cerr << e.what() << std::endl; + mMessage = "ImageCompare: Failed to load image " +*iterName + " because: " + e.what(); + return false; } - catch(...) + + float RMS = testImages( centerSlice, baseline, false, *iterName); + + if ( RMS >= 0.0 && RMS < bestRMS ) { - std::cerr << "Unexpected error while trying to normalize and save images for dashboard!" << std::endl; + bestBaselineName = *iterName; + bestRMS = RMS; } + } + + if ( bestRMS > fabs ( mTolerance ) ) + { + sitk::Image baseline = sitk::ImageFileReader().SetFileName (bestBaselineName ).Execute(); + testImages( centerSlice, baseline, true, bestBaselineName ); return false; - } + } + else + { + return true; + } - return true; } diff --git a/Testing/Unit/sitkImageCompare.h b/Testing/Unit/sitkImageCompare.h index db70a947f..2e703af09 100644 --- a/Testing/Unit/sitkImageCompare.h +++ b/Testing/Unit/sitkImageCompare.h @@ -29,6 +29,12 @@ class ImageCompare { // If the baseline does not exist, fail, and write a baseline image in the output directory bool compare ( const itk::simple::Image& image, std::string testGroup, std::string tag ); + float testImages( const itk::simple::Image& testImage, + const itk::simple::Image& baselineImage, + bool retportErrors, + const std::string &baselineImageFilename ); + + // Return the message from the previous image comparison. std::string getMessage() { return mMessage; } Self& setTolerance ( double t ) { mTolerance = t; return *this; } From b9c7321b767e85a9e69d5d708bd8c34de58452f1 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 7 Jan 2016 18:07:13 -0500 Subject: [PATCH 125/412] Adding alternative baseline images for ITK 4.9 changes to the algorithim With the release of ITK the boundary condition for the image has changed. Change-Id: Ia7f6093e2ecb01025c1b58480c1bb84458abf89c --- ..._AdaptiveHistogramEqualizationImageFilter_defaults.1.nrrd.md5 | 1 + ...ers_AdaptiveHistogramEqualizationImageFilter_histo.1.nrrd.md5 | 1 + 2 files changed, 2 insertions(+) create mode 100644 Testing/Data/Baseline/BasicFilters_AdaptiveHistogramEqualizationImageFilter_defaults.1.nrrd.md5 create mode 100644 Testing/Data/Baseline/BasicFilters_AdaptiveHistogramEqualizationImageFilter_histo.1.nrrd.md5 diff --git a/Testing/Data/Baseline/BasicFilters_AdaptiveHistogramEqualizationImageFilter_defaults.1.nrrd.md5 b/Testing/Data/Baseline/BasicFilters_AdaptiveHistogramEqualizationImageFilter_defaults.1.nrrd.md5 new file mode 100644 index 000000000..36476f9d4 --- /dev/null +++ b/Testing/Data/Baseline/BasicFilters_AdaptiveHistogramEqualizationImageFilter_defaults.1.nrrd.md5 @@ -0,0 +1 @@ +8484d918ce9f99837e96d7efeba7e848 diff --git a/Testing/Data/Baseline/BasicFilters_AdaptiveHistogramEqualizationImageFilter_histo.1.nrrd.md5 b/Testing/Data/Baseline/BasicFilters_AdaptiveHistogramEqualizationImageFilter_histo.1.nrrd.md5 new file mode 100644 index 000000000..5fbb5c248 --- /dev/null +++ b/Testing/Data/Baseline/BasicFilters_AdaptiveHistogramEqualizationImageFilter_histo.1.nrrd.md5 @@ -0,0 +1 @@ +fe2ea78da192cf9dc2eb1826063e761b From 362cfc76ea19f00710b185dc1a3a96b0ff249950 Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Wed, 29 Jul 2015 14:51:18 +1000 Subject: [PATCH 126/412] Support for using an R function as a callback. This change uses special R features for garbage collection of callback functions (R_PreserveObject). Mechanics of function calling and memory management of R objects is in RCommand typemaps declarations have been added for SEXP for the Command interface (and image/array conversion) to make the dispatching function correctly. Change-Id: I71f433eed09829c1e93933d5c1522ff4fd119809 --- Examples/ImageRegistrationMethod1.R | 59 +++++++++++++ Examples/test/CMakeLists.txt | 13 +++ Wrapping/Common/SimpleITK_Common.i | 3 + Wrapping/R/CMakeLists.txt | 7 +- Wrapping/R/R.i | 87 ++++++++++++++++++-- Wrapping/R/sitkRCommand.cxx | 123 ++++++++++++++++++++++++++++ Wrapping/R/sitkRCommand.h | 101 +++++++++++++++++++++++ 7 files changed, 381 insertions(+), 12 deletions(-) create mode 100644 Examples/ImageRegistrationMethod1.R create mode 100644 Wrapping/R/sitkRCommand.cxx create mode 100644 Wrapping/R/sitkRCommand.h diff --git a/Examples/ImageRegistrationMethod1.R b/Examples/ImageRegistrationMethod1.R new file mode 100644 index 000000000..632c53037 --- /dev/null +++ b/Examples/ImageRegistrationMethod1.R @@ -0,0 +1,59 @@ +#========================================================================= +# +# Copyright Insight Software Consortium +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0.txt +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#========================================================================= +# Run with: +# +# Rscript --vanilla ImageRegistrationMethod1.R fixedImage movingImage outputTransform +# + + +library(SimpleITK) + + +commandIteration <- function(method) +{ + res <- function() { + msg <- paste("Optimizer iteration number ", method$GetOptimizerIteration(), + " = ", method$GetMetricValue(), " : ", method$GetOptimizerPosition(), + "\n" ) + cat(msg) + } + return(res) +} + +args <- commandArgs( TRUE ) + +if (length(args) != 3) { + stop("3 arguments expected - FixedImage, MovingImage, TransformFilename") +} + +fixed <- ReadImage(args[[1]], 'sitkFloat32') + +moving <- ReadImage(args[[2]], 'sitkFloat32') + + +Reg = ImageRegistrationMethod() +Reg$SetMetricAsMeanSquares() +Reg$SetOptimizerAsRegularStepGradientDescent(4.0, .01, 200 ) +Reg$SetInitialTransform(TranslationTransform(fixed$GetDimension())) +Reg$SetInterpolator('sitkLinear') + +Reg$AddCommand('sitkIterationEvent', commandIteration(Reg)) + +outTx = Reg$Execute(fixed, moving) + +WriteTransform(outTx, args[[3]]) diff --git a/Examples/test/CMakeLists.txt b/Examples/test/CMakeLists.txt index 3715aed08..db00df6c5 100644 --- a/Examples/test/CMakeLists.txt +++ b/Examples/test/CMakeLists.txt @@ -557,6 +557,19 @@ sitk_add_r_test( Example.SimpleGaussian "${TEST_HARNESS_TEMP_DIRECTORY}/Python.SimpleGaussian.nrrd" ) +sitk_add_r_test( Example.ImageRegistrationMethod1 + "--file=${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethod1.R" + --args + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceShifted13x17y.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/RImageRegistrationMethod11Test.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/RImageRegistrationMethod11Test.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/displacement_13x17y.mha} + 0.02 + ) + + # # CSharp Examples diff --git a/Wrapping/Common/SimpleITK_Common.i b/Wrapping/Common/SimpleITK_Common.i index 0e7200b17..2d9a8a905 100644 --- a/Wrapping/Common/SimpleITK_Common.i +++ b/Wrapping/Common/SimpleITK_Common.i @@ -209,6 +209,9 @@ namespace std %include "sitkPyCommand.h" #endif +#if SWIGR +%include "sitkRCommand.h" +#endif // Auto-generated headers %include "SimpleITKBasicFiltersGeneratedHeaders.i" diff --git a/Wrapping/R/CMakeLists.txt b/Wrapping/R/CMakeLists.txt index 3a647d662..eee8b028d 100644 --- a/Wrapping/R/CMakeLists.txt +++ b/Wrapping/R/CMakeLists.txt @@ -1,14 +1,13 @@ find_package ( R REQUIRED ) -include_directories ( ${R_INCLUDE_DIR} ) +include_directories ( ${R_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}) set_source_files_properties ( SimpleITK.i PROPERTIES CPLUSPLUS ON ) # Run swig set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_GLOBAL_FLAGS}) set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) -set(SWIG_MODULE_SimpleITK_EXTRA_DEPS ${SWIG_EXTRA_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/R.i ) -SWIG_add_module ( SimpleITK r SimpleITK.i ) +set(SWIG_MODULE_SimpleITK_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/R.i ) +SWIG_add_module ( SimpleITK r SimpleITK.i sitkRCommand.cxx ) SWIG_link_libraries ( SimpleITK ${SimpleITK_LIBRARIES} ) # on some platforms the r libraries are not required at link time... diff --git a/Wrapping/R/R.i b/Wrapping/R/R.i index a1f899e38..7dda7e9da 100644 --- a/Wrapping/R/R.i +++ b/Wrapping/R/R.i @@ -6,19 +6,15 @@ %ignore itk::simple::GetPixelIDValueAsString( PixelIDValueType type ); %include - // we don't want a class assigned to unsigned char +// we don't want a class assigned to unsigned char %typemap(scoerceout) unsigned char, unsigned char *, unsigned char & %{ %} -// Gets rid of the class check for unsigned char function arguments -%typemap("rtype") unsigned char, unsigned char *, unsigned char & "integer"; -// and for unsigned int vectors -%typemap("rtype") std::vector, std::vector *, std::vector & "integer"; - -// some important enumerations don't get evaluate properly. This is a -// hack to fix the problem. +// SEXP numeric typemap for array/image converion - SEXP are +// arrays here +%typemap("rtype") SEXP "numeric"; %inline %{ @@ -58,6 +54,7 @@ itk::simple::PixelIDValueType RsitkLabelUInt32 = itk::simple::sitkLabelUInt32; itk::simple::PixelIDValueType RsitkLabelUInt64 = itk::simple::sitkLabelUInt64; + // functions for image content access via bracket operator itk::simple::Image SingleBracketOperator(std::vector xcoord, std::vector ycoord, std::vector zcoord, const itk::simple::Image src) { @@ -528,6 +525,80 @@ itk::simple::Image ArrayAsIm(SEXP arr, %} + +// Garbage collection issues are tricky here. The obj parameter +// is a function closure - see ImageRegistrationMethod1.R for +// example of how to set it up. The closure part of it includes +// the environment in which the function was created, which is +// how it is able to access the registration object. +// The call to AddCommand is like this: +// Reg$AddCommand('sitkIterationEvent', commandIteration(Reg)) +// It is difficult to cause crashes, even by calling gc() manually. +// +// The R documentation describes the scenario in which C code +// allocates R objects. The idea is that garbage collection +// can be invoked while the C code is being run due to +// calls to R internal functions. The PROTECT mechanism +// is used to guard the objects allocated in the C code. +// +// This doesn't cover the situation we have here, in which +// R objects are retained inside C objects, or are allocated +// then retained and are used in multiple C call. +// This case seems to be mentioned in passing at +// the end of 5.9.1 of Writing R extensions - R_PreserveObject +// and R_ReleaseObject. Sparing use is advised, but this +// seems like the situation for it. +// In order to keep things simple, we'll preserve the +// function closure passed in and the call we create. +// The obj will be passed to RCommand so that we can +// release it in the destructor. + +// Dispatching is based on a type attribute attached to +// R classes. For standard types this is simple. For c++ +// objects we end up with a class name that is a mangled +// c++ name. R SEXP objects are a problem. The default +// mangled name isn't useful and SEXP is used to represent +// everything in R. Ideally we can supply custom rtype +// setting, as below, but this gets quite tricky to mangage. +// The only other place where an SEXP is passed to/from +// swig bindings is in the array/image conversion code, +// which doesn't do dispatching. That code is largely +// confined to this file, so we put it first and set +// rtype to "numeric" there, then to "function" here. +// Finer control will require putting swig code in the right +// scope. + +%typemap("rtype") SEXP "function"; +%{ +#include "sitkRCommand.h" +%} + +%extend itk::simple::ProcessObject { + int AddCommand( itk::simple::EventEnum e, SEXP obj ) + { + // make sure that the CommandCallable is in fact callable + if (!Rf_isFunction(obj)) + { + sitkExceptionMacro(<<"R object is not a function, " + <<"or it has not been set."); + } + itk::simple::RCommand *cmd = NULL; + try + { + cmd = new itk::simple::RCommand(); + cmd->SetFunctionClosure(obj); + int ret = self->AddCommand(e,*cmd); + cmd->OwnedByProcessObjectsOn(); + return(ret); + } + catch(...) + { + delete cmd; + throw; + } + } +}; + //#define %rcode %insert("sinit") %Rruntime %{ diff --git a/Wrapping/R/sitkRCommand.cxx b/Wrapping/R/sitkRCommand.cxx new file mode 100644 index 000000000..a23bf1364 --- /dev/null +++ b/Wrapping/R/sitkRCommand.cxx @@ -0,0 +1,123 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ + +// The python header defines _POSIX_C_SOURCE without a preceding #undef +#include +#include + +#include "sitkRCommand.h" +#include "sitkExceptionObject.h" + + + + +namespace itk +{ +namespace simple +{ + + +RCommand::RCommand() + : m_Object(R_NilValue), + m_Environ(R_NilValue), + m_FunctionClosure(R_NilValue) +{ +} + +RCommand::~RCommand() +{ + R_ReleaseObject(this->m_Object); + R_ReleaseObject(this->m_FunctionClosure); +} + +void RCommand::SetCallbackRCallable(SEXP obj) +{ + if (obj != this->m_Object) + { + if (this->m_Object != R_NilValue) + { + // unprotect + R_ReleaseObject(this->m_Object); + } + this->m_Object = obj; + R_PreserveObject(this->m_Object); + } +} +void RCommand::SetCallbackREnviron(SEXP rho) +{ + if (rho != this->m_Environ) + { + // Don't need to do any releasing of the + // environment as it is part of the callable, + // and we haven't needed to explicitly protect it + this->m_Environ = rho; + } +} + +void RCommand::SetFunctionClosure(SEXP FN) +{ + if (FN != this->m_FunctionClosure) + { + if (this->m_FunctionClosure != R_NilValue) + { + R_ReleaseObject(this->m_FunctionClosure); + } + this->m_FunctionClosure = FN; + R_PreserveObject(this->m_FunctionClosure); + + // set up expression for evaluation + SEXP R_fcall; + // Rf_lang1 creates an executable pair list with one + // element + R_fcall = PROTECT(Rf_lang1(this->m_FunctionClosure)); + this->SetCallbackRCallable(R_fcall); + this->SetCallbackREnviron(CLOENV(this->m_FunctionClosure)); + UNPROTECT(1); + } +} + + +SEXP RCommand::GetCallbackRCallable() +{ + return this->m_Object; +} + +void RCommand::Execute() +{ + // if null do nothing + if ((!this->m_Object) || (!this->m_Environ)) + { + return; + } + + else + { + SEXP result; + // retrieve the environment for passing to eval + result = eval(this->m_Object, this->m_Environ); + if (result == NULL) + { + sitkExceptionMacro(<<"There was an error executing the " + <<"R Callable."); + } + } +} + + +} // namespace simple +} // namespace itk diff --git a/Wrapping/R/sitkRCommand.h b/Wrapping/R/sitkRCommand.h new file mode 100644 index 000000000..5ef88e383 --- /dev/null +++ b/Wrapping/R/sitkRCommand.h @@ -0,0 +1,101 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 __sitkRCommand_h +#define __sitkRCommand_h + +#include "sitkCommand.h" + + + + +namespace itk +{ +namespace simple +{ + +/** \class RCommand + * \brief Command subclass that calls an R callable object, e.g. + * an R function. + * + * With this class, arbitrary R functions + * can be associated with an instance to be used in AddObserver calls. + * + * Written by Richard Beare . + */ + +#include "Rinternals.h" + +class RCommand + : public itk::simple::Command +{ +public: + // Standard "Self" typedef. + typedef RCommand Self; + typedef Command Super; + + RCommand(); + ~RCommand(); + + /** + * Assign a R callable object to be used. You don't have to keep + * a binding to the callable, RCommand will preserve the objects + * across library calls + */ + /* This method is called from AddCommand, defined in R.i */ + /* It is a simplified interface that doesn't allow separate passing + * of the function and environment, which usually just makes things + * more confusing + */ + void SetFunctionClosure(SEXP FN); + + SEXP GetCallbackRCallable(); + + virtual void Execute(void); + + #ifndef SWIG + // export for access in the custom ProcessObject method for callables + using Super::SetOwnedByProcessObjects; + using Super::GetOwnedByProcessObjects; + using Super::OwnedByProcessObjectsOn; + using Super::OwnedByProcessObjectsOff; + #endif + + +protected: + RCommand(const Self&); + RCommand & operator=(const Self&); + + void SetCallbackRCallable(SEXP obj); + void SetCallbackREnviron(SEXP rho); + +private: + SEXP m_Object; + SEXP m_Environ; + // the function closure is stored to + // allow safe cleanup + SEXP m_FunctionClosure; +}; + +} // namespace simple +} // namespace itk + +#endif // _sitkRCommand_h From d81563cdc46b6649415d15385a894361f05618ae Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 8 Jan 2016 15:29:03 -0500 Subject: [PATCH 127/412] Adding new baselines for deconvolution with FFTW FFTW has different padding requirements for transforms than vnl FFT algorithm. This results in slightly different results. Alternative baseline images are now provided. Change-Id: Ic85ed35a54e2fa2af39eb7a48230290afdb5cfaa --- ...icFilters_InverseDeconvolutionImageFilter_defaults.1.nrrd.md5 | 1 + ...Filters_LandweberDeconvolutionImageFilter_defaults.1.nrrd.md5 | 1 + ...cFilters_TikhonovDeconvolutionImageFilter_defaults.1.nrrd.md5 | 1 + ...sicFilters_WienerDeconvolutionImageFilter_defaults.1.nrrd.md5 | 1 + 4 files changed, 4 insertions(+) create mode 100644 Testing/Data/Baseline/BasicFilters_InverseDeconvolutionImageFilter_defaults.1.nrrd.md5 create mode 100644 Testing/Data/Baseline/BasicFilters_LandweberDeconvolutionImageFilter_defaults.1.nrrd.md5 create mode 100644 Testing/Data/Baseline/BasicFilters_TikhonovDeconvolutionImageFilter_defaults.1.nrrd.md5 create mode 100644 Testing/Data/Baseline/BasicFilters_WienerDeconvolutionImageFilter_defaults.1.nrrd.md5 diff --git a/Testing/Data/Baseline/BasicFilters_InverseDeconvolutionImageFilter_defaults.1.nrrd.md5 b/Testing/Data/Baseline/BasicFilters_InverseDeconvolutionImageFilter_defaults.1.nrrd.md5 new file mode 100644 index 000000000..e9265e123 --- /dev/null +++ b/Testing/Data/Baseline/BasicFilters_InverseDeconvolutionImageFilter_defaults.1.nrrd.md5 @@ -0,0 +1 @@ +ade10e95c97fdc72399e210bc77e1a27 diff --git a/Testing/Data/Baseline/BasicFilters_LandweberDeconvolutionImageFilter_defaults.1.nrrd.md5 b/Testing/Data/Baseline/BasicFilters_LandweberDeconvolutionImageFilter_defaults.1.nrrd.md5 new file mode 100644 index 000000000..5d8b5e5cb --- /dev/null +++ b/Testing/Data/Baseline/BasicFilters_LandweberDeconvolutionImageFilter_defaults.1.nrrd.md5 @@ -0,0 +1 @@ +6ab6025929136899d3e3f91fe62fae15 diff --git a/Testing/Data/Baseline/BasicFilters_TikhonovDeconvolutionImageFilter_defaults.1.nrrd.md5 b/Testing/Data/Baseline/BasicFilters_TikhonovDeconvolutionImageFilter_defaults.1.nrrd.md5 new file mode 100644 index 000000000..9e551d170 --- /dev/null +++ b/Testing/Data/Baseline/BasicFilters_TikhonovDeconvolutionImageFilter_defaults.1.nrrd.md5 @@ -0,0 +1 @@ +788099cb89927e7a5039313cc8476388 diff --git a/Testing/Data/Baseline/BasicFilters_WienerDeconvolutionImageFilter_defaults.1.nrrd.md5 b/Testing/Data/Baseline/BasicFilters_WienerDeconvolutionImageFilter_defaults.1.nrrd.md5 new file mode 100644 index 000000000..9e551d170 --- /dev/null +++ b/Testing/Data/Baseline/BasicFilters_WienerDeconvolutionImageFilter_defaults.1.nrrd.md5 @@ -0,0 +1 @@ +788099cb89927e7a5039313cc8476388 From 64dbd3c97ff4a29c7fc4c3f59238b8db16d8f678 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 27 Nov 2015 14:23:58 -0500 Subject: [PATCH 128/412] Adding R Example for filter callbacks Change-Id: Iae3db103ab010ab980b195b9415d5f96cfac8950 --- Examples/FilterProgressReporting.R | 57 ++++++++++++++++++++++++++++++ Examples/test/CMakeLists.txt | 11 ++++-- 2 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 Examples/FilterProgressReporting.R diff --git a/Examples/FilterProgressReporting.R b/Examples/FilterProgressReporting.R new file mode 100644 index 000000000..063e2cecc --- /dev/null +++ b/Examples/FilterProgressReporting.R @@ -0,0 +1,57 @@ +#========================================================================= +# +# Copyright Insight Software Consortium +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0.txt +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#========================================================================= +# Run with: +# +# Rscript --vanilla ImageRegistrationMethod1.R fixedImage movingImage outputTransform +# + + +library(SimpleITK) + +args <- commandArgs( TRUE ) + +if (length(args) < 3){ + write("Usage arguments: ", stderr()) + quit(1) +} + +reader <- ImageFileReader() +reader$SetFileName(args[[1]]) +image = reader$Execute() + +pixelID <- image$GetPixelID() + +gaussian <- DiscreteGaussianImageFilter() +gaussian$SetVariance( as.numeric(args[2]) ) + +##! [R lambda command] +gaussian$AddCommand( 'sitkStartEvent', function(method) {cat("StartEvent\n")} ) +##! [R lambda command] + +cmd <- RCommand() +gaussian$AddCommand( 'sitkEndEvent', cmd ) + +image = gaussian$Execute( image ) + +caster <- CastImageFilter() +caster$SetOutputPixelType( pixelID ) +image = caster$Execute( image ) + +writer <- ImageFileWriter() +writer$SetFileName( args[[3]] ) +writer$Execute( image ) diff --git a/Examples/test/CMakeLists.txt b/Examples/test/CMakeLists.txt index db00df6c5..785cefced 100644 --- a/Examples/test/CMakeLists.txt +++ b/Examples/test/CMakeLists.txt @@ -549,12 +549,19 @@ endif ( WRAP_JAVA ) sitk_add_r_test( Example.SimpleGaussian "--file=${SimpleITKExamples_SOURCE_DIR}/SimpleGaussian.R" --compare - "${TEST_HARNESS_TEMP_DIRECTORY}/Python.SimpleGaussian.nrrd" + "${TEST_HARNESS_TEMP_DIRECTORY}/R.SimpleGaussian.nrrd" DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} --args DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} "2.0" - "${TEST_HARNESS_TEMP_DIRECTORY}/Python.SimpleGaussian.nrrd" + "${TEST_HARNESS_TEMP_DIRECTORY}/R.SimpleGaussian.nrrd" + ) +sitk_add_r_test( Example.FilterProgressReporting + "--file=${SimpleITKExamples_SOURCE_DIR}/FilterProgressReporting.R" + --args + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} + 2.0 + "${TEST_HARNESS_TEMP_DIRECTORY}/R.FilterProgressReporting.nrrd" ) sitk_add_r_test( Example.ImageRegistrationMethod1 From 52bc5688f2fd1e16f9c5c1c8ce9c50f5dbefc2c2 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 12 Jan 2016 15:48:43 -0500 Subject: [PATCH 129/412] Adding documentation for R lambda callback usage Change-Id: Id2f6e6af06b68a028d5672fc3fa825631e6001ba --- Documentation/Doxygen/CommandsAndEvents.dox | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Documentation/Doxygen/CommandsAndEvents.dox b/Documentation/Doxygen/CommandsAndEvents.dox index 11115ce38..987c6e982 100644 --- a/Documentation/Doxygen/CommandsAndEvents.dox +++ b/Documentation/Doxygen/CommandsAndEvents.dox @@ -56,6 +56,10 @@ for functions for the ProcessObject::AddCommand method: \subsubsection CommandFunctionPython \snippet FilterProgressReporting.py python lambda command +\subsubsection CommandFunctionR +\snippet FilterProgressReporting.R R lambda command + + */ } } From 000f95445cf5a1e884d4d4636d37907cd876ad14 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 13 Jan 2016 13:25:59 -0500 Subject: [PATCH 130/412] Update tolerance for AdaptiveHistogramEqualizationImageFilter test Change-Id: I930781a323da011c78255e7083952496b37bdfc7 --- .../json/AdaptiveHistogramEqualizationImageFilter.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/BasicFilters/json/AdaptiveHistogramEqualizationImageFilter.json b/Code/BasicFilters/json/AdaptiveHistogramEqualizationImageFilter.json index 9bf336349..19c4d5613 100644 --- a/Code/BasicFilters/json/AdaptiveHistogramEqualizationImageFilter.json +++ b/Code/BasicFilters/json/AdaptiveHistogramEqualizationImageFilter.json @@ -49,7 +49,7 @@ "tag" : "defaults", "description" : "Simply run with default settings", "settings" : [], - "tolerance" : "5e-4", + "tolerance" : "2e-3", "inputs" : [ "Input/RA-Slice-Float.nrrd" ] From 15ff205f9c60d9d95fdfd879aa557128598edb30 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 15 Jan 2016 15:59:43 -0500 Subject: [PATCH 131/412] Updating ITK Superbuild version along release branch This ITK update contains an important patch to ITK's VNL to support OSX's libc++ Change-Id: I4f24bf170937017514947361ab689421dc3a1163 --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 08b5b64ec..696ff117d 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY git://itk.org/ITK.git) # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG v4.9rc03 ) +set(ITK_TAG_COMMAND GIT_TAG 2744162f6d74160c8f4b2943af8a21a8e5c11720 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From a4f786ddb8c8162c34b82c361e16fc71d9daf936 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 19 Jan 2016 12:04:31 -0500 Subject: [PATCH 132/412] BUG: Address HistogramMatching error with number of bins Changes in ITK 4.9 changes the way the number of bins are computed. This example incorrectly tried to use 1024 bins with uint8 images. This has been corrected to only use 128 bins. This gives the same results with prior versions of ITK as with the fixed version of ITK. Change-Id: I8203b6412a18972759aaf63070d333cf61271aef --- Examples/DemonsRegistration2.cxx | 10 +++++++++- Examples/DemonsRegistration2.py | 5 ++++- .../DemonsRegistration2Test_displacement.mha.md5 | 2 +- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/Examples/DemonsRegistration2.cxx b/Examples/DemonsRegistration2.cxx index 907df1a14..6765b87ab 100644 --- a/Examples/DemonsRegistration2.cxx +++ b/Examples/DemonsRegistration2.cxx @@ -72,7 +72,15 @@ int main(int argc, char *argv[]) sitk::Image moving = sitk::ReadImage( argv[2] ); sitk::HistogramMatchingImageFilter matcher; - matcher.SetNumberOfHistogramLevels( 1024 ); + if ( fixed.GetPixelID() == sitk::sitkUInt8 + || fixed.GetPixelID() == sitk::sitkInt8 ) + { + matcher.SetNumberOfHistogramLevels( 128 ); + } + else + { + matcher.SetNumberOfHistogramLevels( 1024 ); + } matcher.SetNumberOfMatchPoints( 7 ); matcher.ThresholdAtMeanIntensityOn(); diff --git a/Examples/DemonsRegistration2.py b/Examples/DemonsRegistration2.py index 215ce3f5b..f13fadcdf 100755 --- a/Examples/DemonsRegistration2.py +++ b/Examples/DemonsRegistration2.py @@ -38,7 +38,10 @@ def command_iteration(filter) : moving = sitk.ReadImage(sys.argv[2]) matcher = sitk.HistogramMatchingImageFilter() -matcher.SetNumberOfHistogramLevels(1024) +if ( fixed.GetPixelID() in ( sitk.sitkUInt8, sitk.sitkInt8 ) ): + matcher.SetNumberOfHistogramLevels(128) +else: + matcher.SetNumberOfHistogramLevels(1024) matcher.SetNumberOfMatchPoints(7) matcher.ThresholdAtMeanIntensityOn() moving = matcher.Execute(moving,fixed) diff --git a/Testing/Data/Baseline/DemonsRegistration2Test_displacement.mha.md5 b/Testing/Data/Baseline/DemonsRegistration2Test_displacement.mha.md5 index 674d95033..db99471e3 100644 --- a/Testing/Data/Baseline/DemonsRegistration2Test_displacement.mha.md5 +++ b/Testing/Data/Baseline/DemonsRegistration2Test_displacement.mha.md5 @@ -1 +1 @@ -0686ed8ae2c689ddff45a69715e46005 +059a97d1e6f0a9b05162b9b44a2fd786 From 0a759c71e10c19d2287c514e13fcb0643ed4392d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 19 Jan 2016 13:29:55 -0500 Subject: [PATCH 133/412] Updating ITK along release branch Change-Id: Ib1b52949f6c028d99a2d13f7e3aa97e957cfc371 --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 696ff117d..8b9fa1f3f 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY git://itk.org/ITK.git) # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG 2744162f6d74160c8f4b2943af8a21a8e5c11720 ) +set(ITK_TAG_COMMAND GIT_TAG 0c4381bbca1c5595bf397e2d4f2646aaf394a973 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 57609490c6f2be91599d593e097e8d26c8d0ba77 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 19 Jan 2016 16:06:24 -0500 Subject: [PATCH 134/412] Disable Explicit ITK instantiation for gcc 4.1 There is a compiler issues with explicit instantiation of classing with static const members which causes a gargantuan number of compilation errors with the SimpleITK explicit instantiation library. Change-Id: Ie3eea297f1be2445b084ca8bc253c95e7116d9e5 --- CMakeLists.txt | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index bc439e9e5..980be79db 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -95,7 +95,17 @@ endif() option(BUILD_SHARED_LIBS "Build SimpleITK ITK with shared libraries. This does not effect wrapped languages." OFF) set(SITK_BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS}) -option(SITK_EXPLICIT_INSTANTIATION "Enable an ITK static library of explicitly instantiated templates." ON) +set(SITK_EXPLICIT_INSTANTIATION_DEFAULT ON) +# +# Disable Explicit Instantiation for gcc 4.1 because of problems with +# ITK's static constant macro introduced in ITK 4.9.0 version +if ("${ITK_VERSION_MAJOR}.${ITK_VERSION_MINOR}.${ITK_VERSION_PATCH}" VERSION_EQUAL "4.9" + AND ${CMAKE_COMPILER_IS_GNUCXX} + AND ${CMAKE_CXX_COMPILER_VERSION} VERSION_LESS "4.2" ) + set(SITK_EXPLICIT_INSTANTIATION_DEFAULT OFF) +endif() + +option(SITK_EXPLICIT_INSTANTIATION "Enable an ITK static library of explicitly instantiated templates." ${SITK_EXPLICIT_INSTANTIATION_DEFAULT}) if ( MSVC AND SITK_BUILD_SHARED_LIBS ) set( SITK_SimpleITKExplit_STATIC 1 ) endif() From 58da83f42bf6337247664473656e8db70e6f96c3 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 19 Jan 2016 22:16:25 -0500 Subject: [PATCH 135/412] Adding needed quote to CMake variable to handle null strings. Change-Id: I3125226045f154ca2f672d1eda4c4afbf97300ef --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 980be79db..3c8d77216 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -100,8 +100,8 @@ set(SITK_EXPLICIT_INSTANTIATION_DEFAULT ON) # Disable Explicit Instantiation for gcc 4.1 because of problems with # ITK's static constant macro introduced in ITK 4.9.0 version if ("${ITK_VERSION_MAJOR}.${ITK_VERSION_MINOR}.${ITK_VERSION_PATCH}" VERSION_EQUAL "4.9" - AND ${CMAKE_COMPILER_IS_GNUCXX} - AND ${CMAKE_CXX_COMPILER_VERSION} VERSION_LESS "4.2" ) + AND "${CMAKE_COMPILER_IS_GNUCXX}" + AND "${CMAKE_CXX_COMPILER_VERSION}" VERSION_LESS "4.2" ) set(SITK_EXPLICIT_INSTANTIATION_DEFAULT OFF) endif() From 4b595f4879c617b12e872b462465fcca19c2a6d0 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 26 Jan 2016 12:46:05 -0500 Subject: [PATCH 136/412] Updating to latest hash on ITK release branch for 4.9 This addresses compilation issue with ITK and explicit instantiation for <=gcc 4.2 Change-Id: I27b8d9e8425fb67c6aef3d833dd2ee51271ba178 --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 8b9fa1f3f..131c61b0f 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY git://itk.org/ITK.git) # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG 0c4381bbca1c5595bf397e2d4f2646aaf394a973 ) +set(ITK_TAG_COMMAND GIT_TAG 5908767d9ad53585c59c4fde3b8cba79eba9a40b ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 388bbe5386594c018a09c934b92bd501d7d6968e Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 26 Jan 2016 12:51:19 -0500 Subject: [PATCH 137/412] Revert "Disable Explicit ITK instantiation for gcc 4.1" This reverts commits 57609490c6f2be91599d593e097e8d26c8d0ba77^..58da83f42bf6337247664473656e8db70e6f96c3 Change-Id: I59adacca5e50a41fa3e6b8f8c434a8b6ddf1976e --- CMakeLists.txt | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3c8d77216..bc439e9e5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -95,17 +95,7 @@ endif() option(BUILD_SHARED_LIBS "Build SimpleITK ITK with shared libraries. This does not effect wrapped languages." OFF) set(SITK_BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS}) -set(SITK_EXPLICIT_INSTANTIATION_DEFAULT ON) -# -# Disable Explicit Instantiation for gcc 4.1 because of problems with -# ITK's static constant macro introduced in ITK 4.9.0 version -if ("${ITK_VERSION_MAJOR}.${ITK_VERSION_MINOR}.${ITK_VERSION_PATCH}" VERSION_EQUAL "4.9" - AND "${CMAKE_COMPILER_IS_GNUCXX}" - AND "${CMAKE_CXX_COMPILER_VERSION}" VERSION_LESS "4.2" ) - set(SITK_EXPLICIT_INSTANTIATION_DEFAULT OFF) -endif() - -option(SITK_EXPLICIT_INSTANTIATION "Enable an ITK static library of explicitly instantiated templates." ${SITK_EXPLICIT_INSTANTIATION_DEFAULT}) +option(SITK_EXPLICIT_INSTANTIATION "Enable an ITK static library of explicitly instantiated templates." ON) if ( MSVC AND SITK_BUILD_SHARED_LIBS ) set( SITK_SimpleITKExplit_STATIC 1 ) endif() From fe2c1b27dded46884e9407f2e4c7e7e954698888 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 26 Jan 2016 21:37:11 -0500 Subject: [PATCH 138/412] BUG: Fix conversion to int in overloaded > and >= operators This also effect the reverse operator, when the image in on the right hand size and the operator is < or <=. Adding good testing for the related operators. Change-Id: Ibe9dc2eaa4b1af9d47a1393706c02bf57a7f015a --- Testing/Unit/ImageIndexingTest.py | 42 +++++++++++++++++++++++++++++++ Wrapping/Python.i | 4 +-- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/Testing/Unit/ImageIndexingTest.py b/Testing/Unit/ImageIndexingTest.py index 3700bafde..2740f6e62 100644 --- a/Testing/Unit/ImageIndexingTest.py +++ b/Testing/Unit/ImageIndexingTest.py @@ -151,6 +151,48 @@ def test_3d(self): self.assertImageNDArrayEquals(img[:,::-2,::-1], nda[::-1,::-2,:]) self.assertImageNDArrayEquals(img[-1:-4:-1,:,:], nda[:,:,-1:-4:-1]) + def test_compare(self): + + img = sitk.Image(1,1,sitk.sitkFloat32) + self.assertEqual(img.GetPixel(0,0), 0.0) + + self.assertEqual((img<0).GetPixel(0,0), 0) + self.assertEqual((img<=0).GetPixel(0,0), 1) + + self.assertEqual((0>img).GetPixel(0,0), 0) + self.assertEqual((0>=img).GetPixel(0,0), 1) + + self.assertEqual((img>0).GetPixel(0,0), 0) + self.assertEqual((img>=0).GetPixel(0,0), 1) + + self.assertEqual((0img).GetPixel(0,0), 0) + self.assertEqual((0.5>=img).GetPixel(0,0), 1) + + self.assertEqual((img>0.5).GetPixel(0,0), 0) + self.assertEqual((img>=0.5).GetPixel(0,0), 1) + + self.assertEqual((0.5img).GetPixel(0,0), 0) + self.assertEqual((-1>=img).GetPixel(0,0), 0) + + self.assertEqual((img>-1).GetPixel(0,0), 1) + self.assertEqual((img>=-1).GetPixel(0,0), 1) + + self.assertEqual((-1 Date: Wed, 20 Jan 2016 15:14:01 -0500 Subject: [PATCH 139/412] Remove Clang warnings when building Lua When building Lua, Clang gives warnings about an empty loop body and a few deprecated declarations. This submissions adds the -Wno-empty-body and -Wno-deprecated-declaration flags to the compiler line to supress thos warnings. Change-Id: I9100a65d74987c1ccd4bc950087bcc25cd4120f0 --- SuperBuild/lua.cmake | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/SuperBuild/lua.cmake b/SuperBuild/lua.cmake index a4d3fa0b3..0dfa8ce3e 100644 --- a/SuperBuild/lua.cmake +++ b/SuperBuild/lua.cmake @@ -1,5 +1,11 @@ cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) + +if(POLICY CMP0025) + cmake_policy(SET CMP0025 OLD) +endif() + + project (LUA C) # Setup build locations. @@ -41,6 +47,12 @@ if( MSVC ) SET( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4334" ) endif() +if( APPLE ) + if("${CMAKE_C_COMPILER_ID}" STREQUAL "Clang") + # suppress Clang warnings about empty loop bodies and deprecated declarations (tmpnam) + SET( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-empty-body -Wno-deprecated-declarations" ) + endif() +endif() # define the lua core source files set (LUA_CORE_SRCS src/lapi.c src/lcode.c src/ldebug.c src/ldo.c src/ldump.c From 23b18b2738ae865832e4ccb951a7381a936b15ac Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 5 Feb 2016 13:44:58 -0500 Subject: [PATCH 140/412] COMP: Adress Ununsed typenames in Common Remove many unused typedef, and changed scope of others. --- Code/Common/include/Ancillary/TypeList.h | 27 +++++------------------- Code/Common/include/sitkImageConvert.h | 1 - Code/Common/include/sitkProcessObject.h | 1 - Code/Common/src/sitkTransform.cxx | 1 - 4 files changed, 5 insertions(+), 25 deletions(-) diff --git a/Code/Common/include/Ancillary/TypeList.h b/Code/Common/include/Ancillary/TypeList.h index ddf302392..5d51b9be3 100644 --- a/Code/Common/include/Ancillary/TypeList.h +++ b/Code/Common/include/Ancillary/TypeList.h @@ -402,15 +402,14 @@ struct DualVisit template < typename TLeftTypeList, typename TRightTypeList > struct DualVisitImpl { + typedef typename TLeftTypeList::Head LeftHead; + typedef typename TRightTypeList::Head RightHead; + typedef typename TLeftTypeList::Tail LeftTail; + typedef typename TRightTypeList::Tail RightTail; + template void operator()( Visitor &visitor ) const { - typedef typename TLeftTypeList::Head LeftHead; - typedef typename TRightTypeList::Head RightHead; - typedef typename TLeftTypeList::Tail LeftTail; - typedef typename TRightTypeList::Tail RightTail; - - DualVisitImpl< TLeftTypeList, TRightTypeList> goRight; goRight.visitRHS( visitor ); @@ -421,12 +420,6 @@ struct DualVisitImpl template void operator()( const Visitor &visitor ) const { - typedef typename TLeftTypeList::Head LeftHead; - typedef typename TRightTypeList::Head RightHead; - typedef typename TLeftTypeList::Tail LeftTail; - typedef typename TRightTypeList::Tail RightTail; - - DualVisitImpl< TLeftTypeList, TRightTypeList> goRight; goRight.visitRHS( visitor ); @@ -437,11 +430,6 @@ struct DualVisitImpl template void visitRHS( Visitor &visitor ) const { - typedef typename TLeftTypeList::Head LeftHead; - typedef typename TRightTypeList::Head RightHead; - typedef typename TLeftTypeList::Tail LeftTail; - typedef typename TRightTypeList::Tail RightTail; - visitor.CLANG_TEMPLATE operator()( ); DualVisitImpl< TLeftTypeList, RightTail> goRight; @@ -450,11 +438,6 @@ struct DualVisitImpl template void visitRHS( const Visitor &visitor ) const { - typedef typename TLeftTypeList::Head LeftHead; - typedef typename TRightTypeList::Head RightHead; - typedef typename TLeftTypeList::Tail LeftTail; - typedef typename TRightTypeList::Tail RightTail; - visitor.CLANG_TEMPLATE operator()( ); DualVisitImpl< TLeftTypeList, RightTail> goRight; diff --git a/Code/Common/include/sitkImageConvert.h b/Code/Common/include/sitkImageConvert.h index 1f2ba28bf..c209b02cf 100644 --- a/Code/Common/include/sitkImageConvert.h +++ b/Code/Common/include/sitkImageConvert.h @@ -72,7 +72,6 @@ SITKCommon_HIDDEN typename itk::VectorImage< TPixelType, NImageDimension >::Pointer GetVectorImageFromImage( itk::Image< itk::Vector< TPixelType, NLength >, NImageDimension> *img, bool transferOwnership = false ) { - typedef itk::Image< itk::Vector< TPixelType, NLength >, NImageDimension> ImageType; typedef itk::VectorImage< TPixelType, NImageDimension > VectorImageType; size_t numberOfElements = img->GetBufferedRegion().GetNumberOfPixels(); diff --git a/Code/Common/include/sitkProcessObject.h b/Code/Common/include/sitkProcessObject.h index b8ca39581..abef03e23 100644 --- a/Code/Common/include/sitkProcessObject.h +++ b/Code/Common/include/sitkProcessObject.h @@ -290,7 +290,6 @@ namespace itk { template class TVector > static Image CastITKToImage( itk::Image< TVector< TPixelType, VLength >, VImageDimension> *img ) { - typedef itk::Image< TVector< TPixelType, VLength >, VImageDimension> ImageType; typedef itk::VectorImage< TPixelType, VImageDimension > VectorImageType; size_t numberOfElements = img->GetBufferedRegion().GetNumberOfPixels(); diff --git a/Code/Common/src/sitkTransform.cxx b/Code/Common/src/sitkTransform.cxx index 15058a872..9bb8eded6 100644 --- a/Code/Common/src/sitkTransform.cxx +++ b/Code/Common/src/sitkTransform.cxx @@ -348,7 +348,6 @@ void Transform::InternalBSplineInitialization( Image & inImage ) { typedef TDisplacementType VectorImageType; - typedef typename VectorImageType::PixelType PixelType; typedef typename VectorImageType::InternalPixelType ComponentType; const unsigned int ImageDimension = VectorImageType::ImageDimension; From 165f310cc33b06daaa64129d1209a29f66fda7c0 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Fri, 5 Feb 2016 14:36:06 -0500 Subject: [PATCH 141/412] COMP: CLang Warning Remediation A set of macros was introduced in sitkMacro.h to help silence some of clang's many warnings. These warnings, sitkClangDiagnosticPush, sitkClangDiagnosticPop, and sitkClangDiagnosticIgnore are used in the other files of this commit to sqelch the "-Wunused-local-typedef" warnings that clang gives. Change-Id: I8b7a11ceca816087dae6ba6c2d545f153283dc5c --- .../templates/sitkDualImageFilterTemplate.cxx.in | 5 +++++ .../templates/sitkImageFilterTemplate.cxx.in | 5 +++++ .../templates/sitkImageSourceTemplate.cxx.in | 5 +++++ Code/Common/include/sitkMacro.h | 11 +++++++++++ 4 files changed, 26 insertions(+) diff --git a/Code/BasicFilters/templates/sitkDualImageFilterTemplate.cxx.in b/Code/BasicFilters/templates/sitkDualImageFilterTemplate.cxx.in index 2c187350c..6a94dcd45 100644 --- a/Code/BasicFilters/templates/sitkDualImageFilterTemplate.cxx.in +++ b/Code/BasicFilters/templates/sitkDualImageFilterTemplate.cxx.in @@ -134,6 +134,9 @@ $(include CustomCasts.cxx) //----------------------------------------------------------------------------- +sitkClangDiagnosticPush(); +sitkClangDiagnosticIgnore("-Wunused-local-typedef"); + // // ExecuteInternal // @@ -251,6 +254,8 @@ OUT=OUT..[[ return Image( toVector->GetOutput() ); } +sitkClangDiagnosticPop(); + //----------------------------------------------------------------------------- ]]end) diff --git a/Code/BasicFilters/templates/sitkImageFilterTemplate.cxx.in b/Code/BasicFilters/templates/sitkImageFilterTemplate.cxx.in index c1b5ff501..f3f1ddcff 100644 --- a/Code/BasicFilters/templates/sitkImageFilterTemplate.cxx.in +++ b/Code/BasicFilters/templates/sitkImageFilterTemplate.cxx.in @@ -60,6 +60,9 @@ $(include CustomCasts.cxx) //----------------------------------------------------------------------------- +sitkClangDiagnosticPush(); +sitkClangDiagnosticIgnore("-Wunused-local-typedef"); + // // ExecuteInternal // @@ -75,6 +78,8 @@ $(include ExecuteInternalSetITKFilterInputs.cxx.in) $(include ExecuteInternalUpdateAndReturn.cxx.in) } +sitkClangDiagnosticPop(); + //----------------------------------------------------------------------------- $(include ExecuteInternalVectorImages.cxx.in) diff --git a/Code/BasicFilters/templates/sitkImageSourceTemplate.cxx.in b/Code/BasicFilters/templates/sitkImageSourceTemplate.cxx.in index 84e90b10b..691b0c93c 100644 --- a/Code/BasicFilters/templates/sitkImageSourceTemplate.cxx.in +++ b/Code/BasicFilters/templates/sitkImageSourceTemplate.cxx.in @@ -86,6 +86,9 @@ $(include CustomCasts.cxx) //----------------------------------------------------------------------------- +sitkClangDiagnosticPush(); +sitkClangDiagnosticIgnore("-Wunused-local-typedef"); + // // ExecuteInternal // @@ -101,6 +104,8 @@ $(include ExecuteInternalSetITKFilterInputs.cxx.in) $(include ExecuteInternalUpdateAndReturn.cxx.in) } +sitkClangDiagnosticPop(); + //----------------------------------------------------------------------------- $(include ExecuteInternalVectorImages.cxx.in) diff --git a/Code/Common/include/sitkMacro.h b/Code/Common/include/sitkMacro.h index eb090aee1..9a246a588 100644 --- a/Code/Common/include/sitkMacro.h +++ b/Code/Common/include/sitkMacro.h @@ -106,6 +106,17 @@ template<> struct StaticAssertFailure{ enum { Value = 1 }; }; #endif +#define sitkPragma(x) _Pragma (#x) + +#if defined(__clang__) && defined(__has_warning) +#define sitkClangDiagnosticPush() sitkPragma( clang diagnostic push ) +#define sitkClangDiagnosticPop() sitkPragma( clang diagnostic pop ) +#define sitkClangDiagnosticIgnore(x) sitkPragma( clang diagnostic ignored x) +#else +#define sitkClangDiagnosticPush() +#define sitkClangDiagnosticPop() +#define sitkClangDiagnosticIgnore(x) +#endif } } From f949d0282c847584d533c37fe7a44ab9915972ab Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 9 Feb 2016 09:14:54 -0500 Subject: [PATCH 142/412] Update to ITK 4.9 release tag Change-Id: I313335f40e8850bbff107a0ff95902c6be70b23f --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 131c61b0f..5f20409c9 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY git://itk.org/ITK.git) # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG 5908767d9ad53585c59c4fde3b8cba79eba9a40b ) +set(ITK_TAG_COMMAND GIT_TAG v4.9.0 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 84df75872ab2423a0b0905f7477e247183827f96 Mon Sep 17 00:00:00 2001 From: Hans Johnson Date: Tue, 9 Feb 2016 11:28:09 -0600 Subject: [PATCH 143/412] DOC: s/treaded/treated/g spelling fix Fixing the spelling in documentation. --- Wrapping/Python/Python.i | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Wrapping/Python/Python.i b/Wrapping/Python/Python.i index 16f60b5fd..b374449c5 100644 --- a/Wrapping/Python/Python.i +++ b/Wrapping/Python/Python.i @@ -733,7 +733,7 @@ def GetArrayFromImage(image): return arr def GetImageFromArray( arr, isVector=False): - """Get a SimpleITK Image from a numpy array. If isVector is True, then a 3D array will be treaded as a 2D vector image, otherwise it will be treaded as a 3D image""" + """Get a SimpleITK Image from a numpy array. If isVector is True, then a 3D array will be treated as a 2D vector image, otherwise it will be treated as a 3D image""" if not HAVE_NUMPY: raise ImportError('Numpy not available.') From 8fe8a781072e7f85c566d95db4bc7f4f86fe4875 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 5 Feb 2016 15:57:16 -0500 Subject: [PATCH 144/412] BUG: Do not link against specific Python version on OS X Added new CMake macro sitk_target_link_libraries_with_dynamic_lookup, to help resolve symbols at load time and not link time. This macro is used to link loadable module against their language libraries to improve compatibility. This will help packaging on homebrew, as homebrew is starting to enforce the policy that libraries should not be linked to a specific python. Thanks to: Michka Popoff Change-Id: Idc02ecb7a567a0e8c022097ff827f51a6af2e80d --- CMake/sitkExtras.cmake | 21 +++++++++++++++++++++ CMakeLists.txt | 2 ++ Wrapping/CSharp/CMakeLists.txt | 2 +- Wrapping/Java/CMakeLists.txt | 2 +- Wrapping/Python/CMakeLists.txt | 8 +++++--- Wrapping/R/CMakeLists.txt | 4 ++-- Wrapping/Ruby/CMakeLists.txt | 3 ++- Wrapping/Tcl/CMakeLists.txt | 3 ++- 8 files changed, 36 insertions(+), 9 deletions(-) create mode 100644 CMake/sitkExtras.cmake diff --git a/CMake/sitkExtras.cmake b/CMake/sitkExtras.cmake new file mode 100644 index 000000000..a03ea48d7 --- /dev/null +++ b/CMake/sitkExtras.cmake @@ -0,0 +1,21 @@ + +# +# Link a library to a target such that the symbols are resolved at +# run-time not link-time. This should be used when compiling a +# loadable module when the symbols should be resolve from the run-time +# environment where the module is loaded, and not a specific system +# library. +# +# Specifically, for OSX it uses undefined dynamic_lookup. This is +# simular to using "-shared" on Linux where undefined symbols are +# ignored. +# +# http://blog.tim-smith.us/2015/09/python-extension-modules-os-x/ +# +macro( sitk_target_link_libraries_with_dynamic_lookup target ) + if ( ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" ) + set_target_properties( ${target} PROPERTIES LINK_FLAGS "-undefined dynamic_lookup" ) + else() + target_link_libraries ( ${target} ${ARGN} ) + endif() +endmacro() diff --git a/CMakeLists.txt b/CMakeLists.txt index bc439e9e5..fbf470117 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -56,6 +56,8 @@ find_package(ITK REQUIRED ) #we require certain packages be turned on in ITK include(sitkCheckForITKModuleDependencies) +include(sitkExtras) + if(ITK_FOUND) # NOTE: We are purposely not calling UseITK yet. However, we must make diff --git a/Wrapping/CSharp/CMakeLists.txt b/Wrapping/CSharp/CMakeLists.txt index 30f763d66..cadc54ba0 100644 --- a/Wrapping/CSharp/CMakeLists.txt +++ b/Wrapping/CSharp/CMakeLists.txt @@ -50,7 +50,7 @@ if(DEFINED SimpleITK_VERSION_POST) ${CMAKE_CURRENT_SOURCE_DIR}/CSharp.i ${CMAKE_CURRENT_SOURCE_DIR}/CSharpTypemapHelper.i ) swig_add_module(SimpleITKCSharpNative csharp SimpleITK.i) - swig_link_libraries(SimpleITKCSharpNative ${SimpleITK_LIBRARIES}) + target_link_libraries(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} ${SimpleITK_LIBRARIES}) set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CSHARP_BINARY_DIRECTORY}) if ( UNIX ) set_target_properties(${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} PROPERTIES PREFIX "lib") diff --git a/Wrapping/Java/CMakeLists.txt b/Wrapping/Java/CMakeLists.txt index 0dc5591a0..27b62432f 100644 --- a/Wrapping/Java/CMakeLists.txt +++ b/Wrapping/Java/CMakeLists.txt @@ -21,7 +21,7 @@ set(CMAKE_SWIG_OUTDIR ${JAVA_SOURCE_DIRECTORY}/org/itk/simple/) set(CMAKE_SWIG_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR} -package "org.itk.simple" ${CMAKE_SWIG_GLOBAL_FLAGS}) set(SWIG_MODULE_SimpleITKJava_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/Java.i ${CMAKE_CURRENT_SOURCE_DIR}/JavaDoc.i) SWIG_add_module ( SimpleITKJava java SimpleITK.i ) -SWIG_link_libraries(SimpleITKJava ${SimpleITK_LIBRARIES}) +target_link_libraries( ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} ${SimpleITK_LIBRARIES}) set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") sitk_strip_target( ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} ) diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index 878f64de1..f34dbf41c 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -21,11 +21,13 @@ set(SWIG_MODULE_SimpleITK_EXTRA_DEPS ${SWIG_EXTRA_DEPS} SWIG_add_module ( SimpleITK python SimpleITK.i sitkPyCommand.cxx ) -SWIG_link_libraries ( SimpleITK ${SimpleITK_LIBRARIES} ${PYTHON_LIBRARIES}) +set(SWIG_MODULE_SimpleITKPython_TARGET_NAME "${SWIG_MODULE_SimpleITK_TARGET_NAME}") +target_link_libraries ( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ${SimpleITK_LIBRARIES} ) +sitk_target_link_libraries_with_dynamic_lookup( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ${PYTHON_LIBRARIES} ) set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") -sitk_strip_target( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ) +sitk_strip_target( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ) + -set(SWIG_MODULE_SimpleITKPython_TARGET_NAME "${SWIG_MODULE_SimpleITK_TARGET_NAME}") # Installation set( SIMPLEITK_PYTHON_PACKAGE_DIR "${SimpleITK_BINARY_DIR}/Wrapping/Python" ) diff --git a/Wrapping/R/CMakeLists.txt b/Wrapping/R/CMakeLists.txt index eee8b028d..c73ac9a90 100644 --- a/Wrapping/R/CMakeLists.txt +++ b/Wrapping/R/CMakeLists.txt @@ -8,11 +8,11 @@ set(CMAKE_SWIG_FLAGS ${CMAKE_SWIG_GLOBAL_FLAGS}) set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) set(SWIG_MODULE_SimpleITK_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/R.i ) SWIG_add_module ( SimpleITK r SimpleITK.i sitkRCommand.cxx ) -SWIG_link_libraries ( SimpleITK ${SimpleITK_LIBRARIES} ) +target_link_libraries ( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ${SimpleITK_LIBRARIES} ) # on some platforms the r libraries are not required at link time... if(R_LIBRARIES) - SWIG_link_libraries ( SimpleITK ${R_LIBRARIES} ) + sitk_target_link_libraries_with_dynamic_lookup ( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ${R_LIBRARIES} ) endif() set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") diff --git a/Wrapping/Ruby/CMakeLists.txt b/Wrapping/Ruby/CMakeLists.txt index 243da30b5..5ab1d8e0d 100644 --- a/Wrapping/Ruby/CMakeLists.txt +++ b/Wrapping/Ruby/CMakeLists.txt @@ -11,6 +11,7 @@ set(SWIG_MODULE_simpleitk_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/Ruby.i) SWIG_add_module( simpleitk ruby SimpleITK.i ) -SWIG_link_libraries( simpleitk ${SimpleITK_LIBRARIES} ${RUBY_LIBRARY}) +target_link_libraries( ${SWIG_MODULE_simpleitk_TARGET_NAME} ${SimpleITK_LIBRARIES} ) +sitk_target_link_libraries_with_dynamic_lookup( ${SWIG_MODULE_simpleitk_TARGET_NAME} ${RUBY_LIBRARY} ) set_source_files_properties( ${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") sitk_strip_target( ${SWIG_MODULE_simpleitk_TARGET_NAME} ) diff --git a/Wrapping/Tcl/CMakeLists.txt b/Wrapping/Tcl/CMakeLists.txt index 2b38ac2ea..bdc686bff 100644 --- a/Wrapping/Tcl/CMakeLists.txt +++ b/Wrapping/Tcl/CMakeLists.txt @@ -10,7 +10,8 @@ set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) set(SWIG_MODULE_SimpleITKTCL_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_DIR}/Tcl.i ) set(SWIG_MODULE_SimpleITKTcl_EXTRA_DEPS ${SWIG_MODULE_SimpleITKTCL_EXTRA_DEPS}) # SWIG_add_module ( SimpleITKTcl tcl SimpleITK.i SimpleITKTCL_wrap.cxx ) -# SWIG_link_libraries ( SimpleITKTcl ${SimpleITK_LIBRARIES} ${TCL_LIBRARY}) +# target_link_libraries ( ${SWIG_MODULE_SimpleITKTcl_TARGET_NAME} ${SimpleITK_LIBRARIES} ) +# sitk_target_link_libraries_with_dynamic_lookup( ${SWIG_MODULE_SimpleITKTcl_TARGET_NAME} ${TCL_LIBRARY} ) # set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") # add_executable ( SimpleITKTclsh ${swig_generated_file_fullname} ) # target_link_libraries ( SimpleITKTclsh ${SimpleITK_LIBRARIES} ${TCL_LIBRARY}) From 493840e74752b71570d31f49e9fe25005b4ae950 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Tue, 9 Feb 2016 15:39:54 -0500 Subject: [PATCH 145/412] COMP: Macros to suppress clang warnings Clang tends to produce a plethora of warnings. This patch introduces 3 macros in sitkMacro.h to help the user suppress particular warnings. The macros sitkClangDiagnosticPush and sitkClangDiagnosticPop save and restore the state of clang's diagnostic warnings. sitkClangWarningIgnore allows the user to suppress any particular warning. To implement sitkClangWarningIgnore, we use the macro sitkMacroJoin, which is a pre-processor trick to join two macros, similar boost and ITK. The template files in this patch use the sitkClangWarningIgnore macro to suppress the "-Wunused-local-typedef" warning. Change-Id: Id724b9c2cdb6b22326e483059f8bccf647ed05f2 --- .../sitkDualImageFilterTemplate.cxx.in | 2 +- .../templates/sitkImageFilterTemplate.cxx.in | 2 +- .../templates/sitkImageSourceTemplate.cxx.in | 2 +- Code/Common/include/sitkMacro.h | 20 ++++++++++--------- 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/Code/BasicFilters/templates/sitkDualImageFilterTemplate.cxx.in b/Code/BasicFilters/templates/sitkDualImageFilterTemplate.cxx.in index 6a94dcd45..846af3003 100644 --- a/Code/BasicFilters/templates/sitkDualImageFilterTemplate.cxx.in +++ b/Code/BasicFilters/templates/sitkDualImageFilterTemplate.cxx.in @@ -135,7 +135,7 @@ $(include CustomCasts.cxx) //----------------------------------------------------------------------------- sitkClangDiagnosticPush(); -sitkClangDiagnosticIgnore("-Wunused-local-typedef"); +sitkClangWarningIgnore("-Wunused-local-typedef"); // // ExecuteInternal diff --git a/Code/BasicFilters/templates/sitkImageFilterTemplate.cxx.in b/Code/BasicFilters/templates/sitkImageFilterTemplate.cxx.in index f3f1ddcff..f9ccae45e 100644 --- a/Code/BasicFilters/templates/sitkImageFilterTemplate.cxx.in +++ b/Code/BasicFilters/templates/sitkImageFilterTemplate.cxx.in @@ -61,7 +61,7 @@ $(include CustomCasts.cxx) //----------------------------------------------------------------------------- sitkClangDiagnosticPush(); -sitkClangDiagnosticIgnore("-Wunused-local-typedef"); +sitkClangWarningIgnore("-Wunused-local-typedef"); // // ExecuteInternal diff --git a/Code/BasicFilters/templates/sitkImageSourceTemplate.cxx.in b/Code/BasicFilters/templates/sitkImageSourceTemplate.cxx.in index 691b0c93c..1735b7e5d 100644 --- a/Code/BasicFilters/templates/sitkImageSourceTemplate.cxx.in +++ b/Code/BasicFilters/templates/sitkImageSourceTemplate.cxx.in @@ -87,7 +87,7 @@ $(include CustomCasts.cxx) //----------------------------------------------------------------------------- sitkClangDiagnosticPush(); -sitkClangDiagnosticIgnore("-Wunused-local-typedef"); +sitkClangWarningIgnore("-Wunused-local-typedef"); // // ExecuteInternal diff --git a/Code/Common/include/sitkMacro.h b/Code/Common/include/sitkMacro.h index 9a246a588..7318bda36 100644 --- a/Code/Common/include/sitkMacro.h +++ b/Code/Common/include/sitkMacro.h @@ -89,6 +89,10 @@ class GenericException; #endif +#define sitkMacroJoin( X, Y ) sitkDoMacroJoin( X, Y ) +#define sitkDoMacroJoin( X, Y ) sitkDoMacroJoin2(X,Y) +#define sitkDoMacroJoin2( X, Y ) X##Y + #ifdef SITK_HAS_CXX11_STATIC_ASSERT // utilize the c++11 static_assert if available #define sitkStaticAssert( expr, str) static_assert( expr, str ) @@ -97,28 +101,26 @@ class GenericException; template struct StaticAssertFailure; template<> struct StaticAssertFailure{ enum { Value = 1 }; }; -#define BOOST_JOIN( X, Y ) BOOST_DO_JOIN( X, Y ) -#define BOOST_DO_JOIN( X, Y ) BOOST_DO_JOIN2(X,Y) -#define BOOST_DO_JOIN2( X, Y ) X##Y - -#define sitkStaticAssert( expr, str ) enum { BOOST_JOIN( static_assert_typedef, __LINE__) = sizeof( itk::simple::StaticAssertFailure<((expr) == 0 ? false : true )> ) }; +#define sitkStaticAssert( expr, str ) enum { sitkMacroJoin( static_assert_typedef, __LINE__) = sizeof( itk::simple::StaticAssertFailure<((expr) == 0 ? false : true )> ) }; #endif +} +} #define sitkPragma(x) _Pragma (#x) #if defined(__clang__) && defined(__has_warning) #define sitkClangDiagnosticPush() sitkPragma( clang diagnostic push ) #define sitkClangDiagnosticPop() sitkPragma( clang diagnostic pop ) -#define sitkClangDiagnosticIgnore(x) sitkPragma( clang diagnostic ignored x) +#define sitkClangWarningIgnore_0(x) +#define sitkClangWarningIgnore_1(x) sitkPragma( clang diagnostic ignored x) +#define sitkClangWarningIgnore(x) sitkMacroJoin( sitkClangWarningIgnore_, __has_warning(x) )(x) #else #define sitkClangDiagnosticPush() #define sitkClangDiagnosticPop() -#define sitkClangDiagnosticIgnore(x) +#define sitkClangWarningIgnore(x) #endif -} -} #endif From 805941b9c01523dae332c245e07b33c891d28098 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Wed, 10 Feb 2016 14:15:33 -0500 Subject: [PATCH 146/412] COMP: Removed anonymous namespace The anonymous namespace enclosing the inline vector functions was generating warnings with clang 5.0, so it has been removed. Change-Id: I0639113252aab9945ca0aed10fb5e09044d04ba8 --- Testing/Unit/SimpleITKTestHarness.h | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Testing/Unit/SimpleITKTestHarness.h b/Testing/Unit/SimpleITKTestHarness.h index 83e42c097..ce76431a2 100644 --- a/Testing/Unit/SimpleITKTestHarness.h +++ b/Testing/Unit/SimpleITKTestHarness.h @@ -247,9 +247,6 @@ class CountCommand }; -namespace -{ - inline std::vector v2(double v1, double v2) { @@ -307,8 +304,6 @@ inline std::vector v12(double v1, double v2, double v3, } -} - ::testing::AssertionResult VectorDoubleRMSPredFormat(const char* expr1, const char* expr2, const char* rms_error_expr, From dc25eab49ff350077bb587c2f6d2c3eb6f132011 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 23 Feb 2016 10:51:21 -0500 Subject: [PATCH 147/412] Add CMake option to build eggs Change-Id: Id258e5d1ecd389a2afa96cf1c2059223c5d3b1ec --- Wrapping/Python/CMakeLists.txt | 2 ++ Wrapping/Python/dist/CMakeLists.txt | 9 ++++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index f34dbf41c..699b42633 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -4,6 +4,8 @@ include_directories ( ${PYTHON_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ) option ( SimpleITK_PYTHON_THREADS "Enable threaded python usage by unlocking the GIL." ON ) mark_as_advanced( SimpleITK_PYTHON_THREADS ) +option ( SimpleITK_PYTHON_EGG "Add building of python eggs to the dist target." ON ) +mark_as_advanced( SimpleITK_PYTHON_EGG ) option ( SimpleITK_PYTHON_WHEEL "Add building of python wheels to the dist target." OFF ) mark_as_advanced( SimpleITK_PYTHON_WHEEL ) diff --git a/Wrapping/Python/dist/CMakeLists.txt b/Wrapping/Python/dist/CMakeLists.txt index 50a43019c..4b65ed928 100644 --- a/Wrapping/Python/dist/CMakeLists.txt +++ b/Wrapping/Python/dist/CMakeLists.txt @@ -2,14 +2,17 @@ # Packaging # -if( WRAP_PYTHON ) +if( SimpleITK_PYTHON_EGG OR SimpleITK_PYTHON_WHEEL ) - set(bdist_commands "bdist_egg") + set(bdist_commands "") + if( SimpleITK_PYTHON_EGG ) + set(bdist_commands "bdist_egg") + endif() if( SimpleITK_PYTHON_WHEEL ) set(bdist_commands ${bdist_commands} bdist_wheel) endif() - if(SITK_PYTHON_USE_VIRTUALENV) + if( SITK_PYTHON_USE_VIRTUALENV ) add_custom_target( dist.Python ${VIRTUAL_PYTHON_EXECUTABLE} ${SimpleITK_BINARY_DIR}/Wrapping/Python/Packaging/setupegg.py ${bdist_commands} WORKING_DIRECTORY ${SimpleITK_BINARY_DIR}/Wrapping/Python From ba14f0bcc203d4b3ded3e6dc22f2672724ca1954 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 23 Feb 2016 11:25:40 -0500 Subject: [PATCH 148/412] Move Python virtualenv to Superbuild Python's virtualenv is now downloaded as part of the Superbuild. This contains the full support directory with wheels for pip, setuptools and wheel itself. A system virtualenv can be provided. Change-Id: Icee6c26a488a780f70a510fadcc6c9ced99c0a3f --- SuperBuild/External_virtualenv.cmake | 34 + SuperBuild/SuperBuild.cmake | 14 + Utilities/virtualenv/LICENSE.txt | 22 - Utilities/virtualenv/virtualenv.py | 2342 ----------------- Wrapping/Python/CMakeLists.txt | 5 + .../Python/PythonVirtualEnvInstall.cmake.in | 2 +- 6 files changed, 54 insertions(+), 2365 deletions(-) create mode 100644 SuperBuild/External_virtualenv.cmake delete mode 100644 Utilities/virtualenv/LICENSE.txt delete mode 100755 Utilities/virtualenv/virtualenv.py diff --git a/SuperBuild/External_virtualenv.cmake b/SuperBuild/External_virtualenv.cmake new file mode 100644 index 000000000..2aa580b2d --- /dev/null +++ b/SuperBuild/External_virtualenv.cmake @@ -0,0 +1,34 @@ +# Make sure this file is included only once +get_filename_component(CMAKE_CURRENT_LIST_FILENAME ${CMAKE_CURRENT_LIST_FILE} NAME_WE) +if(${CMAKE_CURRENT_LIST_FILENAME}_FILE_INCLUDED) + return() +endif() +set(${CMAKE_CURRENT_LIST_FILENAME}_FILE_INCLUDED 1) + +set(proj virtualenv) + +set(${proj}_TARGET_VERSION 14.0.6) +set(${proj}_DOWNLOAD_SOURCE_HASH "a035037925c82990a7659ecf8764bcdb") + +# based on the standard EP_PREFIX locations, but since we don't build +# or install, then standars install directory is also the source +set(${proj}_binary_dir ${CMAKE_CURRENT_BINARY_DIR}/${proj}-prefix/src/${proj}-build) +set(${proj}_source_dir ${CMAKE_CURRENT_BINARY_DIR}/${proj}) +set(${proj}_install_dir ${CMAKE_CURRENT_BINARY_DIR}/${proj}) + + +ExternalProject_Add(${proj} + URL http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${${proj}_DOWNLOAD_SOURCE_HASH}&name=virtualenv-${${proj}_TARGET_VERSION}.tar.gz + URL_MD5 ${${proj}_DOWNLOAD_SOURCE_HASH} + SOURCE_DIR ${${proj}_source_dir} + BINARY_DIR ${${proj}_binary_dir} + INSTALL_DIR ${${proj}_install_dir} + UPDATE_COMMAND "" + PATCH_COMMAND "" + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" +) + +set(${proj}_ROOT ${${proj}_source_dir}) +set(PYTHON_VIRTUALENV_EXECUTABLE ${${proj}_source_dir}/virtualenv.py) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 4c793f325..bbbf5b5f3 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -290,6 +290,20 @@ if ( BUILD_TESTING ) endif() endif() +#------------------------------------------------------------------------------ +# Python virtualenv +#------------------------------------------------------------------------------ +option( USE_SYSTEM_VIRTUALENV "Use a system version of Python's virtualenv. " OFF ) +mark_as_advanced(USE_SYSTEM_VIRTUALENV) +if ( USE_SYSTEM_VIRTUALENV ) + set( PYTHON_VIRTUALENV_EXECUTABLE "" CACHE FILEPATH "Python virtualenv executable" ) +else() + include(External_virtualenv) + list(APPEND SimpleITK_VARS PYTHON_VIRTUALENV_EXECUTABLE) + list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES GTest) +endif() + + #------------------------------------------------------------------------------ # ITK #------------------------------------------------------------------------------ diff --git a/Utilities/virtualenv/LICENSE.txt b/Utilities/virtualenv/LICENSE.txt deleted file mode 100644 index 7e00d5d51..000000000 --- a/Utilities/virtualenv/LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2007 Ian Bicking and Contributors -Copyright (c) 2009 Ian Bicking, The Open Planning Project -Copyright (c) 2011-2014 The virtualenv developers - -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. diff --git a/Utilities/virtualenv/virtualenv.py b/Utilities/virtualenv/virtualenv.py deleted file mode 100755 index c9bc4b478..000000000 --- a/Utilities/virtualenv/virtualenv.py +++ /dev/null @@ -1,2342 +0,0 @@ -#!/usr/bin/env python -"""Create a "virtual" Python installation -""" - -__version__ = "1.11.2" -virtualenv_version = __version__ # legacy - -import base64 -import sys -import os -import codecs -import optparse -import re -import shutil -import logging -import tempfile -import zlib -import errno -import glob -import distutils.sysconfig -from distutils.util import strtobool -import struct -import subprocess -import tarfile - -if sys.version_info < (2, 6): - print('ERROR: %s' % sys.exc_info()[1]) - print('ERROR: this script requires Python 2.6 or greater.') - sys.exit(101) - -try: - set -except NameError: - from sets import Set as set -try: - basestring -except NameError: - basestring = str - -try: - import ConfigParser -except ImportError: - import configparser as ConfigParser - -join = os.path.join -py_version = 'python%s.%s' % (sys.version_info[0], sys.version_info[1]) - -is_jython = sys.platform.startswith('java') -is_pypy = hasattr(sys, 'pypy_version_info') -is_win = (sys.platform == 'win32') -is_cygwin = (sys.platform == 'cygwin') -is_darwin = (sys.platform == 'darwin') -abiflags = getattr(sys, 'abiflags', '') - -user_dir = os.path.expanduser('~') -if is_win: - default_storage_dir = os.path.join(user_dir, 'virtualenv') -else: - default_storage_dir = os.path.join(user_dir, '.virtualenv') -default_config_file = os.path.join(default_storage_dir, 'virtualenv.ini') - -if is_pypy: - expected_exe = 'pypy' -elif is_jython: - expected_exe = 'jython' -else: - expected_exe = 'python' - -# Return a mapping of version -> Python executable -# Only provided for Windows, where the information in the registry is used -if not is_win: - def get_installed_pythons(): - return {} -else: - try: - import winreg - except ImportError: - import _winreg as winreg - - def get_installed_pythons(): - python_core = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, - "Software\\Python\\PythonCore") - i = 0 - versions = [] - while True: - try: - versions.append(winreg.EnumKey(python_core, i)) - i = i + 1 - except WindowsError: - break - exes = dict() - for ver in versions: - path = winreg.QueryValue(python_core, "%s\\InstallPath" % ver) - exes[ver] = join(path, "python.exe") - - winreg.CloseKey(python_core) - - # Add the major versions - # Sort the keys, then repeatedly update the major version entry - # Last executable (i.e., highest version) wins with this approach - for ver in sorted(exes): - exes[ver[0]] = exes[ver] - - return exes - -REQUIRED_MODULES = ['os', 'posix', 'posixpath', 'nt', 'ntpath', 'genericpath', - 'fnmatch', 'locale', 'encodings', 'codecs', - 'stat', 'UserDict', 'readline', 'copy_reg', 'types', - 're', 'sre', 'sre_parse', 'sre_constants', 'sre_compile', - 'zlib'] - -REQUIRED_FILES = ['lib-dynload', 'config'] - -majver, minver = sys.version_info[:2] -if majver == 2: - if minver >= 6: - REQUIRED_MODULES.extend(['warnings', 'linecache', '_abcoll', 'abc']) - if minver >= 7: - REQUIRED_MODULES.extend(['_weakrefset']) - if minver <= 3: - REQUIRED_MODULES.extend(['sets', '__future__']) -elif majver == 3: - # Some extra modules are needed for Python 3, but different ones - # for different versions. - REQUIRED_MODULES.extend(['_abcoll', 'warnings', 'linecache', 'abc', 'io', - '_weakrefset', 'copyreg', 'tempfile', 'random', - '__future__', 'collections', 'keyword', 'tarfile', - 'shutil', 'struct', 'copy', 'tokenize', 'token', - 'functools', 'heapq', 'bisect', 'weakref', - 'reprlib']) - if minver >= 2: - REQUIRED_FILES[-1] = 'config-%s' % majver - if minver >= 3: - import sysconfig - platdir = sysconfig.get_config_var('PLATDIR') - REQUIRED_FILES.append(platdir) - # The whole list of 3.3 modules is reproduced below - the current - # uncommented ones are required for 3.3 as of now, but more may be - # added as 3.3 development continues. - REQUIRED_MODULES.extend([ - #"aifc", - #"antigravity", - #"argparse", - #"ast", - #"asynchat", - #"asyncore", - "base64", - #"bdb", - #"binhex", - #"bisect", - #"calendar", - #"cgi", - #"cgitb", - #"chunk", - #"cmd", - #"codeop", - #"code", - #"colorsys", - #"_compat_pickle", - #"compileall", - #"concurrent", - #"configparser", - #"contextlib", - #"cProfile", - #"crypt", - #"csv", - #"ctypes", - #"curses", - #"datetime", - #"dbm", - #"decimal", - #"difflib", - #"dis", - #"doctest", - #"dummy_threading", - "_dummy_thread", - #"email", - #"filecmp", - #"fileinput", - #"formatter", - #"fractions", - #"ftplib", - #"functools", - #"getopt", - #"getpass", - #"gettext", - #"glob", - #"gzip", - "hashlib", - #"heapq", - "hmac", - #"html", - #"http", - #"idlelib", - #"imaplib", - #"imghdr", - "imp", - "importlib", - #"inspect", - #"json", - #"lib2to3", - #"logging", - #"macpath", - #"macurl2path", - #"mailbox", - #"mailcap", - #"_markupbase", - #"mimetypes", - #"modulefinder", - #"multiprocessing", - #"netrc", - #"nntplib", - #"nturl2path", - #"numbers", - #"opcode", - #"optparse", - #"os2emxpath", - #"pdb", - #"pickle", - #"pickletools", - #"pipes", - #"pkgutil", - #"platform", - #"plat-linux2", - #"plistlib", - #"poplib", - #"pprint", - #"profile", - #"pstats", - #"pty", - #"pyclbr", - #"py_compile", - #"pydoc_data", - #"pydoc", - #"_pyio", - #"queue", - #"quopri", - #"reprlib", - "rlcompleter", - #"runpy", - #"sched", - #"shelve", - #"shlex", - #"smtpd", - #"smtplib", - #"sndhdr", - #"socket", - #"socketserver", - #"sqlite3", - #"ssl", - #"stringprep", - #"string", - #"_strptime", - #"subprocess", - #"sunau", - #"symbol", - #"symtable", - #"sysconfig", - #"tabnanny", - #"telnetlib", - #"test", - #"textwrap", - #"this", - #"_threading_local", - #"threading", - #"timeit", - #"tkinter", - #"tokenize", - #"token", - #"traceback", - #"trace", - #"tty", - #"turtledemo", - #"turtle", - #"unittest", - #"urllib", - #"uuid", - #"uu", - #"wave", - #"weakref", - #"webbrowser", - #"wsgiref", - #"xdrlib", - #"xml", - #"xmlrpc", - #"zipfile", - ]) - if minver >= 4: - REQUIRED_MODULES.extend([ - 'operator', - '_collections_abc', - '_bootlocale', - ]) - -if is_pypy: - # these are needed to correctly display the exceptions that may happen - # during the bootstrap - REQUIRED_MODULES.extend(['traceback', 'linecache']) - -class Logger(object): - - """ - Logging object for use in command-line script. Allows ranges of - levels, to avoid some redundancy of displayed information. - """ - - DEBUG = logging.DEBUG - INFO = logging.INFO - NOTIFY = (logging.INFO+logging.WARN)/2 - WARN = WARNING = logging.WARN - ERROR = logging.ERROR - FATAL = logging.FATAL - - LEVELS = [DEBUG, INFO, NOTIFY, WARN, ERROR, FATAL] - - def __init__(self, consumers): - self.consumers = consumers - self.indent = 0 - self.in_progress = None - self.in_progress_hanging = False - - def debug(self, msg, *args, **kw): - self.log(self.DEBUG, msg, *args, **kw) - def info(self, msg, *args, **kw): - self.log(self.INFO, msg, *args, **kw) - def notify(self, msg, *args, **kw): - self.log(self.NOTIFY, msg, *args, **kw) - def warn(self, msg, *args, **kw): - self.log(self.WARN, msg, *args, **kw) - def error(self, msg, *args, **kw): - self.log(self.ERROR, msg, *args, **kw) - def fatal(self, msg, *args, **kw): - self.log(self.FATAL, msg, *args, **kw) - def log(self, level, msg, *args, **kw): - if args: - if kw: - raise TypeError( - "You may give positional or keyword arguments, not both") - args = args or kw - rendered = None - for consumer_level, consumer in self.consumers: - if self.level_matches(level, consumer_level): - if (self.in_progress_hanging - and consumer in (sys.stdout, sys.stderr)): - self.in_progress_hanging = False - sys.stdout.write('\n') - sys.stdout.flush() - if rendered is None: - if args: - rendered = msg % args - else: - rendered = msg - rendered = ' '*self.indent + rendered - if hasattr(consumer, 'write'): - consumer.write(rendered+'\n') - else: - consumer(rendered) - - def start_progress(self, msg): - assert not self.in_progress, ( - "Tried to start_progress(%r) while in_progress %r" - % (msg, self.in_progress)) - if self.level_matches(self.NOTIFY, self._stdout_level()): - sys.stdout.write(msg) - sys.stdout.flush() - self.in_progress_hanging = True - else: - self.in_progress_hanging = False - self.in_progress = msg - - def end_progress(self, msg='done.'): - assert self.in_progress, ( - "Tried to end_progress without start_progress") - if self.stdout_level_matches(self.NOTIFY): - if not self.in_progress_hanging: - # Some message has been printed out since start_progress - sys.stdout.write('...' + self.in_progress + msg + '\n') - sys.stdout.flush() - else: - sys.stdout.write(msg + '\n') - sys.stdout.flush() - self.in_progress = None - self.in_progress_hanging = False - - def show_progress(self): - """If we are in a progress scope, and no log messages have been - shown, write out another '.'""" - if self.in_progress_hanging: - sys.stdout.write('.') - sys.stdout.flush() - - def stdout_level_matches(self, level): - """Returns true if a message at this level will go to stdout""" - return self.level_matches(level, self._stdout_level()) - - def _stdout_level(self): - """Returns the level that stdout runs at""" - for level, consumer in self.consumers: - if consumer is sys.stdout: - return level - return self.FATAL - - def level_matches(self, level, consumer_level): - """ - >>> l = Logger([]) - >>> l.level_matches(3, 4) - False - >>> l.level_matches(3, 2) - True - >>> l.level_matches(slice(None, 3), 3) - False - >>> l.level_matches(slice(None, 3), 2) - True - >>> l.level_matches(slice(1, 3), 1) - True - >>> l.level_matches(slice(2, 3), 1) - False - """ - if isinstance(level, slice): - start, stop = level.start, level.stop - if start is not None and start > consumer_level: - return False - if stop is not None and stop <= consumer_level: - return False - return True - else: - return level >= consumer_level - - #@classmethod - def level_for_integer(cls, level): - levels = cls.LEVELS - if level < 0: - return levels[0] - if level >= len(levels): - return levels[-1] - return levels[level] - - level_for_integer = classmethod(level_for_integer) - -# create a silent logger just to prevent this from being undefined -# will be overridden with requested verbosity main() is called. -logger = Logger([(Logger.LEVELS[-1], sys.stdout)]) - -def mkdir(path): - if not os.path.exists(path): - logger.info('Creating %s', path) - os.makedirs(path) - else: - logger.info('Directory %s already exists', path) - -def copyfileordir(src, dest, symlink=True): - if os.path.isdir(src): - shutil.copytree(src, dest, symlink) - else: - shutil.copy2(src, dest) - -def copyfile(src, dest, symlink=True): - if not os.path.exists(src): - # Some bad symlink in the src - logger.warn('Cannot find file %s (bad symlink)', src) - return - if os.path.exists(dest): - logger.debug('File %s already exists', dest) - return - if not os.path.exists(os.path.dirname(dest)): - logger.info('Creating parent directories for %s', os.path.dirname(dest)) - os.makedirs(os.path.dirname(dest)) - if not os.path.islink(src): - srcpath = os.path.abspath(src) - else: - srcpath = os.readlink(src) - if symlink and hasattr(os, 'symlink') and not is_win: - logger.info('Symlinking %s', dest) - try: - os.symlink(srcpath, dest) - except (OSError, NotImplementedError): - logger.info('Symlinking failed, copying to %s', dest) - copyfileordir(src, dest, symlink) - else: - logger.info('Copying to %s', dest) - copyfileordir(src, dest, symlink) - -def writefile(dest, content, overwrite=True): - if not os.path.exists(dest): - logger.info('Writing %s', dest) - f = open(dest, 'wb') - f.write(content.encode('utf-8')) - f.close() - return - else: - f = open(dest, 'rb') - c = f.read() - f.close() - if c != content.encode("utf-8"): - if not overwrite: - logger.notify('File %s exists with different content; not overwriting', dest) - return - logger.notify('Overwriting %s with new content', dest) - f = open(dest, 'wb') - f.write(content.encode('utf-8')) - f.close() - else: - logger.info('Content %s already in place', dest) - -def rmtree(dir): - if os.path.exists(dir): - logger.notify('Deleting tree %s', dir) - shutil.rmtree(dir) - else: - logger.info('Do not need to delete %s; already gone', dir) - -def make_exe(fn): - if hasattr(os, 'chmod'): - oldmode = os.stat(fn).st_mode & 0xFFF # 0o7777 - newmode = (oldmode | 0x16D) & 0xFFF # 0o555, 0o7777 - os.chmod(fn, newmode) - logger.info('Changed mode of %s to %s', fn, oct(newmode)) - -def _find_file(filename, dirs): - for dir in reversed(dirs): - files = glob.glob(os.path.join(dir, filename)) - if files and os.path.isfile(files[0]): - return True, files[0] - return False, filename - -def file_search_dirs(): - here = os.path.dirname(os.path.abspath(__file__)) - dirs = ['.', here, - join(here, 'virtualenv_support')] - if os.path.splitext(os.path.dirname(__file__))[0] != 'virtualenv': - # Probably some boot script; just in case virtualenv is installed... - try: - import virtualenv - except ImportError: - pass - else: - dirs.append(os.path.join(os.path.dirname(virtualenv.__file__), 'virtualenv_support')) - return [d for d in dirs if os.path.isdir(d)] - - -class UpdatingDefaultsHelpFormatter(optparse.IndentedHelpFormatter): - """ - Custom help formatter for use in ConfigOptionParser that updates - the defaults before expanding them, allowing them to show up correctly - in the help listing - """ - def expand_default(self, option): - if self.parser is not None: - self.parser.update_defaults(self.parser.defaults) - return optparse.IndentedHelpFormatter.expand_default(self, option) - - -class ConfigOptionParser(optparse.OptionParser): - """ - Custom option parser which updates its defaults by checking the - configuration files and environmental variables - """ - def __init__(self, *args, **kwargs): - self.config = ConfigParser.RawConfigParser() - self.files = self.get_config_files() - self.config.read(self.files) - optparse.OptionParser.__init__(self, *args, **kwargs) - - def get_config_files(self): - config_file = os.environ.get('VIRTUALENV_CONFIG_FILE', False) - if config_file and os.path.exists(config_file): - return [config_file] - return [default_config_file] - - def update_defaults(self, defaults): - """ - Updates the given defaults with values from the config files and - the environ. Does a little special handling for certain types of - options (lists). - """ - # Then go and look for the other sources of configuration: - config = {} - # 1. config files - config.update(dict(self.get_config_section('virtualenv'))) - # 2. environmental variables - config.update(dict(self.get_environ_vars())) - # Then set the options with those values - for key, val in config.items(): - key = key.replace('_', '-') - if not key.startswith('--'): - key = '--%s' % key # only prefer long opts - option = self.get_option(key) - if option is not None: - # ignore empty values - if not val: - continue - # handle multiline configs - if option.action == 'append': - val = val.split() - else: - option.nargs = 1 - if option.action == 'store_false': - val = not strtobool(val) - elif option.action in ('store_true', 'count'): - val = strtobool(val) - try: - val = option.convert_value(key, val) - except optparse.OptionValueError: - e = sys.exc_info()[1] - print("An error occured during configuration: %s" % e) - sys.exit(3) - defaults[option.dest] = val - return defaults - - def get_config_section(self, name): - """ - Get a section of a configuration - """ - if self.config.has_section(name): - return self.config.items(name) - return [] - - def get_environ_vars(self, prefix='VIRTUALENV_'): - """ - Returns a generator with all environmental vars with prefix VIRTUALENV - """ - for key, val in os.environ.items(): - if key.startswith(prefix): - yield (key.replace(prefix, '').lower(), val) - - def get_default_values(self): - """ - Overridding to make updating the defaults after instantiation of - the option parser possible, update_defaults() does the dirty work. - """ - if not self.process_default_values: - # Old, pre-Optik 1.5 behaviour. - return optparse.Values(self.defaults) - - defaults = self.update_defaults(self.defaults.copy()) # ours - for option in self._get_all_options(): - default = defaults.get(option.dest) - if isinstance(default, basestring): - opt_str = option.get_opt_string() - defaults[option.dest] = option.check_value(opt_str, default) - return optparse.Values(defaults) - - -def main(): - parser = ConfigOptionParser( - version=virtualenv_version, - usage="%prog [OPTIONS] DEST_DIR", - formatter=UpdatingDefaultsHelpFormatter()) - - parser.add_option( - '-v', '--verbose', - action='count', - dest='verbose', - default=0, - help="Increase verbosity.") - - parser.add_option( - '-q', '--quiet', - action='count', - dest='quiet', - default=0, - help='Decrease verbosity.') - - parser.add_option( - '-p', '--python', - dest='python', - metavar='PYTHON_EXE', - help='The Python interpreter to use, e.g., --python=python2.5 will use the python2.5 ' - 'interpreter to create the new environment. The default is the interpreter that ' - 'virtualenv was installed with (%s)' % sys.executable) - - parser.add_option( - '--clear', - dest='clear', - action='store_true', - help="Clear out the non-root install and start from scratch.") - - parser.set_defaults(system_site_packages=False) - parser.add_option( - '--no-site-packages', - dest='system_site_packages', - action='store_false', - help="DEPRECATED. Retained only for backward compatibility. " - "Not having access to global site-packages is now the default behavior.") - - parser.add_option( - '--system-site-packages', - dest='system_site_packages', - action='store_true', - help="Give the virtual environment access to the global site-packages.") - - parser.add_option( - '--always-copy', - dest='symlink', - action='store_false', - default=True, - help="Always copy files rather than symlinking.") - - parser.add_option( - '--unzip-setuptools', - dest='unzip_setuptools', - action='store_true', - help="Unzip Setuptools when installing it.") - - parser.add_option( - '--relocatable', - dest='relocatable', - action='store_true', - help='Make an EXISTING virtualenv environment relocatable. ' - 'This fixes up scripts and makes all .pth files relative.') - - parser.add_option( - '--no-setuptools', - dest='no_setuptools', - action='store_true', - help='Do not install setuptools (or pip) in the new virtualenv.') - - parser.add_option( - '--no-pip', - dest='no_pip', - action='store_true', - help='Do not install pip in the new virtualenv.') - - default_search_dirs = file_search_dirs() - parser.add_option( - '--extra-search-dir', - dest="search_dirs", - action="append", - metavar='DIR', - default=default_search_dirs, - help="Directory to look for setuptools/pip distributions in. " - "This option can be used multiple times.") - - parser.add_option( - '--never-download', - dest="never_download", - action="store_true", - default=True, - help="DEPRECATED. Retained only for backward compatibility. This option has no effect. " - "Virtualenv never downloads pip or setuptools.") - - parser.add_option( - '--prompt', - dest='prompt', - help='Provides an alternative prompt prefix for this environment.') - - parser.add_option( - '--setuptools', - dest='setuptools', - action='store_true', - help="DEPRECATED. Retained only for backward compatibility. This option has no effect.") - - parser.add_option( - '--distribute', - dest='distribute', - action='store_true', - help="DEPRECATED. Retained only for backward compatibility. This option has no effect.") - - if 'extend_parser' in globals(): - extend_parser(parser) - - options, args = parser.parse_args() - - global logger - - if 'adjust_options' in globals(): - adjust_options(options, args) - - verbosity = options.verbose - options.quiet - logger = Logger([(Logger.level_for_integer(2 - verbosity), sys.stdout)]) - - if options.python and not os.environ.get('VIRTUALENV_INTERPRETER_RUNNING'): - env = os.environ.copy() - interpreter = resolve_interpreter(options.python) - if interpreter == sys.executable: - logger.warn('Already using interpreter %s' % interpreter) - else: - logger.notify('Running virtualenv with interpreter %s' % interpreter) - env['VIRTUALENV_INTERPRETER_RUNNING'] = 'true' - file = __file__ - if file.endswith('.pyc'): - file = file[:-1] - popen = subprocess.Popen([interpreter, file] + sys.argv[1:], env=env) - raise SystemExit(popen.wait()) - - if not args: - print('You must provide a DEST_DIR') - parser.print_help() - sys.exit(2) - if len(args) > 1: - print('There must be only one argument: DEST_DIR (you gave %s)' % ( - ' '.join(args))) - parser.print_help() - sys.exit(2) - - home_dir = args[0] - - if os.environ.get('WORKING_ENV'): - logger.fatal('ERROR: you cannot run virtualenv while in a workingenv') - logger.fatal('Please deactivate your workingenv, then re-run this script') - sys.exit(3) - - if 'PYTHONHOME' in os.environ: - logger.warn('PYTHONHOME is set. You *must* activate the virtualenv before using it') - del os.environ['PYTHONHOME'] - - if options.relocatable: - make_environment_relocatable(home_dir) - return - - if not options.never_download: - logger.warn('The --never-download option is for backward compatibility only.') - logger.warn('Setting it to false is no longer supported, and will be ignored.') - - create_environment(home_dir, - site_packages=options.system_site_packages, - clear=options.clear, - unzip_setuptools=options.unzip_setuptools, - prompt=options.prompt, - search_dirs=options.search_dirs, - never_download=True, - no_setuptools=options.no_setuptools, - no_pip=options.no_pip, - symlink=options.symlink) - if 'after_install' in globals(): - after_install(options, home_dir) - -def call_subprocess(cmd, show_stdout=True, - filter_stdout=None, cwd=None, - raise_on_returncode=True, extra_env=None, - remove_from_env=None): - cmd_parts = [] - for part in cmd: - if len(part) > 45: - part = part[:20]+"..."+part[-20:] - if ' ' in part or '\n' in part or '"' in part or "'" in part: - part = '"%s"' % part.replace('"', '\\"') - if hasattr(part, 'decode'): - try: - part = part.decode(sys.getdefaultencoding()) - except UnicodeDecodeError: - part = part.decode(sys.getfilesystemencoding()) - cmd_parts.append(part) - cmd_desc = ' '.join(cmd_parts) - if show_stdout: - stdout = None - else: - stdout = subprocess.PIPE - logger.debug("Running command %s" % cmd_desc) - if extra_env or remove_from_env: - env = os.environ.copy() - if extra_env: - env.update(extra_env) - if remove_from_env: - for varname in remove_from_env: - env.pop(varname, None) - else: - env = None - try: - proc = subprocess.Popen( - cmd, stderr=subprocess.STDOUT, stdin=None, stdout=stdout, - cwd=cwd, env=env) - except Exception: - e = sys.exc_info()[1] - logger.fatal( - "Error %s while executing command %s" % (e, cmd_desc)) - raise - all_output = [] - if stdout is not None: - stdout = proc.stdout - encoding = sys.getdefaultencoding() - fs_encoding = sys.getfilesystemencoding() - while 1: - line = stdout.readline() - try: - line = line.decode(encoding) - except UnicodeDecodeError: - line = line.decode(fs_encoding) - if not line: - break - line = line.rstrip() - all_output.append(line) - if filter_stdout: - level = filter_stdout(line) - if isinstance(level, tuple): - level, line = level - logger.log(level, line) - if not logger.stdout_level_matches(level): - logger.show_progress() - else: - logger.info(line) - else: - proc.communicate() - proc.wait() - if proc.returncode: - if raise_on_returncode: - if all_output: - logger.notify('Complete output from command %s:' % cmd_desc) - logger.notify('\n'.join(all_output) + '\n----------------------------------------') - raise OSError( - "Command %s failed with error code %s" - % (cmd_desc, proc.returncode)) - else: - logger.warn( - "Command %s had error code %s" - % (cmd_desc, proc.returncode)) - -def filter_install_output(line): - if line.strip().startswith('running'): - return Logger.INFO - return Logger.DEBUG - -def find_wheels(projects, search_dirs): - """Find wheels from which we can import PROJECTS. - - Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return - a list of the first wheel found for each PROJECT - """ - - wheels = [] - - # Look through SEARCH_DIRS for the first suitable wheel. Don't bother - # about version checking here, as this is simply to get something we can - # then use to install the correct version. - for project in projects: - for dirname in search_dirs: - # This relies on only having "universal" wheels available. - # The pattern could be tightened to require -py2.py3-none-any.whl. - files = glob.glob(os.path.join(dirname, project + '-*.whl')) - if files: - wheels.append(os.path.abspath(files[0])) - break - else: - # We're out of luck, so quit with a suitable error - logger.fatal('Cannot find a wheel for %s' % (project,)) - - return wheels - -def install_wheel(project_names, py_executable, search_dirs=None): - if search_dirs is None: - search_dirs = file_search_dirs() - - wheels = find_wheels(['setuptools', 'pip'], search_dirs) - pythonpath = os.pathsep.join(wheels) - findlinks = ' '.join(search_dirs) - - cmd = [ - py_executable, '-c', - 'import sys, pip; sys.exit(pip.main(["install", "--ignore-installed"] + sys.argv[1:]))', - ] + project_names - logger.start_progress('Installing %s...' % (', '.join(project_names))) - logger.indent += 2 - try: - call_subprocess(cmd, show_stdout=False, - extra_env = { - 'PYTHONPATH': pythonpath, - 'PIP_FIND_LINKS': findlinks, - 'PIP_USE_WHEEL': '1', - 'PIP_PRE': '1', - 'PIP_NO_INDEX': '1' - } - ) - finally: - logger.indent -= 2 - logger.end_progress() - -def create_environment(home_dir, site_packages=False, clear=False, - unzip_setuptools=False, - prompt=None, search_dirs=None, never_download=False, - no_setuptools=False, no_pip=False, symlink=True): - """ - Creates a new environment in ``home_dir``. - - If ``site_packages`` is true, then the global ``site-packages/`` - directory will be on the path. - - If ``clear`` is true (default False) then the environment will - first be cleared. - """ - home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir) - - py_executable = os.path.abspath(install_python( - home_dir, lib_dir, inc_dir, bin_dir, - site_packages=site_packages, clear=clear, symlink=symlink)) - - install_distutils(home_dir) - - if not no_setuptools: - to_install = ['setuptools'] - if not no_pip: - to_install.append('pip') - install_wheel(to_install, py_executable, search_dirs) - - install_activate(home_dir, bin_dir, prompt) - -def is_executable_file(fpath): - return os.path.isfile(fpath) and os.access(fpath, os.X_OK) - -def path_locations(home_dir): - """Return the path locations for the environment (where libraries are, - where scripts go, etc)""" - # XXX: We'd use distutils.sysconfig.get_python_inc/lib but its - # prefix arg is broken: http://bugs.python.org/issue3386 - if is_win: - # Windows has lots of problems with executables with spaces in - # the name; this function will remove them (using the ~1 - # format): - mkdir(home_dir) - if ' ' in home_dir: - import ctypes - GetShortPathName = ctypes.windll.kernel32.GetShortPathNameW - size = max(len(home_dir)+1, 256) - buf = ctypes.create_unicode_buffer(size) - try: - u = unicode - except NameError: - u = str - ret = GetShortPathName(u(home_dir), buf, size) - if not ret: - print('Error: the path "%s" has a space in it' % home_dir) - print('We could not determine the short pathname for it.') - print('Exiting.') - sys.exit(3) - home_dir = str(buf.value) - lib_dir = join(home_dir, 'Lib') - inc_dir = join(home_dir, 'Include') - bin_dir = join(home_dir, 'Scripts') - if is_jython: - lib_dir = join(home_dir, 'Lib') - inc_dir = join(home_dir, 'Include') - bin_dir = join(home_dir, 'bin') - elif is_pypy: - lib_dir = home_dir - inc_dir = join(home_dir, 'include') - bin_dir = join(home_dir, 'bin') - elif not is_win: - lib_dir = join(home_dir, 'lib', py_version) - multiarch_exec = '/usr/bin/multiarch-platform' - if is_executable_file(multiarch_exec): - # In Mageia (2) and Mandriva distros the include dir must be like: - # virtualenv/include/multiarch-x86_64-linux/python2.7 - # instead of being virtualenv/include/python2.7 - p = subprocess.Popen(multiarch_exec, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - stdout, stderr = p.communicate() - # stdout.strip is needed to remove newline character - inc_dir = join(home_dir, 'include', stdout.strip(), py_version + abiflags) - else: - inc_dir = join(home_dir, 'include', py_version + abiflags) - bin_dir = join(home_dir, 'bin') - return home_dir, lib_dir, inc_dir, bin_dir - - -def change_prefix(filename, dst_prefix): - prefixes = [sys.prefix] - - if is_darwin: - prefixes.extend(( - os.path.join("/Library/Python", sys.version[:3], "site-packages"), - os.path.join(sys.prefix, "Extras", "lib", "python"), - os.path.join("~", "Library", "Python", sys.version[:3], "site-packages"), - # Python 2.6 no-frameworks - os.path.join("~", ".local", "lib","python", sys.version[:3], "site-packages"), - # System Python 2.7 on OSX Mountain Lion - os.path.join("~", "Library", "Python", sys.version[:3], "lib", "python", "site-packages"))) - - if hasattr(sys, 'real_prefix'): - prefixes.append(sys.real_prefix) - if hasattr(sys, 'base_prefix'): - prefixes.append(sys.base_prefix) - prefixes = list(map(os.path.expanduser, prefixes)) - prefixes = list(map(os.path.abspath, prefixes)) - # Check longer prefixes first so we don't split in the middle of a filename - prefixes = sorted(prefixes, key=len, reverse=True) - filename = os.path.abspath(filename) - for src_prefix in prefixes: - if filename.startswith(src_prefix): - _, relpath = filename.split(src_prefix, 1) - if src_prefix != os.sep: # sys.prefix == "/" - assert relpath[0] == os.sep - relpath = relpath[1:] - return join(dst_prefix, relpath) - assert False, "Filename %s does not start with any of these prefixes: %s" % \ - (filename, prefixes) - -def copy_required_modules(dst_prefix, symlink): - import imp - # If we are running under -p, we need to remove the current - # directory from sys.path temporarily here, so that we - # definitely get the modules from the site directory of - # the interpreter we are running under, not the one - # virtualenv.py is installed under (which might lead to py2/py3 - # incompatibility issues) - _prev_sys_path = sys.path - if os.environ.get('VIRTUALENV_INTERPRETER_RUNNING'): - sys.path = sys.path[1:] - try: - for modname in REQUIRED_MODULES: - if modname in sys.builtin_module_names: - logger.info("Ignoring built-in bootstrap module: %s" % modname) - continue - try: - f, filename, _ = imp.find_module(modname) - except ImportError: - logger.info("Cannot import bootstrap module: %s" % modname) - else: - if f is not None: - f.close() - # special-case custom readline.so on OS X, but not for pypy: - if modname == 'readline' and sys.platform == 'darwin' and not ( - is_pypy or filename.endswith(join('lib-dynload', 'readline.so'))): - dst_filename = join(dst_prefix, 'lib', 'python%s' % sys.version[:3], 'readline.so') - elif modname == 'readline' and sys.platform == 'win32': - # special-case for Windows, where readline is not a - # standard module, though it may have been installed in - # site-packages by a third-party package - pass - else: - dst_filename = change_prefix(filename, dst_prefix) - copyfile(filename, dst_filename, symlink) - if filename.endswith('.pyc'): - pyfile = filename[:-1] - if os.path.exists(pyfile): - copyfile(pyfile, dst_filename[:-1], symlink) - finally: - sys.path = _prev_sys_path - - -def subst_path(prefix_path, prefix, home_dir): - prefix_path = os.path.normpath(prefix_path) - prefix = os.path.normpath(prefix) - home_dir = os.path.normpath(home_dir) - if not prefix_path.startswith(prefix): - logger.warn('Path not in prefix %r %r', prefix_path, prefix) - return - return prefix_path.replace(prefix, home_dir, 1) - - -def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear, symlink=True): - """Install just the base environment, no distutils patches etc""" - if sys.executable.startswith(bin_dir): - print('Please use the *system* python to run this script') - return - - if clear: - rmtree(lib_dir) - ## FIXME: why not delete it? - ## Maybe it should delete everything with #!/path/to/venv/python in it - logger.notify('Not deleting %s', bin_dir) - - if hasattr(sys, 'real_prefix'): - logger.notify('Using real prefix %r' % sys.real_prefix) - prefix = sys.real_prefix - elif hasattr(sys, 'base_prefix'): - logger.notify('Using base prefix %r' % sys.base_prefix) - prefix = sys.base_prefix - else: - prefix = sys.prefix - mkdir(lib_dir) - fix_lib64(lib_dir, symlink) - stdlib_dirs = [os.path.dirname(os.__file__)] - if is_win: - stdlib_dirs.append(join(os.path.dirname(stdlib_dirs[0]), 'DLLs')) - elif is_darwin: - stdlib_dirs.append(join(stdlib_dirs[0], 'site-packages')) - if hasattr(os, 'symlink'): - logger.info('Symlinking Python bootstrap modules') - else: - logger.info('Copying Python bootstrap modules') - logger.indent += 2 - try: - # copy required files... - for stdlib_dir in stdlib_dirs: - if not os.path.isdir(stdlib_dir): - continue - for fn in os.listdir(stdlib_dir): - bn = os.path.splitext(fn)[0] - if fn != 'site-packages' and bn in REQUIRED_FILES: - copyfile(join(stdlib_dir, fn), join(lib_dir, fn), symlink) - # ...and modules - copy_required_modules(home_dir, symlink) - finally: - logger.indent -= 2 - mkdir(join(lib_dir, 'site-packages')) - import site - site_filename = site.__file__ - if site_filename.endswith('.pyc'): - site_filename = site_filename[:-1] - elif site_filename.endswith('$py.class'): - site_filename = site_filename.replace('$py.class', '.py') - site_filename_dst = change_prefix(site_filename, home_dir) - site_dir = os.path.dirname(site_filename_dst) - writefile(site_filename_dst, SITE_PY) - writefile(join(site_dir, 'orig-prefix.txt'), prefix) - site_packages_filename = join(site_dir, 'no-global-site-packages.txt') - if not site_packages: - writefile(site_packages_filename, '') - - if is_pypy or is_win: - stdinc_dir = join(prefix, 'include') - else: - stdinc_dir = join(prefix, 'include', py_version + abiflags) - if os.path.exists(stdinc_dir): - copyfile(stdinc_dir, inc_dir, symlink) - else: - logger.debug('No include dir %s' % stdinc_dir) - - platinc_dir = distutils.sysconfig.get_python_inc(plat_specific=1) - if platinc_dir != stdinc_dir: - platinc_dest = distutils.sysconfig.get_python_inc( - plat_specific=1, prefix=home_dir) - if platinc_dir == platinc_dest: - # Do platinc_dest manually due to a CPython bug; - # not http://bugs.python.org/issue3386 but a close cousin - platinc_dest = subst_path(platinc_dir, prefix, home_dir) - if platinc_dest: - # PyPy's stdinc_dir and prefix are relative to the original binary - # (traversing virtualenvs), whereas the platinc_dir is relative to - # the inner virtualenv and ignores the prefix argument. - # This seems more evolved than designed. - copyfile(platinc_dir, platinc_dest, symlink) - - # pypy never uses exec_prefix, just ignore it - if sys.exec_prefix != prefix and not is_pypy: - if is_win: - exec_dir = join(sys.exec_prefix, 'lib') - elif is_jython: - exec_dir = join(sys.exec_prefix, 'Lib') - else: - exec_dir = join(sys.exec_prefix, 'lib', py_version) - for fn in os.listdir(exec_dir): - copyfile(join(exec_dir, fn), join(lib_dir, fn), symlink) - - if is_jython: - # Jython has either jython-dev.jar and javalib/ dir, or just - # jython.jar - for name in 'jython-dev.jar', 'javalib', 'jython.jar': - src = join(prefix, name) - if os.path.exists(src): - copyfile(src, join(home_dir, name), symlink) - # XXX: registry should always exist after Jython 2.5rc1 - src = join(prefix, 'registry') - if os.path.exists(src): - copyfile(src, join(home_dir, 'registry'), symlink=False) - copyfile(join(prefix, 'cachedir'), join(home_dir, 'cachedir'), - symlink=False) - - mkdir(bin_dir) - py_executable = join(bin_dir, os.path.basename(sys.executable)) - if 'Python.framework' in prefix: - # OS X framework builds cause validation to break - # https://github.com/pypa/virtualenv/issues/322 - if os.environ.get('__PYVENV_LAUNCHER__'): - del os.environ["__PYVENV_LAUNCHER__"] - if re.search(r'/Python(?:-32|-64)*$', py_executable): - # The name of the python executable is not quite what - # we want, rename it. - py_executable = os.path.join( - os.path.dirname(py_executable), 'python') - - logger.notify('New %s executable in %s', expected_exe, py_executable) - pcbuild_dir = os.path.dirname(sys.executable) - pyd_pth = os.path.join(lib_dir, 'site-packages', 'virtualenv_builddir_pyd.pth') - if is_win and os.path.exists(os.path.join(pcbuild_dir, 'build.bat')): - logger.notify('Detected python running from build directory %s', pcbuild_dir) - logger.notify('Writing .pth file linking to build directory for *.pyd files') - writefile(pyd_pth, pcbuild_dir) - else: - pcbuild_dir = None - if os.path.exists(pyd_pth): - logger.info('Deleting %s (not Windows env or not build directory python)' % pyd_pth) - os.unlink(pyd_pth) - - if sys.executable != py_executable: - ## FIXME: could I just hard link? - executable = sys.executable - shutil.copyfile(executable, py_executable) - make_exe(py_executable) - if is_win or is_cygwin: - pythonw = os.path.join(os.path.dirname(sys.executable), 'pythonw.exe') - if os.path.exists(pythonw): - logger.info('Also created pythonw.exe') - shutil.copyfile(pythonw, os.path.join(os.path.dirname(py_executable), 'pythonw.exe')) - python_d = os.path.join(os.path.dirname(sys.executable), 'python_d.exe') - python_d_dest = os.path.join(os.path.dirname(py_executable), 'python_d.exe') - if os.path.exists(python_d): - logger.info('Also created python_d.exe') - shutil.copyfile(python_d, python_d_dest) - elif os.path.exists(python_d_dest): - logger.info('Removed python_d.exe as it is no longer at the source') - os.unlink(python_d_dest) - # we need to copy the DLL to enforce that windows will load the correct one. - # may not exist if we are cygwin. - py_executable_dll = 'python%s%s.dll' % ( - sys.version_info[0], sys.version_info[1]) - py_executable_dll_d = 'python%s%s_d.dll' % ( - sys.version_info[0], sys.version_info[1]) - pythondll = os.path.join(os.path.dirname(sys.executable), py_executable_dll) - pythondll_d = os.path.join(os.path.dirname(sys.executable), py_executable_dll_d) - pythondll_d_dest = os.path.join(os.path.dirname(py_executable), py_executable_dll_d) - if os.path.exists(pythondll): - logger.info('Also created %s' % py_executable_dll) - shutil.copyfile(pythondll, os.path.join(os.path.dirname(py_executable), py_executable_dll)) - if os.path.exists(pythondll_d): - logger.info('Also created %s' % py_executable_dll_d) - shutil.copyfile(pythondll_d, pythondll_d_dest) - elif os.path.exists(pythondll_d_dest): - logger.info('Removed %s as the source does not exist' % pythondll_d_dest) - os.unlink(pythondll_d_dest) - if is_pypy: - # make a symlink python --> pypy-c - python_executable = os.path.join(os.path.dirname(py_executable), 'python') - if sys.platform in ('win32', 'cygwin'): - python_executable += '.exe' - logger.info('Also created executable %s' % python_executable) - copyfile(py_executable, python_executable, symlink) - - if is_win: - for name in 'libexpat.dll', 'libpypy.dll', 'libpypy-c.dll', 'libeay32.dll', 'ssleay32.dll', 'sqlite.dll': - src = join(prefix, name) - if os.path.exists(src): - copyfile(src, join(bin_dir, name), symlink) - - if os.path.splitext(os.path.basename(py_executable))[0] != expected_exe: - secondary_exe = os.path.join(os.path.dirname(py_executable), - expected_exe) - py_executable_ext = os.path.splitext(py_executable)[1] - if py_executable_ext.lower() == '.exe': - # python2.4 gives an extension of '.4' :P - secondary_exe += py_executable_ext - if os.path.exists(secondary_exe): - logger.warn('Not overwriting existing %s script %s (you must use %s)' - % (expected_exe, secondary_exe, py_executable)) - else: - logger.notify('Also creating executable in %s' % secondary_exe) - shutil.copyfile(sys.executable, secondary_exe) - make_exe(secondary_exe) - - if '.framework' in prefix: - if 'Python.framework' in prefix: - logger.debug('MacOSX Python framework detected') - # Make sure we use the the embedded interpreter inside - # the framework, even if sys.executable points to - # the stub executable in ${sys.prefix}/bin - # See http://groups.google.com/group/python-virtualenv/ - # browse_thread/thread/17cab2f85da75951 - original_python = os.path.join( - prefix, 'Resources/Python.app/Contents/MacOS/Python') - if 'EPD' in prefix: - logger.debug('EPD framework detected') - original_python = os.path.join(prefix, 'bin/python') - shutil.copy(original_python, py_executable) - - # Copy the framework's dylib into the virtual - # environment - virtual_lib = os.path.join(home_dir, '.Python') - - if os.path.exists(virtual_lib): - os.unlink(virtual_lib) - copyfile( - os.path.join(prefix, 'Python'), - virtual_lib, - symlink) - - # And then change the install_name of the copied python executable - try: - mach_o_change(py_executable, - os.path.join(prefix, 'Python'), - '@executable_path/../.Python') - except: - e = sys.exc_info()[1] - logger.warn("Could not call mach_o_change: %s. " - "Trying to call install_name_tool instead." % e) - try: - call_subprocess( - ["install_name_tool", "-change", - os.path.join(prefix, 'Python'), - '@executable_path/../.Python', - py_executable]) - except: - logger.fatal("Could not call install_name_tool -- you must " - "have Apple's development tools installed") - raise - - if not is_win: - # Ensure that 'python', 'pythonX' and 'pythonX.Y' all exist - py_exe_version_major = 'python%s' % sys.version_info[0] - py_exe_version_major_minor = 'python%s.%s' % ( - sys.version_info[0], sys.version_info[1]) - py_exe_no_version = 'python' - required_symlinks = [ py_exe_no_version, py_exe_version_major, - py_exe_version_major_minor ] - - py_executable_base = os.path.basename(py_executable) - - if py_executable_base in required_symlinks: - # Don't try to symlink to yourself. - required_symlinks.remove(py_executable_base) - - for pth in required_symlinks: - full_pth = join(bin_dir, pth) - if os.path.exists(full_pth): - os.unlink(full_pth) - if symlink: - os.symlink(py_executable_base, full_pth) - else: - copyfile(py_executable, full_pth, symlink) - - if is_win and ' ' in py_executable: - # There's a bug with subprocess on Windows when using a first - # argument that has a space in it. Instead we have to quote - # the value: - py_executable = '"%s"' % py_executable - # NOTE: keep this check as one line, cmd.exe doesn't cope with line breaks - cmd = [py_executable, '-c', 'import sys;out=sys.stdout;' - 'getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))'] - logger.info('Testing executable with %s %s "%s"' % tuple(cmd)) - try: - proc = subprocess.Popen(cmd, - stdout=subprocess.PIPE) - proc_stdout, proc_stderr = proc.communicate() - except OSError: - e = sys.exc_info()[1] - if e.errno == errno.EACCES: - logger.fatal('ERROR: The executable %s could not be run: %s' % (py_executable, e)) - sys.exit(100) - else: - raise e - - proc_stdout = proc_stdout.strip().decode("utf-8") - proc_stdout = os.path.normcase(os.path.abspath(proc_stdout)) - norm_home_dir = os.path.normcase(os.path.abspath(home_dir)) - if hasattr(norm_home_dir, 'decode'): - norm_home_dir = norm_home_dir.decode(sys.getfilesystemencoding()) - if proc_stdout != norm_home_dir: - logger.fatal( - 'ERROR: The executable %s is not functioning' % py_executable) - logger.fatal( - 'ERROR: It thinks sys.prefix is %r (should be %r)' - % (proc_stdout, norm_home_dir)) - logger.fatal( - 'ERROR: virtualenv is not compatible with this system or executable') - if is_win: - logger.fatal( - 'Note: some Windows users have reported this error when they ' - 'installed Python for "Only this user" or have multiple ' - 'versions of Python installed. Copying the appropriate ' - 'PythonXX.dll to the virtualenv Scripts/ directory may fix ' - 'this problem.') - sys.exit(100) - else: - logger.info('Got sys.prefix result: %r' % proc_stdout) - - pydistutils = os.path.expanduser('~/.pydistutils.cfg') - if os.path.exists(pydistutils): - logger.notify('Please make sure you remove any previous custom paths from ' - 'your %s file.' % pydistutils) - ## FIXME: really this should be calculated earlier - - fix_local_scheme(home_dir, symlink) - - if site_packages: - if os.path.exists(site_packages_filename): - logger.info('Deleting %s' % site_packages_filename) - os.unlink(site_packages_filename) - - return py_executable - - -def install_activate(home_dir, bin_dir, prompt=None): - home_dir = os.path.abspath(home_dir) - if is_win or is_jython and os._name == 'nt': - files = { - 'activate.bat': ACTIVATE_BAT, - 'deactivate.bat': DEACTIVATE_BAT, - 'activate.ps1': ACTIVATE_PS, - } - - # MSYS needs paths of the form /c/path/to/file - drive, tail = os.path.splitdrive(home_dir.replace(os.sep, '/')) - home_dir_msys = (drive and "/%s%s" or "%s%s") % (drive[:1], tail) - - # Run-time conditional enables (basic) Cygwin compatibility - home_dir_sh = ("""$(if [ "$OSTYPE" "==" "cygwin" ]; then cygpath -u '%s'; else echo '%s'; fi;)""" % - (home_dir, home_dir_msys)) - files['activate'] = ACTIVATE_SH.replace('__VIRTUAL_ENV__', home_dir_sh) - - else: - files = {'activate': ACTIVATE_SH} - - # suppling activate.fish in addition to, not instead of, the - # bash script support. - files['activate.fish'] = ACTIVATE_FISH - - # same for csh/tcsh support... - files['activate.csh'] = ACTIVATE_CSH - - files['activate_this.py'] = ACTIVATE_THIS - if hasattr(home_dir, 'decode'): - home_dir = home_dir.decode(sys.getfilesystemencoding()) - vname = os.path.basename(home_dir) - for name, content in files.items(): - content = content.replace('__VIRTUAL_PROMPT__', prompt or '') - content = content.replace('__VIRTUAL_WINPROMPT__', prompt or '(%s)' % vname) - content = content.replace('__VIRTUAL_ENV__', home_dir) - content = content.replace('__VIRTUAL_NAME__', vname) - content = content.replace('__BIN_NAME__', os.path.basename(bin_dir)) - writefile(os.path.join(bin_dir, name), content) - -def install_distutils(home_dir): - distutils_path = change_prefix(distutils.__path__[0], home_dir) - mkdir(distutils_path) - ## FIXME: maybe this prefix setting should only be put in place if - ## there's a local distutils.cfg with a prefix setting? - home_dir = os.path.abspath(home_dir) - ## FIXME: this is breaking things, removing for now: - #distutils_cfg = DISTUTILS_CFG + "\n[install]\nprefix=%s\n" % home_dir - writefile(os.path.join(distutils_path, '__init__.py'), DISTUTILS_INIT) - writefile(os.path.join(distutils_path, 'distutils.cfg'), DISTUTILS_CFG, overwrite=False) - -def fix_local_scheme(home_dir, symlink=True): - """ - Platforms that use the "posix_local" install scheme (like Ubuntu with - Python 2.7) need to be given an additional "local" location, sigh. - """ - try: - import sysconfig - except ImportError: - pass - else: - if sysconfig._get_default_scheme() == 'posix_local': - local_path = os.path.join(home_dir, 'local') - if not os.path.exists(local_path): - os.mkdir(local_path) - for subdir_name in os.listdir(home_dir): - if subdir_name == 'local': - continue - copyfile(os.path.abspath(os.path.join(home_dir, subdir_name)), \ - os.path.join(local_path, subdir_name), symlink) - -def fix_lib64(lib_dir, symlink=True): - """ - Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y - instead of lib/pythonX.Y. If this is such a platform we'll just create a - symlink so lib64 points to lib - """ - if [p for p in distutils.sysconfig.get_config_vars().values() - if isinstance(p, basestring) and 'lib64' in p]: - # PyPy's library path scheme is not affected by this. - # Return early or we will die on the following assert. - if is_pypy: - logger.debug('PyPy detected, skipping lib64 symlinking') - return - - logger.debug('This system uses lib64; symlinking lib64 to lib') - - assert os.path.basename(lib_dir) == 'python%s' % sys.version[:3], ( - "Unexpected python lib dir: %r" % lib_dir) - lib_parent = os.path.dirname(lib_dir) - top_level = os.path.dirname(lib_parent) - lib_dir = os.path.join(top_level, 'lib') - lib64_link = os.path.join(top_level, 'lib64') - assert os.path.basename(lib_parent) == 'lib', ( - "Unexpected parent dir: %r" % lib_parent) - if os.path.lexists(lib64_link): - return - cp_or_ln = (os.symlink if symlink else copyfile) - cp_or_ln('lib', lib64_link) - -def resolve_interpreter(exe): - """ - If the executable given isn't an absolute path, search $PATH for the interpreter - """ - # If the "executable" is a version number, get the installed executable for - # that version - python_versions = get_installed_pythons() - if exe in python_versions: - exe = python_versions[exe] - - if os.path.abspath(exe) != exe: - paths = os.environ.get('PATH', '').split(os.pathsep) - for path in paths: - if os.path.exists(os.path.join(path, exe)): - exe = os.path.join(path, exe) - break - if not os.path.exists(exe): - logger.fatal('The executable %s (from --python=%s) does not exist' % (exe, exe)) - raise SystemExit(3) - if not is_executable(exe): - logger.fatal('The executable %s (from --python=%s) is not executable' % (exe, exe)) - raise SystemExit(3) - return exe - -def is_executable(exe): - """Checks a file is executable""" - return os.access(exe, os.X_OK) - -############################################################ -## Relocating the environment: - -def make_environment_relocatable(home_dir): - """ - Makes the already-existing environment use relative paths, and takes out - the #!-based environment selection in scripts. - """ - home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir) - activate_this = os.path.join(bin_dir, 'activate_this.py') - if not os.path.exists(activate_this): - logger.fatal( - 'The environment doesn\'t have a file %s -- please re-run virtualenv ' - 'on this environment to update it' % activate_this) - fixup_scripts(home_dir, bin_dir) - fixup_pth_and_egg_link(home_dir) - ## FIXME: need to fix up distutils.cfg - -OK_ABS_SCRIPTS = ['python', 'python%s' % sys.version[:3], - 'activate', 'activate.bat', 'activate_this.py', - 'activate.fish', 'activate.csh'] - -def fixup_scripts(home_dir, bin_dir): - if is_win: - new_shebang_args = ( - '%s /c' % os.path.normcase(os.environ.get('COMSPEC', 'cmd.exe')), - '', '.exe') - else: - new_shebang_args = ('/usr/bin/env', sys.version[:3], '') - - # This is what we expect at the top of scripts: - shebang = '#!%s' % os.path.normcase(os.path.join( - os.path.abspath(bin_dir), 'python%s' % new_shebang_args[2])) - # This is what we'll put: - new_shebang = '#!%s python%s%s' % new_shebang_args - - for filename in os.listdir(bin_dir): - filename = os.path.join(bin_dir, filename) - if not os.path.isfile(filename): - # ignore subdirs, e.g. .svn ones. - continue - f = open(filename, 'rb') - try: - try: - lines = f.read().decode('utf-8').splitlines() - except UnicodeDecodeError: - # This is probably a binary program instead - # of a script, so just ignore it. - continue - finally: - f.close() - if not lines: - logger.warn('Script %s is an empty file' % filename) - continue - - old_shebang = lines[0].strip() - old_shebang = old_shebang[0:2] + os.path.normcase(old_shebang[2:]) - - if not old_shebang.startswith(shebang): - if os.path.basename(filename) in OK_ABS_SCRIPTS: - logger.debug('Cannot make script %s relative' % filename) - elif lines[0].strip() == new_shebang: - logger.info('Script %s has already been made relative' % filename) - else: - logger.warn('Script %s cannot be made relative (it\'s not a normal script that starts with %s)' - % (filename, shebang)) - continue - logger.notify('Making script %s relative' % filename) - script = relative_script([new_shebang] + lines[1:]) - f = open(filename, 'wb') - f.write('\n'.join(script).encode('utf-8')) - f.close() - -def relative_script(lines): - "Return a script that'll work in a relocatable environment." - activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, activate_this" - # Find the last future statement in the script. If we insert the activation - # line before a future statement, Python will raise a SyntaxError. - activate_at = None - for idx, line in reversed(list(enumerate(lines))): - if line.split()[:3] == ['from', '__future__', 'import']: - activate_at = idx + 1 - break - if activate_at is None: - # Activate after the shebang. - activate_at = 1 - return lines[:activate_at] + ['', activate, ''] + lines[activate_at:] - -def fixup_pth_and_egg_link(home_dir, sys_path=None): - """Makes .pth and .egg-link files use relative paths""" - home_dir = os.path.normcase(os.path.abspath(home_dir)) - if sys_path is None: - sys_path = sys.path - for path in sys_path: - if not path: - path = '.' - if not os.path.isdir(path): - continue - path = os.path.normcase(os.path.abspath(path)) - if not path.startswith(home_dir): - logger.debug('Skipping system (non-environment) directory %s' % path) - continue - for filename in os.listdir(path): - filename = os.path.join(path, filename) - if filename.endswith('.pth'): - if not os.access(filename, os.W_OK): - logger.warn('Cannot write .pth file %s, skipping' % filename) - else: - fixup_pth_file(filename) - if filename.endswith('.egg-link'): - if not os.access(filename, os.W_OK): - logger.warn('Cannot write .egg-link file %s, skipping' % filename) - else: - fixup_egg_link(filename) - -def fixup_pth_file(filename): - lines = [] - prev_lines = [] - f = open(filename) - prev_lines = f.readlines() - f.close() - for line in prev_lines: - line = line.strip() - if (not line or line.startswith('#') or line.startswith('import ') - or os.path.abspath(line) != line): - lines.append(line) - else: - new_value = make_relative_path(filename, line) - if line != new_value: - logger.debug('Rewriting path %s as %s (in %s)' % (line, new_value, filename)) - lines.append(new_value) - if lines == prev_lines: - logger.info('No changes to .pth file %s' % filename) - return - logger.notify('Making paths in .pth file %s relative' % filename) - f = open(filename, 'w') - f.write('\n'.join(lines) + '\n') - f.close() - -def fixup_egg_link(filename): - f = open(filename) - link = f.readline().strip() - f.close() - if os.path.abspath(link) != link: - logger.debug('Link in %s already relative' % filename) - return - new_link = make_relative_path(filename, link) - logger.notify('Rewriting link %s in %s as %s' % (link, filename, new_link)) - f = open(filename, 'w') - f.write(new_link) - f.close() - -def make_relative_path(source, dest, dest_is_directory=True): - """ - Make a filename relative, where the filename is dest, and it is - being referred to from the filename source. - - >>> make_relative_path('/usr/share/something/a-file.pth', - ... '/usr/share/another-place/src/Directory') - '../another-place/src/Directory' - >>> make_relative_path('/usr/share/something/a-file.pth', - ... '/home/user/src/Directory') - '../../../home/user/src/Directory' - >>> make_relative_path('/usr/share/a-file.pth', '/usr/share/') - './' - """ - source = os.path.dirname(source) - if not dest_is_directory: - dest_filename = os.path.basename(dest) - dest = os.path.dirname(dest) - dest = os.path.normpath(os.path.abspath(dest)) - source = os.path.normpath(os.path.abspath(source)) - dest_parts = dest.strip(os.path.sep).split(os.path.sep) - source_parts = source.strip(os.path.sep).split(os.path.sep) - while dest_parts and source_parts and dest_parts[0] == source_parts[0]: - dest_parts.pop(0) - source_parts.pop(0) - full_parts = ['..']*len(source_parts) + dest_parts - if not dest_is_directory: - full_parts.append(dest_filename) - if not full_parts: - # Special case for the current directory (otherwise it'd be '') - return './' - return os.path.sep.join(full_parts) - - - -############################################################ -## Bootstrap script creation: - -def create_bootstrap_script(extra_text, python_version=''): - """ - Creates a bootstrap script, which is like this script but with - extend_parser, adjust_options, and after_install hooks. - - This returns a string that (written to disk of course) can be used - as a bootstrap script with your own customizations. The script - will be the standard virtualenv.py script, with your extra text - added (your extra text should be Python code). - - If you include these functions, they will be called: - - ``extend_parser(optparse_parser)``: - You can add or remove options from the parser here. - - ``adjust_options(options, args)``: - You can change options here, or change the args (if you accept - different kinds of arguments, be sure you modify ``args`` so it is - only ``[DEST_DIR]``). - - ``after_install(options, home_dir)``: - - After everything is installed, this function is called. This - is probably the function you are most likely to use. An - example would be:: - - def after_install(options, home_dir): - subprocess.call([join(home_dir, 'bin', 'easy_install'), - 'MyPackage']) - subprocess.call([join(home_dir, 'bin', 'my-package-script'), - 'setup', home_dir]) - - This example immediately installs a package, and runs a setup - script from that package. - - If you provide something like ``python_version='2.5'`` then the - script will start with ``#!/usr/bin/env python2.5`` instead of - ``#!/usr/bin/env python``. You can use this when the script must - be run with a particular Python version. - """ - filename = __file__ - if filename.endswith('.pyc'): - filename = filename[:-1] - f = codecs.open(filename, 'r', encoding='utf-8') - content = f.read() - f.close() - py_exe = 'python%s' % python_version - content = (('#!/usr/bin/env %s\n' % py_exe) - + '## WARNING: This file is generated\n' - + content) - return content.replace('##EXT' 'END##', extra_text) - -##EXTEND## - -def convert(s): - b = base64.b64decode(s.encode('ascii')) - return zlib.decompress(b).decode('utf-8') - -##file site.py -SITE_PY = convert(""" -eJzFPf1z2zaWv/OvwMqToZTIdOJ0e3tOnRsncVrvuYm3SWdz63q0lARZrCmSJUjL2pu7v/3eBwAC -JCXbm+6cphNLJPDw8PC+8PAeOhgMTopCZnOxyud1KoWScTlbiiKulkos8lJUy6Sc7xdxWW3g6ewm -vpZKVLlQGxVhqygInn7lJ3gqPi8TZVCAb3Fd5au4SmZxmm5EsiryspJzMa/LJLsWSZZUSZwm/4AW -eRaJp1+PQXCWCZh5mshS3MpSAVwl8oW42FTLPBPDusA5v4j+GL8cjYWalUlRQYNS4wwUWcZVkEk5 -BzShZa2AlEkl91UhZ8kimdmG67xO56JI45kUf/87T42ahmGg8pVcL2UpRQbIAEwJsArEA74mpZjl -cxkJ8UbOYhyAnzfEChjaGNdMIRmzXKR5dg1zyuRMKhWXGzGc1hUBIpTFPAecEsCgStI0WOfljRrB -ktJ6rOGRiJk9/Mkwe8A8cfwu5wCOH7Pg5yy5GzNs4B4EVy2ZbUq5SO5EjGDhp7yTs4l+NkwWYp4s -FkCDrBphk4ARUCJNpgcFLcd3eoVeHxBWlitjGEMiytyYX1KPKDirRJwqYNu6QBopwvydnCZxBtTI -bmE4gAgkDfrGmSeqsuPQ7EQOAEpcxwqkZKXEcBUnGTDrj/GM0P5rks3ztRoRBWC1lPi1VpU7/2EP -AaC1Q4BxgItlVrPO0uRGppsRIPAZsC+lqtMKBWKelHJW5WUiFQEA1DZC3gHSYxGXUpOQOdPI7Zjo -TzRJMlxYFDAUeHyJJFkk13VJEiYWCXAucMX7jz+Jd6dvzk4+aB4zwFhmr1eAM0ChhXZwggHEQa3K -gzQHgY6Cc/wj4vkchewaxwe8mgYH9650MIS5F1G7j7PgQHa9uHoYmGMFyoTGCqjff0OXsVoCff7n -nvUOgpNtVKGJ87f1MgeZzOKVFMuY+Qs5I/hOw3kdFdXyFXCDQjgVkErh4iCCCcIDkrg0G+aZFAWw -WJpkchQAhabU1l9FYIUPebZPa93iBIBQBhm8dJ6NaMRMwkS7sF6hvjCNNzQz3SSw67zKS1IcwP/Z -jHRRGmc3hKMihuJvU3mdZBkihLwQhHshDaxuEuDEeSTOqRXpBdNIhKy9uCWKRA28hEwHPCnv4lWR -yjGLL+rW3WqEBpOVMGudMsdBy4rUK61aM9Ve3juMvrS4jtCslqUE4PXUE7pFno/FFHQ2YVPEKxav -ap0T5wQ98kSdkCeoJfTF70DRE6XqlbQvkVdAsxBDBYs8TfM1kOwoCITYw0bGKPvMCW/hHfwLcPHf -VFazZRA4I1nAGhQivw0UAgGTIDPN1RoJj9s0K7eVTJKxpsjLuSxpqIcR+4ARf2BjnGvwIa+0UePp -4irnq6RClTTVJjNhi5eFFevHVzxvmAZYbkU0M00bOq1wemmxjKfSuCRTuUBJ0Iv0yi47jBn0jEm2 -uBIrtjLwDsgiE7Yg/YoFlc6ikuQEAAwWvjhLijqlRgoZTMQw0Kog+KsYTXqunSVgbzbLASokNt8z -sD+A2z9AjNbLBOgzAwigYVBLwfJNk6pEB6HRR4Fv9E1/Hh849WyhbRMPuYiTVFv5OAvO6OFpWZL4 -zmSBvcaaGApmmFXo2l1nQEcU88FgEATGHdoo8zVXQVVujoAVhBlnMpnWCRq+yQRNvf6hAh5FOAN7 -3Ww7Cw80hOn0AajkdFmU+Qpf27l9AmUCY2GPYE9ckJaR7CB7nPgKyeeq9MI0RdvtsLNAPRRc/HT6 -/uzL6SdxLC4blTZu67MrGPM0i4GtySIAU7WGbXQZtETFl6DuE+/BvBNTgD2j3iS+Mq5q4F1A/XNZ -02uYxsx7GZx+OHlzfjr5+dPpT5NPZ59PAUGwMzLYoymjeazBYVQRCAdw5VxF2r4GnR704M3JJ/sg -mCRq8u03wG7wZHgtK2DicggzHotwFd8pYNBwTE1HiGOnAVjwcDQSr8Xh06cvDwlasSk2AAzMrtMU -H060RZ8k2SIPR9T4V3bpj1lJaf/t8uibK3F8LMJf49s4DMCHapoyS/xI4vR5U0joWsGfYa5GQTCX -CxC9G4kCOnxKfvGIO8CSQMtc2+lf8yQz75kr3SFIfwypB+AwmczSWClsPJmEQATq0POBDhE71yh1 -Q+hYbNyuI40KfkoJC5thlzH+04NiPKV+iAaj6HYxjUBcV7NYSW5F04d+kwnqrMlkqAcEYSaJAYeL -1VAoTBPUWWUCfi1xHuqwqcpT/InwUQuQAOLWCrUkLpLeOkW3cVpLNXQmBUQcDltkREWbKOJHcFGG -YImbpRuN2tQ0PAPNgHxpDlq0bFEOP3vg74C6Mps43Ojx3otphpj+mXcahAO4nCGqe6VaUFg7iovT -C/Hy+eE+ujOw55xb6njN0UInWS3twwWslpEHRph7GXlx6bJAPYtPj3bDXEV2ZbqssNBLXMpVfivn -gC0ysLPK4id6AztzmMcshlUEvU7+AKtQ4zfGuA/l2YO0oO8A1FsRFLP+Zun3OBggMwWKiDfWRGq9 -62dTWJT5bYLOxnSjX4KtBGWJFtM4NoGzcB6ToUkEDQFecIaUWssQ1GFZs8NKeCNItBfzRrFGBO4c -NfUVfb3J8nU24Z3wMSrd4ciyLgqWZl5s0CzBnngPVgiQzGFj1xCNoYDLL1C29gF5mD5MFyhLewsA -BIZe0XbNgWW2ejRF3jXisAhj9EqQ8JYS/YVbMwRttQwxHEj0NrIPjJZASDA5q+CsatBMhrJmmsHA -Dkl8rjuPeAvqA2hRMQKzOdTQuJGh3+URKGdx7iolpx9a5C9fvjDbqCXFVxCxKU4aXYgFGcuo2IBh -TUAnGI+MozXEBmtwbgFMrTRriv1PIi/YG4P1vNCyDX4A7O6qqjg6OFiv15GOLuTl9YFaHPzxT99+ -+6fnrBPnc+IfmI4jLTrUFh3QO/Roo++MBXptVq7Fj0nmcyPBGkryysgVRfy+r5N5Lo72R1Z/Ihc3 -Zhr/Na4MKJCJGZSpDLQdNBg9UftPopdqIJ6QdbZthyP2S7RJtVbMt7rQo8rBEwC/ZZbXaKobTlDi -GVg32KHP5bS+Du3gno00P2CqKKdDywP7L64QA58zDF8ZUzxBLUFsgRbfIf1PzDYxeUdaQyB50UR1 -ds+bfi1miDt/uLxbX9MRGjPDRCF3oET4TR4sgLZxV3Lwo11btHuOa2s+niEwlj4wzKsdyyEKDuGC -azF2pc7havR4QZrWrJpBwbiqERQ0OIlTprYGRzYyRJDo3ZjNPi+sbgF0akUOTXzArAK0cMfpWLs2 -KzieEPLAsXhBTyS4yEedd895aes0pYBOi0c9qjBgb6HRTufAl0MDYCwG5c8Dbmm2KR9bi8Jr0AMs -5xgQMtiiw0z4xvUBB3uDHnbqWP1tvZnGfSBwkYYci3oQdEL5mEcoFUhTMfR7bmNxS9zuYDstDjGV -WSYSabVFuNrKo1eodhqmRZKh7nUWKZqlOXjFVisSIzXvfWeB9kH4uM+YaQnUZGjI4TQ6Jm/PE8BQ -t8Pw2XWNgQY3DoMYrRJF1g3JtIR/wK2g+AYFo4CWBM2CeaiU+RP7HWTOzld/2cIeltDIEG7TbW5I -x2JoOOb9nkAy6mgMSEEGJOwKI7mOrA5S4DBngTzhhtdyq3QTjEiBnDkWhNQM4E4vvQ0OPonwBIQk -FCHfVUoW4pkYwPK1RfVhuvt35VIThBg6DchV0NGLYzey4UQ1jltRDp+h/fgGnZUUOXDwFFweN9Dv -srlhWht0AWfdV9wWKdDIFIcZjFxUrwxh3GDyH46dFg2xzCCGobyBvCMdM9IosMutQcOCGzDemrfH -0o/diAX2HYa5OpSrO9j/hWWiZrkKKWbSjl24H80VXdpYbM+T6QD+eAswGF15kGSq4xcYZfknBgk9 -6GEfdG+yGBaZx+U6yUJSYJp+x/7SdPCwpPSM3MEn2k4dwEQx4nnwvgQBoaPPAxAn1ASwK5eh0m5/ -F+zOKQ4sXO4+8Nzmy6OXV13ijrdFeOynf6lO76oyVrhaKS8aCwWuVteAo9KFycXZRh9e6sNt3CaU -uYJdpPj46YtAQnBcdx1vHjf1huERm3vn5H0M6qDX7iVXa3bELoAIakVklIPw8Rz5cGQfO7kdE3sE -kEcxzI5FMZA0n/wzcHYtFIyxP99kGEdrqwz8wOtvv5n0REZdJL/9ZnDPKC1i9In9sOUJ2pE5qWDX -bEsZp+RqOH0oqJg1rGPbFCPW57T90zx21eNzarRs7Lu/BX4MFAypS/ARno8bsnWnih/fndoKT9up -HcA6u1Xz2aNFgL19Pv0VdshKB9Vu4ySlcwWY/P4+Klezued4Rb/28CDtVDAOCfr2X+ryOXBDyNGE -UXc62hk7MQHnnl2w+RSx6qKyp3MImiMwLy/APf7sQtUWzDDucz5eOOxRTd6M+5yJr1Gr+PldNJAF -5tFg0Ef2rez4/zHL5/+aST5wKubk+ne0ho8E9HvNhI0HQ9PGw4fVv+yu3TXAHmCetridO9zC7tB8 -Vrkwzh2rJCWeou56KtaUrkCxVTwpAihz9vt64OAy6kPvt3VZ8tE1qcBClvt4HDsWmKllPL9eE7Mn -Dj7ICjGxzWYUq3byevI+NRLq6LOdSdjsG/rlbJmbmJXMbpMS+oLCHYY/fPzxNOw3IRjHhU4PtyIP -9xsQ7iOYNtTECR/Thyn0mC7/vFS1ty4+QU1GgIkIa7L12gc/EGziCP1rcE9EyDuw5WN23KHPlnJ2 -M5GUOoBsil2doPhbfI2Y2IwCP/9LxQtKYoOZzNIaacWON2YfLupsRucjlQT/SqcKY+oQJQRw+G+R -xtdiSJ3nGHrS3EjRqdu41N5nUeaYnCrqZH5wncyF/K2OU9zWy8UCcMHDK/0q4uEpAiXecU4DJy0q -OavLpNoACWKV67M/Sn9wGk43PNGhhyQf8zABMSHiSHzCaeN7JtzckMsEB/wTD5wk7ruxg5OsENFz -eJ/lExx1Qjm+Y0aqey5Pj4P2CDkAGABQmP9gpCN3/htJr9wDRlpzl6ioJT1SupGGnJwxhDIcYaSD -f9NPnxFd3tqC5fV2LK93Y3ndxvK6F8trH8vr3Vi6IoELa4NWRhL6AlftY43efBs35sTDnMazJbfD -3E/M8QSIojAbbCNTnALtRbb4fI+AkNp2DpzpYZM/k3BSaZlzCFyDRO7HQyy9mTfJ605nysbRnXkq -xp3dlkPk9z2IIkoVm1J3lrd5XMWRJxfXaT4FsbXojhsAY9FOJ+JYaXY7mXJ0t2WpBhf/9fmHjx+w -OYIamPQG6oaLiIYFpzJ8GpfXqitNzeavAHakln4iDnXTAPceGFnjUfb4n3eU4YGMI9aUoZCLAjwA -yuqyzdzcpzBsPddJUvo5MzkfNh2LQVYNmkltIdLJxcW7k88nAwr5Df534AqMoa0vHS4+poVt0PXf -3OaW4tgHhFrHthrj587Jo3XDEffbWAO248O3Hhw+xGD3hgn8Wf5LKQVLAoSKdPD3MYR68B7oq7YJ -HfoYRuwk/7kna+ys2HeO7DkuiiP6fccO7QH8w07cY0yAANqFGpqdQbOZail9a153UNQB+kBf76u3 -YO2tV3sn41PUTqLHAXQoa5ttd/+8cxo2ekpWb06/P/twfvbm4uTzD44LiK7cx08Hh+L0xy+C8kPQ -gLFPFGNqRIWZSGBY3EInMc/hvxojP/O64iAx9Hp3fq5PalZY6oK5z2hzInjOaUwWGgfNOAptH+r8 -I8Qo1Rskp6aI0nWo5gj3SyuuZ1G5zo+mUqUpOqu13nrpWjFTU0bn2hFIHzR2ScEgOMUMXlEWe2V2 -hSWfAOo6qx6ktI22iSEpBQU76QLO+Zc5XfECpdQZnjSdtaK/DF1cw6tIFWkCO7lXoZUl3Q3TYxrG -0Q/tATfj1acBne4wsm7Is96KBVqtVyHPTfcfNYz2Ww0YNgz2DuadSUoPoQxsTG4TITbik5xQ3sFX -u/R6DRQsGB70VbiIhukSmH0Mm2uxTGADATy5BOuL+wSA0FoJ/0DgyIkOyByzM8K3q/n+X0JNEL/1 -L7/0NK/KdP9vooBdkOBUorCHmG7jd7DxiWQkTj++H4WMHKXmir/UWB4ADgkFQB1pp/wlPkGfDJVM -Fzq/xNcH+EL7CfS61b2URam797vGIUrAEzUkr+GJMvQLMd3Lwh7jVEYt0Fj5YDHDCkI3DcF89sSn -pUxTne9+9u78FHxHLMZACeJzt1MYjuMleISuk++4wrEFCg/Y4XWJbFyiC0tJFvPIa9YbtEaRo95e -XoZdJwoMd3t1osBlnCgX7SFOm2GZcoIIWRnWwiwrs3arDVLYbUMUR5lhlphclJTA6vME8DI9jXlL -BHslLPUwEXg+RU6yymQspskM9CioXFCoYxASJC7WMxLn5RnHwPNSmTIoeFhsyuR6WeHpBnSOqAQD -m/948uX87AOVJRy+bLzuHuYc005gzEkkx5giiNEO+OKm/SFXTSZ9PKtfIQzUPvCn/YqzU455gE4/ -Dizin/YrrkM7dnaCPANQUHXRFg/cADjd+uSmkQXG1e6D8eOmADaY+WAoFollLzrRw51flxNty5Yp -obiPefmIA5xFYVPSdGc3Ja390XNcFHjONR/2N4K3fbJlPlPoetN5sy35zf10pBBLYgGjbmt/DJMd -1mmqp+Mw2zZuoW2ttrG/ZE6s1Gk3y1CUgYhDt/PIZbJ+JaybMwd6adQdYOI7ja6RxF5VPvglG2gP -w8PEEruzTzEdqYyFjABGMqSu/anBh0KLAAqEsn+HjuSOR08PvTk61uD+OWrdBbbxB1CEOheXajzy -EjgRvvzGjiO/IrRQjx6J0PFUMpnlNk8MP+slepUv/Dn2ygAFMVHsyji7lkOGNTYwn/nE3hKCJW3r -kfoyueozLOIMnNO7LRzelYv+gxODWosROu1u5KatjnzyYIPeUpCdBPPBl/EadH9RV0NeyS3n0L21 -dNuh3g8Rsw+hqT59H4YYjvkt3LI+DeBeamhY6OH9tuUUltfGOLLWPraqmkL7QnuwsxK2ZpWiYxmn -ONH4otYLaAzucWPyB/apThSyv3vqxJyYkAXKg7sgvbkNdINWOGHA5UpcOZpQOnxTTaPfzeWtTMFo -gJEdYrXDr7baYRTZcEpvHthXY3exudj040ZvGsyOTDkGIkCFGL2Bnl0INTjgCv+idyJxdkPO8du/ -no3F2w8/wb9v5EewoFjzOBZ/g9HF27yEbSUX7dJtCljAUfF+Ma8VFkYSNDqh4Isn0Fu78MiLpyG6 -ssQvKbEKUmAybbni204ARZ4gFbI37oGpl4DfpqCr5YQaB7FvLQb6JdJge40L1oUc6JbRslqlaCac -4EiziJeD87O3px8+nUbVHTK2+Tlwgid+HhZORx8Nl3gMNhb2yazGJ1eOv/yDTIsed1nvNU29DO41 -RQjbkcLuL/kmjdjuKeISAwai2MzzWYQtgdO5RK9ag/88craV99p3z7girOFIH541Tjw+BmqIX9r6 -ZwANqY+eE/UkhOIp1orx42jQb4HHgiLa8OfpzXruBsR10Q9NsI1pM+uh392qwCXTWcOznER4Hdtl -MHWgaRKr1XTm1gd+zIS+CAWUGx1vyEVcp5WQGWylaG9PN1KAgndL+lhCmFXYilGdG0Vn0nW8UU7u -UazEAEcdUFE9nsNQoBC23j/GN2wGsNZQ1FwCDdAJUdo25U5XVc+WLMG8EyLq9eQbrJPspZvGoynM -g/LGeNb4rzBP9BYZo2tZ6fnzg+Ho8kWT4EDB6JlX0DsrwNi5bLIHGrN4+vTpQPzH/U4PoxKleX4D -3hjA7nVWzun1FoOtJ2dXq+vQmzcR8ONsKS/hwRUFze3zOqOI5I6utCDS/jUwQlyb0DKjad8yxxyr -K/l8mVvwOZU2GD9nCV13hBElicpW3xqF0SYjTcSSoBjCWM2SJOToBKzHJq+xFg+ji5pf5B1wfIJg -xvgWD8Z4h71Ex5LyZi33WHSOxYAADyiljEejYmaqRgM8JxcbjebkLEuqpozkuXtmqq8AqOwtRpqv -RLxGyTDzaBHDKev0WLVxrPOdLOptVPLZpRtnbM2SX9+HO7A2SFq+WBhM4aFZpFkuy5kxp7hiySyp -HDCmHcLhznR5E1mfKOhBaQDqnazC3Eq0ffsHuy4uph/p+HjfjKSzhip7IRbHhOKslVcYRc34FH2y -hLR8a76MYJQPFM3WnoA3lviDjqViDYF3b4dbzlhn+j4OTttoLukAOHQHlFWQlh09HeFcPGbhM9Nu -uUUDP7QzJ9xuk7Kq43Sir32YoJ82sefpGk9bBrezwNN6K+Db5+D47uuMfXAcTHIN0hMzbk1FxrFY -6MhE5FaW+UVYRY5e3iH7SuBTIGXmE1MPbWJHl5ZdbaGpTtV0VDyCemaKl7Y45KZqplNw4mI+pvQm -U+6wxXn2M0fp6grxWgxfjsVha+czKzZ4kxMg+2Qe+q4YdYOpOMEAM8f2vRji9bEYvhiLP+6AHm0Z -4OjQHaG9j21B2Ark5dWjyZgmUyJb2JfCfn9fncMImp5xHF21yd8l03dEpX9vUYkrBHWi8ot2onJr -7K371s7HRzJcgeJYJHK+/0QhCTXSjW7ezuCEHxbQ79kcLV073lTUUOHcFDYj60YPOhrRuM12EFOU -rtUX1++irmHDae8cMGkyrVRFe8scpjFq9FpEBQCTvqM0/IZ3u8B7TQrXP9t6xKqLACzYngiCrvTk -A7OmYSOo9zqCj9IA9zCKCPEwtVEUrmQ9QkRCugeHmOhZ6xDb4fjfnXm4xGDbUWgHy2+/2YWnK5i9 -RR09C7q70sITWVte0Sy3+fQH5jxG6ev6VQLjQGlEB5xVc1UluZlHmL3Md9DkNot5hZdB0sk0msRU -um4Tb6X51i/0Yyh2QMlksBbgSdULPEi+pbstTxQlveEVNd8cvhibymAGpCfwMnr5TF8BSd3M5Qe+ -jz3Wezd4qfsdRv/mAEsqv7d91dnN0LSOW3dB+YOFFD0bRRNLh8Yw3V8H0qxZLPDOxIaY7FvbC0De -g7czBT/HXH6ag8MGG9KoD11XYzTSu021bRHg+03GNsl5UNdGkSLSu4Rtm/LcpTgfLQq6V78FwRAC -cv4y5jfoCtbFkQ2xGZuCJ59DN5sTP9VNb90Z2xM0ttVNuGv63H/X3HWLwM7cJDN05u7Xl7o00H23 -W9E+GnB4QxPiQSUSjcbvNyauHRjrHJr+CL3+IPndTjjTLWblPjAmYwfj/cSeGntj9lfxzP2OCWH7 -fCGzW07c62y0pt2xGW2Of4inwMkv+NzeMEAZTXPNgbxfohv2JpwjO5HX12oS4+2OE9pkUz5XZ/dk -tm3v6XI+GauN2W3hpUUAwnCTzrx1k+uBMUBX8i3TnA7l3E4jaGhKGnaykFUyZ5Ogt3YALuKIKfU3 -gXhOIx6kEgPdqi6LEnbDA30XMefp9KU2N0BNAG8VqxuDuukx1lfTkmKl5DBTgsxx2laSDxCBjXjH -NEwm9h3wyvPmmoVkbJlBZvVKlnHVXDHkZwQksOlqRqCic1xcJzzXSGWLS1zEEssbDlIYILPfn8HG -0ttU77hXYWS13cPZiXrokO9jrmxwjJHh4uTOXi/oXms1p6utXe/QNmu4zl6pBMtg7sojHaljZfxW -39/Fd8xyJB/9S4d/QN7dyks/C92qM/ZuLRrOM1chdC9swhsDyDj33cPY4YDujYutDbAd39cXllE6 -HuaWxpaK2ifvVTjNaKMmgoQJo/dEkPyigEdGkDz4D4wg6VszwdBofLQe6C0TuCfUxOrBvYKyYQTo -MwEi4QF26wJDYyqHbtJ9kavkbmAvlGZd6VTyGfOAHNm9m4xA8FWTys1Q9q6C2xVB8qWLHn9//vHN -yTnRYnJx8vY/T76npCw8LmnZqgeH2LJ8n6m976V/u+E2nUjTN3iDbc8NsVzDpCF03ndyEHog9Ner -9S1oW5G5r7d16NT9dDsB4run3YK6TWX3Qu74ZbrGxE2faeVpB/opJ9WaX05mgnlkTupYHJqTOPO+ -OTzRMtqJLW9bOCe9tatOtL+qbwHdEvce2SRrWgE8M0H+skcmpmLGBubZQWn/bz4oMxyrDc0NOiCF -M+nc5EiXODKoyv//iZSg7GLc27GjOLZ3c1M7Ph5S9tJ5PPudycgQxCv3G3Tn5wr7XKZbqBAErPD0 -PYWMiNF/+kDVph88UeJynwqL91HZXNlfuGbauf1rgkkGlb3vS3GCEh+zQuNFnbqJA7ZPpwM5fXQa -lS+cShbQfAdA50Y8FbA3+kusEKcbEcLGUbtkmBxLdNSX9TnIo910sDe0ei72t5WdumWXQrzY3nDe -quzUPQ65h7qnh6pNcZ9jgTFLc1s9qXhNkPk4U9AFX57zgWfoetsPX28vXxzZwwXkd3ztKBLKJhs4 -hv3Sycbceamk052YpRxTuh7u1ZyQsG5x5UBln2Db3qZTkrJl/2PyHBjSwHvfHzIzPbyr9wdtTC3r -HcGUxPCJGtG0nCIejbt9MupOt1FbXSBckPQAIB0VCLAQTEc3OgmiG87yHj7Xu8FpTdfxuidMoSMV -lCzmcwT3ML5fg1+7OxUSP6g7o2j6c4M2B+olB+Fm34FbjbxQyHaT0J56wwdbXACuye7v/+IB/btp -jLb74S6/2rZ62VsHyL4sZr5iZlCLROZxBEYG9OaQtDWWSxhBx2toGjq6DNXMDfkCHT/KpsXLtmmD -Qc7sRHsA1igE/wfVIOdx -""") - -##file activate.sh -ACTIVATE_SH = convert(""" -eJytVVFvokAQfudXTLEPtTlLeo9tvMSmJpq02hSvl7u2wRUG2QR2DSxSe7n/frOACEVNLlceRHa+ -nfl25pvZDswCnoDPQ4QoTRQsENIEPci4CsBMZBq7CAsuLOYqvmYKTTj3YxnBgiXBudGBjUzBZUJI -BXEqgCvweIyuCjeG4eF2F5x14bcB9KQiQQWrjSddI1/oQIx6SYYeoFjzWIoIhYI1izlbhJjkKO7D -M/QEmKfO9O7WeRo/zr4P7pyHwWxkwitcgwpQ5Ej96OX+PmiFwLeVjFUOrNYKaq1Nud3nR2n8nI2m -k9H0friPTGVsUdptaxGrTEfpNVFEskxpXtUkkCkl1UNF9cgLBkx48J4EXyALuBtAwNYIjF5kcmUU -abMKmMq1ULoiRbgsDEkTSsKSGFCJ6Z8vY/2xYiSacmtyAfCDdCNTVZoVF8vSTQOoEwSnOrngBkws -MYGMBMg8/bMBLSYKS7pYEXP0PqT+ZmBT0Xuy+Pplj5yn4aM9nk72JD8/Wi+Gr98sD9eWSMOwkapD -BbUv91XSvmyVkICt2tmXR4tWmrcUCsjWOpw87YidEC8i0gdTSOFhouJUNxR+4NYBG0MftoCTD9F7 -2rTtxG3oPwY1b2HncYwhrlmj6Wq924xtGDWqfdNxap+OYxplEurnMVo9RWks+rH8qKEtx7kZT5zJ -4H7oOFclrN6uFe+d+nW2aIUsSgs/42EIPuOhXq+jEo3S6tX6w2ilNkDnIpHCWdEQhFgwj9pkk7FN -l/y5eQvRSIQ5+TrL05lewxWpt/Lbhes5cJF3mLET1MGhcKCF+40tNWnUulxrpojwDo2sObdje3Bz -N3QeHqf3D7OjEXMVV8LN3ZlvuzoWHqiUcNKHtwNd0IbvPGKYYM31nPKCgkUILw3KL+Y8l7aO1ArS -Ad37nIU0fCj5NE5gQCuC5sOSu+UdI2NeXg/lFkQIlFpdWVaWZRfvqGiirC9o6liJ9FXGYrSY9mI1 -D/Ncozgn13vJvsznr7DnkJWXsyMH7e42ljdJ+aqNDF1bFnKWFLdj31xtaJYK6EXFgqmV/ymD/ROG -+n8O9H8f5vsGOWXsL1+1k3g= -""") - -##file activate.fish -ACTIVATE_FISH = convert(""" -eJydVW2P2jgQ/s6vmAZQoVpA9/WkqqJaTou0u6x2uZVOVWWZZEKsS+yc7UDpr+84bziQbauLxEvs -eXnsZ56ZIWwTYSAWKUJWGAs7hMJgBEdhEwiMKnSIsBNywUMrDtziPBYmCeBDrFUG7v8HmCTW5n8u -Fu7NJJim81Bl08EQTqqAkEupLOhCgrAQCY2hTU+DQVxIiqgkRNiEBphFEKy+kd1BaFvwFOUBuIxA -oy20BKtAKp3xFMo0QNtCK5mhtMEA6BmSpUELKo38TThwLfguRVNaiRgs0llnEoIR29zfstf18/bv -5T17Wm7vAiiN3ONCzfbfwC3DtWXXDqHfAGX0q6z/bO82j3ebh1VwnbrduwTQbvwcRtesAfMGor/W -L3fs6Xnz8LRlm9fV8/P61sM0LDNwCZjl9gSpCokJRzpryGQ5t8kNGFUt51QjOZGu0Mj35FlYlXEr -yC09EVOp4lEXfF84Lz1qbhBsgl59vDedXI3rTV03xipduSgt9kLytI3XmBp3aV6MPoMQGNUU62T6 -uQdeefTy1Hfj10zVHg2pq8fXDoHBiOv94csfXwN49xECqWREy7pwukKfvxdMY2j23vXDPuuxxeE+ -JOdCOhxCE3N44B1ZeSLuZh8Mmkr2wEPAmPfKWHA2uxIRjEopdbQYjDz3BWOf14/scfmwoki1eQvX -ExBdF60Mqh+Y/QcX4uiH4Amwzx79KOVFtbL63sXJbtcvy8/3q5rupmO5CnE91wBviQAhjUUegYpL -vVEbpLt2/W+PklRgq5Ku6mp+rpMhhCo/lXthQTxJ2ysO4Ka0ad97S7VT/n6YXus6fzk3fLnBZW5C -KDC6gSO62QDqgFqLCCtPmjegjnLeAdArtSE8VYGbAJ/aLb+vnQutFhk768E9uRbSxhCMzdgEveYw -IZ5ZqFKl6+kz7UR4U+buqQZXu9SIujrAfD7f0FXpozB4Q0gwp31H9mVTZGGC4b871/wm7lvyDLu1 -FUyvTj/yvD66k3UPTs08x1AQQaGziOl0S1qRkPG9COtBTSTWM9NzQ4R64B+Px/l3tDzCgxv5C6Ni -e+QaF9xFWrxx0V/G5uvYQOdiZzvYpQUVQSIsTr1TTghI33GnPbTA7/GCqcE3oE3GZurq4HeQXQD6 -32XS1ITj/qLjN72ob0hc5C9bzw8MhfmL -""") - -##file activate.csh -ACTIVATE_CSH = convert(""" -eJx9VG1P2zAQ/u5fcYQKNgTNPtN1WxlIQ4KCUEGaxuQ6yYVYSuzKdhqVX7+zk3bpy5YPUXL3PPfc -ne98DLNCWshliVDV1kGCUFvMoJGugMjq2qQIiVSxSJ1cCofD1BYRnOVGV0CfZ0N2DD91DalQSjsw -tQLpIJMGU1euvPe7QeJlkKzgWixlhnAt4aoUVsLnLBiy5NtbJWQ5THX1ZciYKKWwkOFaE04dUm6D -r/zh7pq/3D7Nnid3/HEy+wFHY/gEJydg0aFaQrBFgz1c5DG1IhTs+UZgsBC2GMFBlaeH+8dZXwcW -VPvCjXdlAvCfQsE7al0+07XjZvrSCUevR5dnkVeKlFYZmUztG4BdzL2u9KyLVabTU0bdfg7a0hgs -cSmUg6UwUiQl2iHrcbcVGNvPCiLOe7+cRwG13z9qRGgx2z6DHjfm/Op2yqeT+xvOLzs0PTKHDz2V -tkckFHoQfQRXoGJAj9el0FyJCmEMhzgMS4sB7KPOE2ExoLcSieYwDvR+cP8cg11gKkVJc2wRcm1g -QhYFlXiTaTfO2ki0fQoiFM4tLuO4aZrhOzqR4dIPcWx17hphMBY+Srwh7RTyN83XOWkcSPh1Pg/k -TXX/jbJTbMtUmcxZ+/bbqOsy82suFQg/BhdSOTRhMNBHlUarCpU7JzBhmkKmRejKOQzayQe6MWoa -n1wqWmuh6LZAaHxcdeqIlVLhIBJdO9/kbl0It2oEXQj+eGjJOuvOIR/YGRqvFhttUB2XTvLXYN2H -37CBdbW2W7j2r2+VsCn0doVWcFG1/4y1VwBjfwAyoZhD -""") - -##file activate.bat -ACTIVATE_BAT = convert(""" -eJx9UdEKgjAUfW6wfxjiIH+hEDKUFHSKLCMI7kNOEkIf9P9pTJ3OLJ/03HPPPed4Es9XS9qqwqgT -PbGKKOdXL4aAFS7A4gvAwgijuiKlqOpGlATS2NeMLE+TjJM9RkQ+SmqAXLrBo1LLIeLdiWlD6jZt -r7VNubWkndkXaxg5GO3UaOOKS6drO3luDDiO5my3iA0YAKGzPRV1ack8cOdhysI0CYzIPzjSiH5X -0QcvC8Lfaj0emsVKYF2rhL5L3fCkVjV76kShi59NHwDniAHzkgDgqBcwOgTMx+gDQQqXCw== -""") - -##file deactivate.bat -DEACTIVATE_BAT = convert(""" -eJxzSE3OyFfIT0vj4ipOLVEI8wwKCXX0iXf1C7Pl4spMU0hJTcvMS01RiPf3cYmHyQYE+fsGhCho -cCkAAUibEkTEVhWLMlUlLk6QGixStlyaeCyJDPHw9/Pw93VFsQguim4ZXAJoIUw5DhX47XUM8UCx -EchHtwsohN1bILUgw61c/Vy4AJYPYm4= -""") - -##file activate.ps1 -ACTIVATE_PS = convert(""" -eJylWdmS40Z2fVeE/oHT6rCloNUEAXDThB6wAyQAEjsB29GBjdgXYiWgmC/zgz/Jv+AEWNVd3S2N -xuOKYEUxM+/Jmzfvcm7W//zXf/+wUMOoXtyi1F9kbd0sHH/hFc2iLtrK9b3FrSqyxaVQwr8uhqJd -uHaeg9mqzRdR8/13Pyy8qPLdJh0+LMhi0QCoXxYfFh9WtttEnd34H8p6/f1300KauwrULws39e18 -0ZaLNm9rgN/ZVf3h++/e124Vlc0vKsspHy+Yyi5+XbzPhijvCtduoiL/kA1ukWV27n0o7Sb8LIFj -CvWR5GQgUJdp1Pw8TS9+rPy6SDv/+e3d+0+4qw8f3v20+PliV37efEYBAB9FTKC+RHn/Cfxn3rdv -00Fube5O+iyCtHDs9BfPfz3q4sfFv9d91Ljhfy7ei0VO+nVTtdOkv/jpt0l2AX6iG1jXgKnnDuD4 -ke2k/i8fzzz5UedkVcP4pwF+Wvz2FJl+3vt598urXf5Y6LNA5WcFOP7r0sW7b9a+W/xcu0Xpv5zk -Kfq3P9Dz9di/fCxS72MXVU1rpx9L4Bxl85Wmn5a+zP76Zuh3pL9ROWr87PN+//GHIl+oOtvn9XSU -qH+p0gQBFnx1uV+JLH5O5zv+PXW+WepXVVHZT0+oQezkIATcIm+ivPV/z5J/+cYj3ir4w0Lx09vC -e5n/y5/Y5LPPfdrqb88ga/PabxZRVfmp39l588m/6u+/e+OpP+dF7n1WZpJ9//Z4v372fDDz9eHB -7Juvs/BLMHzrxL9+9twXpJfhd1/DrpQ5Euu/vlss3wp9HXC/54C/Ld69m6zwdx3tC0d8daSv0V8B -n4b9YYF53sJelJV/ix6LZspw/sJtqyl5LJ5r/23htA1Imfm/gt9R7dqVB1LjhydAX4Gb+zksQF59 -9+P7H//U+376afFuvh2/T6P85Xr/5c8C6OXyFY4BGuN+EE0+GeR201b+wkkLN5mmBY5TfMw8ngqL -CztXxCSXKMCYrRIElWkEJlEPYsSOeKBVZCAQTKBhApMwRFQzmCThE0YQu2CdEhgjbgmk9GluHpfR -/hhwJCZhGI5jt5FsAkOrObVyE6g2y1snyhMGFlDY1x+BoHpCMulTj5JYWNAYJmnKpvLxXgmQ8az1 -4fUGxxcitMbbhDFcsiAItg04E+OSBIHTUYD1HI4FHH4kMREPknuYRMyhh3AARWMkfhCketqD1CWJ -mTCo/nhUScoQcInB1hpFhIKoIXLo5jLpwFCgsnLCx1QlEMlz/iFEGqzH3vWYcpRcThgWnEKm0QcS -rA8ek2a2IYYeowUanOZOlrbWSJUC4c7y2EMI3uJPMnMF/SSXdk6E495VLhzkWHps0rOhKwqk+xBI -DhJirhdUCTamMfXz2Hy303hM4DFJ8QL21BcPBULR+gcdYxoeiDqOFSqpi5B5PUISfGg46gFZBPo4 -jdh8lueaWuVSMTURfbAUnLINr/QYuuYoMQV6l1aWxuZVTjlaLC14UzqZ+ziTGDzJzhiYoPLrt3uI -tXkVR47kAo09lo5BD76CH51cTt1snVpMOttLhY93yxChCQPI4OBecS7++h4p4Bdn4H97bJongtPk -s9gQnXku1vzsjjmX4/o4YUDkXkjHwDg5FXozU0fW4y5kyeYW0uJWlh536BKr0kMGjtzTkng6Ep62 -uTWnQtiIqKnEsx7e1hLtzlXs7Upw9TwEnp0t9yzCGgUJIZConx9OHJArLkRYW0dW42G9OeR5Nzwk -yk1mX7du5RGHT7dka7N3AznmSif7y6tuKe2N1Al/1TUPRqH6E2GLVc27h9IptMLkCKQYRqPQJgzV -2m6WLsSipS3v3b1/WmXEYY1meLEVIU/arOGVkyie7ZsH05ZKpjFW4cpY0YkjySpSExNG2TS8nnJx -nrQmWh2WY3cP1eISP9wbaVK35ZXc60yC3VN/j9n7UFoK6zvjSTE2+Pvz6Mx322rnftfP8Y0XKIdv -Qd7AfK0nexBTMqRiErvCMa3Hegpfjdh58glW2oNMsKeAX8x6YJLZs9K8/ozjJkWL+JmECMvhQ54x -9rsTHwcoGrDi6Y4I+H7yY4/rJVPAbYymUH7C2D3uiUS3KQ1nrCAUkE1dJMneDQIJMQQx5SONxoEO -OEn1/Ig1eBBUeEDRuOT2WGGGE4bNypBLFh2PeIg3bEbg44PHiqNDbGIQm50LW6MJU62JHCGBrmc9 -2F7WBJrrj1ssnTAK4sxwRgh5LLblhwNAclv3Gd+jC/etCfyfR8TMhcWQz8TBIbG8IIyAQ81w2n/C -mHWAwRzxd3WoBY7BZnsqGOWrOCKwGkMMNfO0Kci/joZgEocLjNnzgcmdehPHJY0FudXgsr+v44TB -I3jnMGnsK5veAhgi9iXGifkHMOC09Rh9cAw9sQ0asl6wKMk8mpzFYaaDSgG4F0wisQDDBRpjCINg -FIxhlhQ31xdSkkk6odXZFpTYOQpOOgw9ugM2cDQ+2MYa7JsEirGBrOuxsQy5nPMRdYjsTJ/j1iNw -FeSt1jY2+dd5yx1/pzZMOQXUIDcXeAzR7QlDRM8AMkUldXOmGmvYXPABjxqkYKO7VAY6JRU7kpXr -+Epu2BU3qFFXClFi27784LrDZsJwbNlDw0JzhZ6M0SMXE4iBHehCpHVkrQhpTFn2dsvsZYkiPEEB -GSEAwdiur9LS1U6P2U9JhGp4hnFpJo4FfkdJHcwV6Q5dV1Q9uNeeu7rV8PAjwdFg9RLtroifOr0k -uOiRTo/obNPhQIf42Fr4mtThWoSjitEdAmFW66UCe8WFjPk1YVNpL9srFbond7jrLg8tqAasIMpy -zkH0SY/6zVAwJrEc14zt14YRXdY+fcJ4qOd2XKB0/Kghw1ovd11t2o+zjt+txndo1ZDZ2T+uMVHT -VSXhedBAHoJIID9xm6wPQI3cXY+HR7vxtrJuCKh6kbXaW5KkVeJsdsjqsYsOwYSh0w5sMbu7LF8J -5T7U6LJdiTx+ca7RKlulGgS5Z1JSU2Llt32cHFipkaurtBrvNX5UtvNZjkufZ/r1/XyLl6yOpytL -Km8Fn+y4wkhlqZP5db0rooqy7xdL4wxzFVTX+6HaxuQJK5E5B1neSSovZ9ALB8091dDbbjVxhWNY -Ve5hn1VnI9OF0wpvaRm7SZuC1IRczwC7GnkhPt3muHV1YxUJfo+uh1sYnJy+vI0ZwuPV2uqWJYUH -bmBsi1zmFSxHrqwA+WIzLrHkwW4r+bad7xbOzJCnKIa3S3YvrzEBK1Dc0emzJW+SqysQfdEDorQG -9ZJlbQzEHQV8naPaF440YXzJk/7vHGK2xwuP+Gc5xITxyiP+WQ4x18oXHjFzCBy9kir1EFTAm0Zq -LYwS8MpiGhtfxiBRDXpxDWxk9g9Q2fzPPAhS6VFDAc/aiNGatUkPtZIStZFQ1qD0IlJa/5ZPAi5J -ySp1ETDomZMnvgiysZSBfMikrSDte/K5lqV6iwC5q7YN9I1dBZXUytDJNqU74MJsUyNNLAPopWK3 -tzmLkCiDyl7WQnj9sm7Kd5kzgpoccdNeMw/6zPVB3pUwMgi4C7hj4AMFAf4G27oXH8NNT9zll/sK -S6wVlQwazjxWKWy20ZzXb9ne8ngGalPBWSUSj9xkc1drsXkZ8oOyvYT3e0rnYsGwx85xZB9wKeKg -cJKZnamYwiaMymZvzk6wtDUkxmdUg0mPad0YHtvzpjEfp2iMxvORhnx0kCVLf5Qa43WJsVoyfEyI -pzmf8ruM6xBr7dnBgzyxpqXuUPYaKahOaz1LrxNkS/Q3Ae5AC+xl6NbxAqXXlzghZBZHmOrM6Y6Y -ctAkltwlF7SKEsShjVh7QHuxMU0a08/eiu3x3M+07OijMcKFFltByXrpk8w+JNnZpnp3CfgjV1Ax -gUYCnWwYow42I5wHCcTzLXK0hMZN2DrPM/zCSqe9jRSlJnr70BPE4+zrwbk/xVIDHy2FAQyHoomT -Tt5jiM68nBQut35Y0qLclLiQrutxt/c0OlSqXAC8VrxW97lGoRWzhOnifE2zbF05W4xuyhg7JTUL -aqJ7SWDywhjlal0b+NLTpERBgnPW0+Nw99X2Ws72gOL27iER9jgzj7Uu09JaZ3n+hmCjjvZpjNst -vOWWTbuLrg+/1ltX8WpPauEDEvcunIgTxuMEHweWKCx2KQ9DU/UKdO/3za4Szm2iHYL+ss9AAttm -gZHq2pkUXFbV+FiJCKrpBms18zH75vax5jSo7FNunrVWY3Chvd8KKnHdaTt/6ealwaA1x17yTlft -8VBle3nAE+7R0MScC3MJofNCCkA9PGKBgGMYEwfB2QO5j8zUqa8F/EkWKCzGQJ5EZ05HTly1B01E -z813G5BY++RZ2sxbQS8ZveGPJNabp5kXAeoign6Tlt5+L8i5ZquY9+S+KEUHkmYMRFBxRrHnbl2X -rVemKnG+oB1yd9+zT+4c43jQ0wWmQRR6mTCkY1q3VG05Y120ZzKOMBe6Vy7I5Vz4ygPB3yY4G0FP -8RxiMx985YJPXsgRU58EuHj75gygTzejP+W/zKGe78UQN3yOJ1aMQV9hFH+GAfLRsza84WlPLAI/ -9G/5JdcHftEfH+Y3/fHUG7/o8bv98dzzy3e8S+XCvgqB+VUf7sH0yDHpONdbRE8tAg9NWOzcTJ7q -TuAxe/AJ07c1Rs9okJvl1/0G60qvbdDzz5zO0FuPFQIHNp9y9Bd1CufYVx7dB26mAxwa8GMNrN/U -oGbNZ3EQ7inLzHy5tRg9AXJrN8cB59cCUBeCiVO7zKM0jU0MamhnRThkg/NMmBOGb6StNeD9tDfA -7czsAWopDdnGoXUHtA+s/k0vNPkBcxEI13jVd/axp85va3LpwGggXXWw12Gwr/JGAH0b8CPboiZd -QO1l0mk/UHukud4C+w5uRoNzpCmoW6GbgbMyaQNkga2pQINB18lOXOCJzSWPFOhZcwzdgrsQnne7 -nvjBi+7cP2BbtBeDOW5uOLGf3z94FasKIguOqJl+8ss/6Kumns4cuWbqq5592TN/RNIbn5Qo6qbi -O4F0P9txxPAwagqPlftztO8cWBzdN/jz3b7GD6JHYP/Zp4ToAMaA74M+EGSft3hEGMuf8EwjnTk/ -nz/P7SLipB/ogQ6xNX0fDqNncMCfHqGLCMM0ZzFa+6lPJYQ5p81vW4HkCvidYf6kb+P/oB965g8K -C6uR0rdjX1DNKc5pOSTquI8uQ6KXxYaKBn+30/09tK4kMpJPgUIQkbENEPbuezNPPje2Um83SgyX -GTCJb6MnGVIpgncdQg1qz2bvPfxYD9fewCXDomx9S+HQJuX6W3VAL+v5WZMudRQZk9ZdOk6GIUtC -PqEb/uwSIrtR7/edzqgEdtpEwq7p2J5OQV+RLrmtTvFwFpf03M/VrRyTZ73qVod7v7Jh2Dwe5J25 -JqFOU2qEu1sP+CRotklediycKfLjeIZzjJQsvKmiGSNQhxuJpKa+hoWUizaE1PuIRGzJqropwgVB -oo1hr870MZLgnXF5ZIpr6mF0L8aSy2gVnTAuoB4WEd4d5NPVC9TMotYXERKlTcwQ2KiB/C48AEfH -Qbyq4CN8xTFnTvf/ebOc3isnjD95s0QF0nx9s+y+zMmz782xL0SgEmRpA3x1w1Ff9/74xcxKEPdS -IEFTz6GgU0+BK/UZ5Gwbl4gZwycxEw+Kqa5QmMkh4OzgzEVPnDAiAOGBFaBW4wkDmj1G4RyElKgj -NlLCq8zsp085MNh/+R4t1Q8yxoSv8PUpTt7izZwf2BTHZZ3pIZpUIpuLkL1nNL6sYcHqcKm237wp -T2+RCjgXweXd2Zp7ZM8W6dG5bZsqo0nrJBTx8EC0+CQQdzEGnabTnkzofu1pYkWl4E7XSniECdxy -vLYavPMcL9LW5SToJFNnos+uqweOHriUZ1ntIYZUonc7ltEQ6oTRtwOHNwez2sVREskHN+bqG3ua -eaEbJ8XpyO8CeD9QJc8nbLP2C2R3A437ISUNyt5Yd0TbDNcl11/DSsOzdbi/VhCC0KE6v1vqVNkq -45ZnG6fiV2NwzInxCNth3BwL0+8814jE6+1W1EeWtpWbSZJOJNYXmWRXa7vLnAljE692eHjZ4y5u -y1u63De0IzKca7As48Z3XshVF+3XiLNz0JIMh/JOpbiNLlMi672uO0wYzOCZjRxcxj3D+gVenGIE -MvFUGGXuRps2RzMcgWIRolHXpGUP6sMsQt1hspUBnVKUn/WQj2u6j3SXd9Xz0QtEzoM7qTu5y7gR -q9gNNsrlEMLdikBt9bFvBnfbUIh6voTw7eDsyTmPKUvF0bHqWLbHe3VRHyRZnNeSGKsB73q66Vsk -taxWYmwz1tYVFG/vOQhlM0gUkyvIab3nv2caJ1udU1F3pDMty7stubTE4OJqm0i0ECfrJIkLtraC -HwRWKzlqpfhEIqYH09eT9WrOhQyt8YEoyBlnXtAT37WHIQ03TIuEHbnRxZDdLun0iok9PUC79prU -m5beZzfQUelEXnhzb/pIROKx3F7qCttYIFGh5dXNzFzID7u8vKykA8Uejf7XXz//S4nKvW//ofS/ -QastYw== -""") - -##file distutils-init.py -DISTUTILS_INIT = convert(""" -eJytV1uL4zYUfvevOE0ottuMW9q3gVDa3aUMXXbLMlDKMBiNrSTqOJKRlMxkf33PkXyRbGe7Dw2E -UXTu37lpxLFV2oIyifAncxmOL0xLIfcG+gv80x9VW6maw7o/CANSWWBwFtqeWMPlGY6qPjV8A0bB -C4eKSTgZ5LRgFeyErMEeOBhbN+Ipgeizhjtnhkn7DdyjuNLPoCS0l/ayQTG0djwZC08cLXozeMss -aG5EzQ0IScpnWtHSTXuxByV/QCmxE7y+eS0uxWeoheaVVfqSJHiU7Mhhi6gULbOHorshkrEnKxpT -0n3A8Y8SMpuwZx6aoix3ouFlmW8gHRSkeSJ2g7hU+kiHLDaQw3bmRDaTGfTnty7gPm0FHbIBg9U9 -oh1kZzAFLaue2R6htPCtAda2nGlDSUJ4PZBgCJBGVcwKTAMz/vJiLD+Oin5Z5QlvDPdulC6EsiyE -NFzb7McNTKJzbJqzphx92VKRFY1idenzmq3K0emRcbWBD0ryqc4NZGmKOOOX9Pz5x+/l27tP797c -f/z0d+4NruGNai8uAM0bfsYaw8itFk8ny41jsfpyO+BWlpqfhcG4yxLdi/0tQqoT4a8Vby382mt8 -p7XSo7aWGdPBc+b6utaBmCQ7rQKQoWtAuthQCiold2KfJIPTT8xwg9blPumc+YDZC/wYGdAyHpJk -vUbHbHWAp5No6pK/WhhLEWrFjUwtPEv1Agf8YmnsuXUQYkeZoHm8ogP16gt2uHoxcEMdf2C6pmbw -hUMsWGhanboh4IzzmsIpWs134jVPqD/c74bZHdY69UKKSn/+KfVhxLgUlToemayLMYQOqfEC61bh -cbhwaqoGUzIyZRFHPmau5juaWqwRn3mpWmoEA5nhzS5gog/5jbcFQqOZvmBasZtwYlG93k5GEiyw -buHhMWLjDarEGpMGB2LFs5nIJkhp/nUmZneFaRth++lieJtHepIvKgx6PJqIlD9X2j6pG1i9x3pZ -5bHuCPFiirGHeO7McvoXkz786GaKVzC9DSpnOxJdc4xm6NSVq7lNEnKdVlnpu9BNYoKX2Iq3wvgh -gGEUM66kK6j4NiyoneuPLSwaCWDxczgaolEWpiMyDVDb7dNuLAbriL8ig8mmeju31oNvQdpnvEPC -1vAXbWacGRVrGt/uXN/gU0CDDwgooKRrHfTBb1/s9lYZ8ZqOBU0yLvpuP6+K9hLFsvIjeNhBi0KL -MlOuWRn3FRwx5oHXjl0YImUx0+gLzjGchrgzca026ETmYJzPD+IpuKzNi8AFn048Thd63OdD86M6 -84zE8yQm0VqXdbbgvub2pKVnS76icBGdeTHHXTKspUmr4NYo/furFLKiMdQzFjHJNcdAnMhltBJK -0/IKX3DVFqvPJ2dLE7bDBkH0l/PJ29074+F0CsGYOxsb7U3myTUncYfXqnLLfa6sJybX4g+hmcjO -kMRBfA1JellfRRKJcyRpxdS4rIl6FdmQCWjo/o9Qz7yKffoP4JHjOvABcRn4CZIT2RH4jnxmfpVG -qgLaAvQBNfuO6X0/Ux02nb4FKx3vgP+XnkX0QW9pLy/NsXgdN24dD3LxO2Nwil7Zlc1dqtP3d7/h -kzp1/+7hGBuY4pk0XD/0Ao/oTe/XGrfyM773aB7iUhgkpy+dwAMalxMP0DrBcsVw/6p25+/hobP9 -GBknrWExDhLJ1bwt1NcCNblaFbMKCyvmX0PeRaQ= -""") - -##file distutils.cfg -DISTUTILS_CFG = convert(""" -eJxNj00KwkAMhfc9xYNuxe4Ft57AjYiUtDO1wXSmNJnK3N5pdSEEAu8nH6lxHVlRhtDHMPATA4uH -xJ4EFmGbvfJiicSHFRzUSISMY6hq3GLCRLnIvSTnEefN0FIjw5tF0Hkk9Q5dRunBsVoyFi24aaLg -9FDOlL0FPGluf4QjcInLlxd6f6rqkgPu/5nHLg0cXCscXoozRrP51DRT3j9QNl99AP53T2Q= -""") - -##file activate_this.py -ACTIVATE_THIS = convert(""" -eJyNU01v2zAMvetXEB4K21jmDOstQA4dMGCHbeihlyEIDMWmG62yJEiKE//7kXKdpN2KzYBt8euR -fKSyLPs8wiEo8wh4wqZTGou4V6Hm0wJa1cSiTkJdr8+GsoTRHuCotBayiWqQEYGtMCgfD1KjGYBe -5a3p0cRKiAe2NtLADikftnDco0ko/SFEVgEZ8aRC5GLux7i3BpSJ6J1H+i7A2CjiHq9z7JRZuuQq -siwTIvpxJYCeuWaBpwZdhB+yxy/eWz+ZvVSU8C4E9FFZkyxFsvCT/ZzL8gcz9aXVE14Yyp2M+2W0 -y7n5mp0qN+avKXvbsyyzUqjeWR8hjGE+2iCE1W1tQ82hsCZN9UzlJr+/e/iab8WfqsmPI6pWeUPd -FrMsd4H/55poeO9n54COhUs+sZNEzNtg/wanpjpuqHJaxs76HtZryI/K3H7KJ/KDIhqcbJ7kI4ar -XL+sMgXnX0D+Te2Iy5xdP8yueSlQB/x/ED2BTAtyE3K4SYUN6AMNfbO63f4lBW3bUJPbTL+mjSxS -PyRfJkZRgj+VbFv+EzHFi5pKwUEepa4JslMnwkowSRCXI+m5XvEOvtuBrxHdhLalG0JofYBok6qj -YdN2dEngUlbC4PG60M1WEN0piu7Nq7on0mgyyUw3iV1etLo6r/81biWdQ9MWHFaePWZYaq+nmp+t -s3az+sj7eA0jfgPfeoN1 -""") - -MH_MAGIC = 0xfeedface -MH_CIGAM = 0xcefaedfe -MH_MAGIC_64 = 0xfeedfacf -MH_CIGAM_64 = 0xcffaedfe -FAT_MAGIC = 0xcafebabe -BIG_ENDIAN = '>' -LITTLE_ENDIAN = '<' -LC_LOAD_DYLIB = 0xc -maxint = majver == 3 and getattr(sys, 'maxsize') or getattr(sys, 'maxint') - - -class fileview(object): - """ - A proxy for file-like objects that exposes a given view of a file. - Modified from macholib. - """ - - def __init__(self, fileobj, start=0, size=maxint): - if isinstance(fileobj, fileview): - self._fileobj = fileobj._fileobj - else: - self._fileobj = fileobj - self._start = start - self._end = start + size - self._pos = 0 - - def __repr__(self): - return '' % ( - self._start, self._end, self._fileobj) - - def tell(self): - return self._pos - - def _checkwindow(self, seekto, op): - if not (self._start <= seekto <= self._end): - raise IOError("%s to offset %d is outside window [%d, %d]" % ( - op, seekto, self._start, self._end)) - - def seek(self, offset, whence=0): - seekto = offset - if whence == os.SEEK_SET: - seekto += self._start - elif whence == os.SEEK_CUR: - seekto += self._start + self._pos - elif whence == os.SEEK_END: - seekto += self._end - else: - raise IOError("Invalid whence argument to seek: %r" % (whence,)) - self._checkwindow(seekto, 'seek') - self._fileobj.seek(seekto) - self._pos = seekto - self._start - - def write(self, bytes): - here = self._start + self._pos - self._checkwindow(here, 'write') - self._checkwindow(here + len(bytes), 'write') - self._fileobj.seek(here, os.SEEK_SET) - self._fileobj.write(bytes) - self._pos += len(bytes) - - def read(self, size=maxint): - assert size >= 0 - here = self._start + self._pos - self._checkwindow(here, 'read') - size = min(size, self._end - here) - self._fileobj.seek(here, os.SEEK_SET) - bytes = self._fileobj.read(size) - self._pos += len(bytes) - return bytes - - -def read_data(file, endian, num=1): - """ - Read a given number of 32-bits unsigned integers from the given file - with the given endianness. - """ - res = struct.unpack(endian + 'L' * num, file.read(num * 4)) - if len(res) == 1: - return res[0] - return res - - -def mach_o_change(path, what, value): - """ - Replace a given name (what) in any LC_LOAD_DYLIB command found in - the given binary with a new name (value), provided it's shorter. - """ - - def do_macho(file, bits, endian): - # Read Mach-O header (the magic number is assumed read by the caller) - cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags = read_data(file, endian, 6) - # 64-bits header has one more field. - if bits == 64: - read_data(file, endian) - # The header is followed by ncmds commands - for n in range(ncmds): - where = file.tell() - # Read command header - cmd, cmdsize = read_data(file, endian, 2) - if cmd == LC_LOAD_DYLIB: - # The first data field in LC_LOAD_DYLIB commands is the - # offset of the name, starting from the beginning of the - # command. - name_offset = read_data(file, endian) - file.seek(where + name_offset, os.SEEK_SET) - # Read the NUL terminated string - load = file.read(cmdsize - name_offset).decode() - load = load[:load.index('\0')] - # If the string is what is being replaced, overwrite it. - if load == what: - file.seek(where + name_offset, os.SEEK_SET) - file.write(value.encode() + '\0'.encode()) - # Seek to the next command - file.seek(where + cmdsize, os.SEEK_SET) - - def do_file(file, offset=0, size=maxint): - file = fileview(file, offset, size) - # Read magic number - magic = read_data(file, BIG_ENDIAN) - if magic == FAT_MAGIC: - # Fat binaries contain nfat_arch Mach-O binaries - nfat_arch = read_data(file, BIG_ENDIAN) - for n in range(nfat_arch): - # Read arch header - cputype, cpusubtype, offset, size, align = read_data(file, BIG_ENDIAN, 5) - do_file(file, offset, size) - elif magic == MH_MAGIC: - do_macho(file, 32, BIG_ENDIAN) - elif magic == MH_CIGAM: - do_macho(file, 32, LITTLE_ENDIAN) - elif magic == MH_MAGIC_64: - do_macho(file, 64, BIG_ENDIAN) - elif magic == MH_CIGAM_64: - do_macho(file, 64, LITTLE_ENDIAN) - - assert(len(what) >= len(value)) - do_file(open(path, 'r+b')) - - -if __name__ == '__main__': - main() - -## TODO: -## Copy python.exe.manifest -## Monkeypatch distutils.sysconfig diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index 699b42633..05323d752 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -97,6 +97,11 @@ option(SITK_PYTHON_USE_VIRTUALENV "Create a Python Virtual Environment for testi mark_as_advanced(SITK_PYTHON_USE_VIRTUALENV) if (SITK_PYTHON_USE_VIRTUALENV) + + # Executable to setup a new Python virtual environment + # todo use a find_program and get version + set( PYTHON_VIRTUALENV_EXECUTABLE "" CACHE FILEPATH "Python virtualenv executable") + sitk_enforce_forbid_downloads( SITK_PYTHON_USE_VIRTUALENV ) # # Setup Python Virtual Enviroment for testing and packaging diff --git a/Wrapping/Python/PythonVirtualEnvInstall.cmake.in b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in index 3a043f5fe..9d18444d2 100644 --- a/Wrapping/Python/PythonVirtualEnvInstall.cmake.in +++ b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in @@ -8,7 +8,7 @@ endif() # execute_process( COMMAND "@PYTHON_EXECUTABLE@" - "@SimpleITK_SOURCE_DIR@/Utilities/virtualenv/virtualenv.py" + "@PYTHON_VIRTUALENV_EXECUTABLE@" "--python=@PYTHON_EXECUTABLE@" --no-pip --no-setuptools From 9075d55755e945e7e2583cf5d34112590a9b46b2 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 3 Dec 2015 16:28:27 -0500 Subject: [PATCH 149/412] Prefer the use of distutils over setuptools Now setup.py does not try to use setuptools by default. It is only used when setuptools is already imported as what is done with the setupegg.py script. Change-Id: I7c02e7a42052e44241405c220f72b614769023dd --- Wrapping/Python/Packaging/setup.py.in | 11 +++++------ Wrapping/Python/Packaging/setupegg.py | 2 ++ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/Wrapping/Python/Packaging/setup.py.in b/Wrapping/Python/Packaging/setup.py.in index 42373fcad..2007345d2 100644 --- a/Wrapping/Python/Packaging/setup.py.in +++ b/Wrapping/Python/Packaging/setup.py.in @@ -1,12 +1,11 @@ +import sys -try: - from setuptools import setup -except ImportError: +if "setuptools" in sys.modules.keys(): + from setuptools import setup, Distribution +else: from distutils.core import setup + from distutils.dist import Distribution -from distutils.core import Extension -from distutils.util import get_platform -from distutils.dist import Distribution import re doc_files = @SimpleITK_DOC_FILES_AS_LIST@ diff --git a/Wrapping/Python/Packaging/setupegg.py b/Wrapping/Python/Packaging/setupegg.py index e91fe8ebd..443158185 100644 --- a/Wrapping/Python/Packaging/setupegg.py +++ b/Wrapping/Python/Packaging/setupegg.py @@ -5,5 +5,7 @@ use_setuptools() import os +from setuptools import setup + fn = os.path.dirname(os.path.realpath(__file__)) + '/setup.py' exec(open(fn).read()) From fc60ada14e7bbcb45e54c3363f47b0e1d7512931 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 23 Feb 2016 12:41:26 -0500 Subject: [PATCH 150/412] Use virtualenv's setuptools and wheel, remove ez_setup Let virtualenv get (the potentially latest version of) setuptools and wheel to be installed in the virtual environment. This removes the need for ez_setup to obtain setuptools, and to use setuptools to obtain wheels. Change-Id: I8d75b863dbaaef2673f7c36da4afae036d7b3e34 --- Wrapping/Python/CMakeLists.txt | 6 - Wrapping/Python/Packaging/ez_setup.py | 364 ------------------ Wrapping/Python/Packaging/setupegg.py | 12 +- .../Python/PythonVirtualEnvInstall.cmake.in | 44 +-- Wrapping/Python/dist/CMakeLists.txt | 27 +- 5 files changed, 36 insertions(+), 417 deletions(-) delete mode 100755 Wrapping/Python/Packaging/ez_setup.py diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index 05323d752..37a35ca5d 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -83,11 +83,6 @@ configure_file( "${CMAKE_CURRENT_BINARY_DIR}/Packaging/setupegg.py" COPYONLY ) -configure_file( - "${CMAKE_CURRENT_SOURCE_DIR}/Packaging/ez_setup.py" - "${CMAKE_CURRENT_BINARY_DIR}/Packaging/ez_setup.py" - COPYONLY ) - configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/Packaging/__init__.py" "${CMAKE_CURRENT_BINARY_DIR}/__init__.py" @@ -141,7 +136,6 @@ if (SITK_PYTHON_USE_VIRTUALENV) "${SWIG_MODULE_SimpleITKPython_TARGET_NAME}" "${CMAKE_CURRENT_BINARY_DIR}/PythonVirtualEnvInstall.cmake" ConfigureFileBuildtime - "${CMAKE_CURRENT_BINARY_DIR}/Packaging/ez_setup.py" COMMENT "Creating python virtual enviroment..." ) else() diff --git a/Wrapping/Python/Packaging/ez_setup.py b/Wrapping/Python/Packaging/ez_setup.py deleted file mode 100755 index 1420c114d..000000000 --- a/Wrapping/Python/Packaging/ez_setup.py +++ /dev/null @@ -1,364 +0,0 @@ -#!/usr/bin/env python -"""Bootstrap setuptools installation - -To use setuptools in your package's setup.py, include this -file in the same directory and add this to the top of your setup.py:: - - from ez_setup import use_setuptools - use_setuptools() - -To require a specific version of setuptools, set a download -mirror, or use an alternate download directory, simply supply -the appropriate options to ``use_setuptools()``. - -This file can also be run as a script to install or upgrade setuptools. -""" -import os -import shutil -import sys -import tempfile -import tarfile -import optparse -import subprocess -import platform -import textwrap - -from distutils import log - -try: - from site import USER_SITE -except ImportError: - USER_SITE = None - -DEFAULT_VERSION = "2.2" -DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/" - -def _python_cmd(*args): - """ - Return True if the command succeeded. - """ - args = (sys.executable,) + args - return subprocess.call(args) == 0 - -def _install(tarball, install_args=()): - # extracting the tarball - tmpdir = tempfile.mkdtemp() - log.warn('Extracting in %s', tmpdir) - old_wd = os.getcwd() - try: - os.chdir(tmpdir) - tar = tarfile.open(tarball) - _extractall(tar) - tar.close() - - # going in the directory - subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) - os.chdir(subdir) - log.warn('Now working in %s', subdir) - - # installing - log.warn('Installing Setuptools') - if not _python_cmd('setup.py', 'install', *install_args): - log.warn('Something went wrong during the installation.') - log.warn('See the error message above.') - # exitcode will be 2 - return 2 - finally: - os.chdir(old_wd) - shutil.rmtree(tmpdir) - - -def _build_egg(egg, tarball, to_dir): - # extracting the tarball - tmpdir = tempfile.mkdtemp() - log.warn('Extracting in %s', tmpdir) - old_wd = os.getcwd() - try: - os.chdir(tmpdir) - tar = tarfile.open(tarball) - _extractall(tar) - tar.close() - - # going in the directory - subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) - os.chdir(subdir) - log.warn('Now working in %s', subdir) - - # building an egg - log.warn('Building a Setuptools egg in %s', to_dir) - _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) - - finally: - os.chdir(old_wd) - shutil.rmtree(tmpdir) - # returning the result - log.warn(egg) - if not os.path.exists(egg): - raise IOError('Could not build the egg.') - - -def _do_download(version, download_base, to_dir, download_delay): - egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg' - % (version, sys.version_info[0], sys.version_info[1])) - if not os.path.exists(egg): - tarball = download_setuptools(version, download_base, - to_dir, download_delay) - _build_egg(egg, tarball, to_dir) - sys.path.insert(0, egg) - - # Remove previously-imported pkg_resources if present (see - # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details). - if 'pkg_resources' in sys.modules: - del sys.modules['pkg_resources'] - - import setuptools - setuptools.bootstrap_install_from = egg - - -def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, - to_dir=os.curdir, download_delay=15): - to_dir = os.path.abspath(to_dir) - rep_modules = 'pkg_resources', 'setuptools' - imported = set(sys.modules).intersection(rep_modules) - try: - import pkg_resources - except ImportError: - return _do_download(version, download_base, to_dir, download_delay) - try: - pkg_resources.require("setuptools>=" + version) - return - except pkg_resources.DistributionNotFound: - return _do_download(version, download_base, to_dir, download_delay) - except pkg_resources.VersionConflict as VC_err: - if imported: - msg = textwrap.dedent(""" - The required version of setuptools (>={version}) is not available, - and can't be installed while this script is running. Please - install a more recent version first, using - 'easy_install -U setuptools'. - - (Currently using {VC_err.args[0]!r}) - """).format(VC_err=VC_err, version=version) - sys.stderr.write(msg) - sys.exit(2) - - # otherwise, reload ok - del pkg_resources, sys.modules['pkg_resources'] - return _do_download(version, download_base, to_dir, download_delay) - -def _clean_check(cmd, target): - """ - Run the command to download target. If the command fails, clean up before - re-raising the error. - """ - try: - subprocess.check_call(cmd) - except subprocess.CalledProcessError: - if os.access(target, os.F_OK): - os.unlink(target) - raise - -def download_file_powershell(url, target): - """ - Download the file at url to target using Powershell (which will validate - trust). Raise an exception if the command cannot complete. - """ - target = os.path.abspath(target) - cmd = [ - 'powershell', - '-Command', - "(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)" % vars(), - ] - _clean_check(cmd, target) - -def has_powershell(): - if platform.system() != 'Windows': - return False - cmd = ['powershell', '-Command', 'echo test'] - devnull = open(os.path.devnull, 'wb') - try: - try: - subprocess.check_call(cmd, stdout=devnull, stderr=devnull) - except: - return False - finally: - devnull.close() - return True - -download_file_powershell.viable = has_powershell - -def download_file_curl(url, target): - cmd = ['curl', url, '--silent', '--output', target] - _clean_check(cmd, target) - -def has_curl(): - cmd = ['curl', '--version'] - devnull = open(os.path.devnull, 'wb') - try: - try: - subprocess.check_call(cmd, stdout=devnull, stderr=devnull) - except: - return False - finally: - devnull.close() - return True - -download_file_curl.viable = has_curl - -def download_file_wget(url, target): - cmd = ['wget', url, '--quiet', '--output-document', target] - _clean_check(cmd, target) - -def has_wget(): - cmd = ['wget', '--version'] - devnull = open(os.path.devnull, 'wb') - try: - try: - subprocess.check_call(cmd, stdout=devnull, stderr=devnull) - except: - return False - finally: - devnull.close() - return True - -download_file_wget.viable = has_wget - -def download_file_insecure(url, target): - """ - Use Python to download the file, even though it cannot authenticate the - connection. - """ - try: - from urllib.request import urlopen - except ImportError: - from urllib2 import urlopen - src = dst = None - try: - src = urlopen(url) - # Read/write all in one block, so we don't create a corrupt file - # if the download is interrupted. - data = src.read() - dst = open(target, "wb") - dst.write(data) - finally: - if src: - src.close() - if dst: - dst.close() - -download_file_insecure.viable = lambda: True - -def get_best_downloader(): - downloaders = [ - download_file_powershell, - download_file_curl, - download_file_wget, - download_file_insecure, - ] - - for dl in downloaders: - if dl.viable(): - return dl - -def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, - to_dir=os.curdir, delay=15, - downloader_factory=get_best_downloader): - """Download setuptools from a specified location and return its filename - - `version` should be a valid setuptools version number that is available - as an egg for download under the `download_base` URL (which should end - with a '/'). `to_dir` is the directory where the egg will be downloaded. - `delay` is the number of seconds to pause before an actual download - attempt. - - ``downloader_factory`` should be a function taking no arguments and - returning a function for downloading a URL to a target. - """ - # making sure we use the absolute path - to_dir = os.path.abspath(to_dir) - tgz_name = "setuptools-%s.tar.gz" % version - url = download_base + tgz_name - saveto = os.path.join(to_dir, tgz_name) - if not os.path.exists(saveto): # Avoid repeated downloads - log.warn("Downloading %s", url) - downloader = downloader_factory() - downloader(url, saveto) - return os.path.realpath(saveto) - - -def _extractall(self, path=".", members=None): - """Extract all members from the archive to the current working - directory and set owner, modification time and permissions on - directories afterwards. `path' specifies a different directory - to extract to. `members' is optional and must be a subset of the - list returned by getmembers(). - """ - import copy - import operator - from tarfile import ExtractError - directories = [] - - if members is None: - members = self - - for tarinfo in members: - if tarinfo.isdir(): - # Extract directories with a safe mode. - directories.append(tarinfo) - tarinfo = copy.copy(tarinfo) - tarinfo.mode = 448 # decimal for oct 0700 - self.extract(tarinfo, path) - - # Reverse sort directories. - directories.sort(key=operator.attrgetter('name'), reverse=True) - - # Set correct owner, mtime and filemode on directories. - for tarinfo in directories: - dirpath = os.path.join(path, tarinfo.name) - try: - self.chown(tarinfo, dirpath) - self.utime(tarinfo, dirpath) - self.chmod(tarinfo, dirpath) - except ExtractError as e: - if self.errorlevel > 1: - raise - else: - self._dbg(1, "tarfile: %s" % e) - - -def _build_install_args(options): - """ - Build the arguments to 'python setup.py install' on the setuptools package - """ - return ['--user'] if options.user_install else [] - -def _parse_args(): - """ - Parse the command line for options - """ - parser = optparse.OptionParser() - parser.add_option( - '--user', dest='user_install', action='store_true', default=False, - help='install in user site package (requires Python 2.6 or later)') - parser.add_option( - '--download-base', dest='download_base', metavar="URL", - default=DEFAULT_URL, - help='alternative URL from where to download the setuptools package') - parser.add_option( - '--insecure', dest='downloader_factory', action='store_const', - const=lambda: download_file_insecure, default=get_best_downloader, - help='Use internal, non-validating downloader' - ) - options, args = parser.parse_args() - # positional arguments are ignored - return options - -def main(version=DEFAULT_VERSION): - """Install or upgrade setuptools and EasyInstall""" - options = _parse_args() - tarball = download_setuptools(download_base=options.download_base, - downloader_factory=options.downloader_factory) - return _install(tarball, _build_install_args(options)) - -if __name__ == '__main__': - sys.exit(main()) diff --git a/Wrapping/Python/Packaging/setupegg.py b/Wrapping/Python/Packaging/setupegg.py index 443158185..05e090f93 100644 --- a/Wrapping/Python/Packaging/setupegg.py +++ b/Wrapping/Python/Packaging/setupegg.py @@ -1,8 +1,14 @@ """ -A setup.py script to use setuptools, which gives egg goodness, etc. +A setup.py script to use setuptools, which gives wheel and egg goodness, etc. """ -from ez_setup import use_setuptools -use_setuptools() +try: + from setuptools import setup +except ImportError: + # SimpleITK no longer provides ez_setup, but a copy may be around + # so we give it a try. It's intended that setuptools be install in + # a constructed virtualenv during the make process. + from ez_setup import use_setuptools + use_setuptools() import os from setuptools import setup diff --git a/Wrapping/Python/PythonVirtualEnvInstall.cmake.in b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in index 9d18444d2..69cd81c17 100644 --- a/Wrapping/Python/PythonVirtualEnvInstall.cmake.in +++ b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in @@ -3,6 +3,17 @@ if(POLICY CMP0012) cmake_policy(SET CMP0012 NEW) endif() +set(VIRTUALENV_ARGS --clear --no-pip) +if ( NOT "@SITK_FORBID_DOWNLOADS@" ) + set(VIRTUALENV_ARGS ${VIRTUALENV_ARGS} --download) +endif() +if ( NOT "@SimpleITK_PYTHON_WHEEL@" ) + set(VIRTUALENV_ARGS ${VIRTUALENV_ARGS} --no-wheel) + if ( NOT "@SimpleITK_PYTHON_EGG@" ) + set(VIRTUALENV_ARGS ${VIRTUALENV_ARGS} --no-setuptools) + endif() +endif() + # # Create the Python virtual environment. # @@ -10,9 +21,7 @@ execute_process( COMMAND "@PYTHON_EXECUTABLE@" "@PYTHON_VIRTUALENV_EXECUTABLE@" "--python=@PYTHON_EXECUTABLE@" - --no-pip - --no-setuptools - --clear + ${VIRTUALENV_ARGS} "@PythonVirtualenvHome@" WORKING_DIRECTORY "@SimpleITK_SOURCE_DIR@/Wrapping/Python" RESULT_VARIABLE failed @@ -42,35 +51,6 @@ if ( failed ) message( FATAL_ERROR "Installation of SimpleITK into Python virutal enviroment failed.\n${error}" ) endif() - -if ( "@SimpleITK_PYTHON_WHEEL@" ) - - set(install_wheel_script " -import sys -from ez_setup import use_setuptools -use_setuptools() -if not(sys.modules.get(\"wheel\")): - from setuptools.command import easy_install - easy_install.main([\"wheel\"]) -") - - # - # Install Python wheel package. - # - message(STATUS "Installing Python Package: wheel") - execute_process( - COMMAND @VIRTUAL_PYTHON_EXECUTABLE@ -c "${install_wheel_script}" - WORKING_DIRECTORY "Packaging" - ERROR_VARIABLE error - RESULT_VARIABLE failed - ) - - if ( failed ) - message( WARNING ${error} ) - endif() -endif() - - # # Get Python library directory. # diff --git a/Wrapping/Python/dist/CMakeLists.txt b/Wrapping/Python/dist/CMakeLists.txt index 4b65ed928..b40de44ae 100644 --- a/Wrapping/Python/dist/CMakeLists.txt +++ b/Wrapping/Python/dist/CMakeLists.txt @@ -3,26 +3,29 @@ # if( SimpleITK_PYTHON_EGG OR SimpleITK_PYTHON_WHEEL ) + if( NOT SITK_PYTHON_USE_VIRTUALENV ) + message( STATUS "Not using SimpleITK's virtualenv for distribution!\ +Using unknown versions of pip, setuptools and/or wheel packages/" ) + endif() + set(bdist_setup "${SimpleITK_BINARY_DIR}/Wrapping/Python/Packaging/setupegg.py") set(bdist_commands "") + if( SimpleITK_PYTHON_EGG ) set(bdist_commands "bdist_egg") endif() + if( SimpleITK_PYTHON_WHEEL ) - set(bdist_commands ${bdist_commands} bdist_wheel) + set(bdist_commands ${bdist_commands} "bdist_wheel") endif() - if( SITK_PYTHON_USE_VIRTUALENV ) - add_custom_target( dist.Python - ${VIRTUAL_PYTHON_EXECUTABLE} ${SimpleITK_BINARY_DIR}/Wrapping/Python/Packaging/setupegg.py ${bdist_commands} - WORKING_DIRECTORY ${SimpleITK_BINARY_DIR}/Wrapping/Python - DEPENDS ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} - COMMENT "Creating Python binary distribution" ) + add_custom_target( dist.Python + ${VIRTUAL_PYTHON_EXECUTABLE} ${bdist_setup} ${bdist_commands} + WORKING_DIRECTORY ${SimpleITK_BINARY_DIR}/Wrapping/Python + DEPENDS ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} + COMMENT "Creating Python binary distribution" ) - add_dependencies( dist.Python PythonVirtualEnv) - add_dependencies( dist dist.Python ) - elseif() - message( STATUS "Not creating dist.Python target since SITK_FORBID_DOWNLOADS is enabled" ) - endif() + add_dependencies( dist.Python PythonVirtualEnv) + add_dependencies( dist dist.Python ) endif() From af98660dad27915559e53204f85af14500150c4b Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Tue, 24 Nov 2015 21:14:26 +1100 Subject: [PATCH 151/412] Support for more indexing operations. 1) A double bracket operator to extract an image component 2) Improved support for accessing a single pixel with single bracket operators. Includes support for vector types that aren't automatically cast to R vectors. Improved testing, and bugfix relating to sitkInt8. Change-Id: Id224c5091b25a97ead50666d70a259ede2bd33f7 --- Testing/Unit/AdditionalTests.cmake | 3 ++ Testing/Unit/RPixelAccess.R | 39 ++++++++++++++++++ Wrapping/R/Packaging/SimpleITK/R/zA.R | 57 +++++++++++++++++++++++++-- Wrapping/R/R.i | 18 +++++++++ 4 files changed, 113 insertions(+), 4 deletions(-) create mode 100644 Testing/Unit/RPixelAccess.R diff --git a/Testing/Unit/AdditionalTests.cmake b/Testing/Unit/AdditionalTests.cmake index c54649cbb..d18b76e24 100644 --- a/Testing/Unit/AdditionalTests.cmake +++ b/Testing/Unit/AdditionalTests.cmake @@ -54,6 +54,9 @@ sitk_add_java_test( ProcessObjectTest sitk_add_r_test( Arithmetic "--file=${SimpleITK_SOURCE_DIR}/Testing/Unit/RArithmeticTest.R" ) +sitk_add_r_test( PixelIndexing + "--file=${SimpleITK_SOURCE_DIR}/Testing/Unit/RPixelAccess.R" + ) # diff --git a/Testing/Unit/RPixelAccess.R b/Testing/Unit/RPixelAccess.R new file mode 100644 index 000000000..36950c560 --- /dev/null +++ b/Testing/Unit/RPixelAccess.R @@ -0,0 +1,39 @@ +## tests of image pixel access. +## helps to check whether the rtype entries for std:vector in R.i are OK. +library(SimpleITK) + +## generate a test image with 2 components. +pp <- PhysicalPointImageSource() +x <- Image(c(25,25), 'sitkUInt8') +pp$SetReferenceImage(x) +fr <- pp$Execute() + +## first component has rows with equal value, starting from 0. +## second component has columns with equal value, stating from 0. +# cast to lots of different types +targs <- c("sitkVectorUInt8", "sitkVectorInt8", "sitkVectorUInt16", + "sitkVectorInt16", "sitkVectorUInt32", "sitkVectorInt32", + "sitkVectorUInt64", "sitkVectorInt64", "sitkVectorFloat32", + "sitkVectorFloat64") +names(targs) <- targs +castims <- lapply(targs, function(m)Cast(fr, m)) +res<-list() +pixvals <- list() + +vectorextract <- sapply(castims, function(K)K[3,4]) +channelextract <- sapply(castims, function(K)K[[1]][3,4]) + +if (any(vectorextract[1,] != 2) | any(vectorextract[2,] != 3)) +{ + cat("Failure in vector extraction\n") + cat("Pixel type :", targs[(vectorextract[1,] != 2) | + (vectorextract[2,] != 3)], "\n") + quit(save="no", status=1) +} + +if (any(channelextract != 2) ) +{ + cat("Failure in channel extraction\n") + cat("Pixel type: ", targs[channelextract != 2], "\n") + quit(save="no", status=1) +} diff --git a/Wrapping/R/Packaging/SimpleITK/R/zA.R b/Wrapping/R/Packaging/SimpleITK/R/zA.R index bc6e4254d..85f292188 100644 --- a/Wrapping/R/Packaging/SimpleITK/R/zA.R +++ b/Wrapping/R/Packaging/SimpleITK/R/zA.R @@ -62,6 +62,43 @@ 'Image_SetPixelAsFloat' = RsitkFloat64() )) + createPixLookup() +} + +createPixLookup <- function( where = topenv(parent.frame())) +{ + m <- get(".__E___itk__simple__PixelIDValueEnum") + # get rid of unknown type - can't access anyway. There will be errors if + # it happens. + # Also need to map Float32 to Float and Float64 to Double + m <- m[m>=0] + n <- names(m) + # Turn the names into function names + ff <- gsub("^sitk(.+)", "Image_GetPixelAs\\1", n) + ff <- gsub("AsFloat32$", "AsFloat", ff) + ff <- gsub("AsFloat64$", "AsDouble", ff) + + sitkPixelAccessMap <- mget(ff, envir=where, + ifnotfound=rep(NA,length(ff))) + names(sitkPixelAccessMap) <- n + assign("sitkPixelAccessMap", sitkPixelAccessMap, envir=where) +} + +ImportPixVec <- function(VP) +{ + ## some pixel vectors aren't automatically converted to + ## R vectors, so we'll do it the long way to avoid having to + ## write new swig fragments dealing with + + ## some pixel vectors work as expected - return them + if (is.numeric(VP)) return(VP) + + l <- VP$'__len__'() + res <- rep(NA, l) + for (idx in 1:l) { + res[idx] <- VP$'__getitem__'(idx-1) + } + return(res) } # experimental bracket operator for images @@ -104,12 +141,11 @@ setMethod('[', "_p_itk__simple__Image", k <- k - 1 if ((length(i) == 1) & (length(j) == 1) & (length(k) == 1) ) { ## return a single point - pixtype <- x$GetPixelIDValue() - afName <- enumFromInteger(pixtype, "_itk__simple__PixelGetEnum") - aF <- get(afName) + pixtype <- x$GetPixelID() + aF <- sitkPixelAccessMap[[pixtype]] if (!is.null(aF)) { ## need to check whether we are using R or C indexing. - return(aF(x, c(i, j,k))) + return(ImportPixVec(aF(x, c(i, j,k)))) } } else { ## construct and return an image @@ -121,13 +157,26 @@ setMethod('[', "_p_itk__simple__Image", } ) +setMethod('[[', "_p_itk__simple__Image", + function(x, i, j, ...) { + return(VectorIndexSelectionCast(x, i-1)) + } + ) setMethod('as.array', "_p_itk__simple__Image", function(x, drop=TRUE) { sz <- x$GetSize() + components <- x$GetNumberOfComponentsPerPixel() + if (components > 1) sz <- c(components, sz) if (.hasSlot(x, "ref")) x = slot(x,"ref") ans = .Call("R_swig_ImAsArray", x, FALSE, PACKAGE = "SimpleITK") dim(ans) <- sz + if (components > 1) { + ## vector images have planes stored next to each other. + ## place in separate planes for sensible display + perm <- c(2:length(sz), 1) + ans <- aperm(ans, perm) + } if (drop) return(drop(ans)) return(ans) diff --git a/Wrapping/R/R.i b/Wrapping/R/R.i index 7dda7e9da..632707a2c 100644 --- a/Wrapping/R/R.i +++ b/Wrapping/R/R.i @@ -12,10 +12,28 @@ unsigned char & %{ %} + // SEXP numeric typemap for array/image converion - SEXP are // arrays here %typemap("rtype") SEXP "numeric"; +// Gets rid of the class check for unsigned char function arguments +%typemap("rtype") unsigned char, unsigned char *, unsigned char & "integer"; +// and for unsigned int vectors, and various pixel types that can be automatically +// converted to R vectors. Otherwise the conversion happens in the C code and +// the wrong class gets assigned on output +%typemap("rtype") std::vector, std::vector *, std::vector & "integer"; +%typemap("rtype") std::vector, std::vector *, std::vector & "integer"; +%typemap("rtype") std::vector, std::vector *, std::vector & "integer"; +%typemap("rtype") std::vector, std::vector *, std::vector & "numeric"; + +// stop classes being asigned as these are already converted to R vectors. +%typemap(scoerceout) std::vector, std::vector *, std::vector &, +std::vector, std::vector *, std::vector & +%{ %} + +// some important enumerations don't get evaluate properly. This is a +// hack to fix the problem. %inline %{ #include "sitkConditional.h" From 4047386793bc3a43785d7af1ea2eff13348c3eae Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 24 Feb 2016 10:29:07 -0500 Subject: [PATCH 152/412] Correctly add superbuild dependency on virtualenv There was a copy paste error, and now it's only needed with when wrapping for Python is done. Change-Id: I159ebb985d02f27c9a3a7ac91465d6c1c4ad3d4c --- SuperBuild/SuperBuild.cmake | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index bbbf5b5f3..7507fa45f 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -300,7 +300,9 @@ if ( USE_SYSTEM_VIRTUALENV ) else() include(External_virtualenv) list(APPEND SimpleITK_VARS PYTHON_VIRTUALENV_EXECUTABLE) - list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES GTest) + if ( WRAP_PYTHON ) + list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES virtualenv) + endif() endif() @@ -406,7 +408,7 @@ include(External_SimpleITKExamples) #------------------------------------------------------------------------------ # List of external projects #------------------------------------------------------------------------------ -set(external_project_list ITK Swig SimpleITKExamples PCRE Lua GTest ${CMAKE_PROJECT_NAME}) +set(external_project_list ITK Swig SimpleITKExamples PCRE Lua GTest virtualenv ${CMAKE_PROJECT_NAME}) #----------------------------------------------------------------------------- From f376cf0764d5512c97964f0941061ffa99838ae9 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 24 Feb 2016 14:17:21 -0500 Subject: [PATCH 153/412] Add find package for Python virtualenv Added standard Find*.cmake file for helping to find the virtualenv executable/script. Additionally, this add getting the version of virtualenv too. Change-Id: Idd7236230e9f4bb199778c3e82110893815c808c --- CMake/FindPythonVirtualEnv.cmake | 45 ++++++++++++++++++++++++++++++++ SuperBuild/SuperBuild.cmake | 5 ++-- Wrapping/Python/CMakeLists.txt | 3 +-- 3 files changed, 48 insertions(+), 5 deletions(-) create mode 100644 CMake/FindPythonVirtualEnv.cmake diff --git a/CMake/FindPythonVirtualEnv.cmake b/CMake/FindPythonVirtualEnv.cmake new file mode 100644 index 000000000..ba4a1d0d9 --- /dev/null +++ b/CMake/FindPythonVirtualEnv.cmake @@ -0,0 +1,45 @@ +#.rst: +# FindPythonVirtualEnv +# -------- +# +# Find Python's VirtualEnv Utility +# +# :: +# +# PYTHON_VIRTUALENV_EXECUTABLE - the full path to virtualenv +# PYTHON_VIRTUALENV_EXECUTABLE_FOUND - If false, don't attempt to use lua +# PYTHON_VIRTUALENV_VERSION_STRING - version of lua found + +find_program(PYTHON_VIRTUALENV_EXECUTABLE + NAMES virtualenv virtualenv.py + ) + +if(PYTHON_VIRTUALENV_EXECUTABLE) + ### PYTHON_VIRTUALENV_VERSION + execute_process( + COMMAND ${PYTHON_VIRTUALENV_EXECUTABLE} --version + OUTPUT_VARIABLE + PYTHON_VIRTUALENV_VERSION_STRING + ERROR_VARIABLE + PYTHON_VIRTUALENV_VERSION_STRING + RESULT_VARIABLE + PYTHON_VIRTUALENV_VERSION_RESULT_VARIABLE + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_STRIP_TRAILING_WHITESPACE + ) + if (NOT PYTHON_VIRTUALENV_VERSION_RESULT_VARIABLE) + string( REGEX MATCH "([0-9]*)([.])([0-9]*)([.]*)([0-9]*)" + PYTHON_VIRTUALENV_VERSION + ${PYTHON_VIRTUALENV_VERSION_STRING} ) + endif() +endif() + + +# handle the QUIETLY and REQUIRED arguments and set PYTHON_VIRTUALENV_FOUND to TRUE if +# all listed variables are TRUE +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(PythonVirtualEnv + REQUIRED_VARS PYTHON_VIRTUALENV_EXECUTABLE + VERSION_VAR PYTHON_VIRTUALENV_VERSION_STRING) + +mark_as_advanced(PYTHON_VIRTUALENV_EXECUTABLE) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 7507fa45f..d3e8821ce 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -296,15 +296,14 @@ endif() option( USE_SYSTEM_VIRTUALENV "Use a system version of Python's virtualenv. " OFF ) mark_as_advanced(USE_SYSTEM_VIRTUALENV) if ( USE_SYSTEM_VIRTUALENV ) - set( PYTHON_VIRTUALENV_EXECUTABLE "" CACHE FILEPATH "Python virtualenv executable" ) + find_package( PythonVirtualEnv REQUIRED) else() include(External_virtualenv) - list(APPEND SimpleITK_VARS PYTHON_VIRTUALENV_EXECUTABLE) if ( WRAP_PYTHON ) list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES virtualenv) endif() endif() - +list(APPEND SimpleITK_VARS PYTHON_VIRTUALENV_EXECUTABLE) #------------------------------------------------------------------------------ # ITK diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index 37a35ca5d..34d72f78e 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -94,8 +94,7 @@ mark_as_advanced(SITK_PYTHON_USE_VIRTUALENV) if (SITK_PYTHON_USE_VIRTUALENV) # Executable to setup a new Python virtual environment - # todo use a find_program and get version - set( PYTHON_VIRTUALENV_EXECUTABLE "" CACHE FILEPATH "Python virtualenv executable") + find_package( PythonVirtualEnv REQUIRED ) sitk_enforce_forbid_downloads( SITK_PYTHON_USE_VIRTUALENV ) # From ea7c12501af07c95d6ae6042f427669282715540 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 24 Feb 2016 14:37:38 -0500 Subject: [PATCH 154/412] Tweak virtualenv creation options Prefer --never-download over --no-download as it works with older versions of the tool. Also --no-wheel was introduced in version 13.0, so only that options with a sufficient version. Change-Id: I7cb08a5fbcbc694d7ae082bdaeb5720f57fe7012 --- Wrapping/Python/PythonVirtualEnvInstall.cmake.in | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Wrapping/Python/PythonVirtualEnvInstall.cmake.in b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in index 69cd81c17..ffd53abd4 100644 --- a/Wrapping/Python/PythonVirtualEnvInstall.cmake.in +++ b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in @@ -4,11 +4,13 @@ if(POLICY CMP0012) endif() set(VIRTUALENV_ARGS --clear --no-pip) -if ( NOT "@SITK_FORBID_DOWNLOADS@" ) - set(VIRTUALENV_ARGS ${VIRTUALENV_ARGS} --download) +if ( "@SITK_FORBID_DOWNLOADS@" ) + set(VIRTUALENV_ARGS ${VIRTUALENV_ARGS} --never-download) endif() if ( NOT "@SimpleITK_PYTHON_WHEEL@" ) - set(VIRTUALENV_ARGS ${VIRTUALENV_ARGS} --no-wheel) + if ("@PYTHON_VIRTUALENV_VERSION_STRING@" VERSION_GREATER "13") + set(VIRTUALENV_ARGS ${VIRTUALENV_ARGS} --no-wheel) + endif() if ( NOT "@SimpleITK_PYTHON_EGG@" ) set(VIRTUALENV_ARGS ${VIRTUALENV_ARGS} --no-setuptools) endif() From b79ed010b6638678615fd5a9ddf1ff8d75c57cc6 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Thu, 25 Feb 2016 15:07:41 +0100 Subject: [PATCH 155/412] BUG: Fix Java 1.8 javadoc linting breaking the java build --- Wrapping/Java/CMakeLists.txt | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Wrapping/Java/CMakeLists.txt b/Wrapping/Java/CMakeLists.txt index 27b62432f..4dd3db03b 100644 --- a/Wrapping/Java/CMakeLists.txt +++ b/Wrapping/Java/CMakeLists.txt @@ -29,6 +29,18 @@ sitk_strip_target( ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} ) add_custom_target(org_itk_simple_jar ALL DEPENDS ${JAR_FILE}) set(JAVA_SOURCE_CODE ${JAVA_SOURCE_DIRECTORY}/org/itk/simple/*.java) +# Java 1.8 javadoc treats linting errors as build errors by default +# so linting should be opt-in for this version +if( ${Java_VERSION_STRING} VERSION_EQUAL 1.8 OR ${Java_VERSION_STRING} VERSION_GREATER 1.8 ) + mark_as_advanced( Java_JAVADOC_LINTING ) + option( Java_JAVADOC_LINTING "Enable javadoc linting for Java 1.8" OFF ) + if( Java_JAVADOC_LINTING ) + set( Java_JAVADOC_LINTING_CMD "-Xdoclint:all" ) + else() + set( Java_JAVADOC_LINTING_CMD "-Xdoclint:none" ) + endif() +endif() + # Add custom command and target to compile the generated files and put them in a jar file # Make sure the commands depend on the output library from SWIG add_custom_command( @@ -36,7 +48,7 @@ add_custom_command( COMMENT "Creating jar file..." COMMAND ${Java_JAVAC_EXECUTABLE} -d ${JAVA_BINARY_DIRECTORY} ${JAVA_SOURCE_CODE} COMMAND ${Java_JAR_EXECUTABLE} cf ${CMAKE_CURRENT_BINARY_DIR}/${JAR_FILE} -C ${JAVA_BINARY_DIRECTORY} org - COMMAND ${Java_JAVADOC_EXECUTABLE} -quiet -d ${JAVA_BINARY_DIRECTORY}/javadoc -sourcepath ${JAVA_SOURCE_DIRECTORY} org.itk.simple + COMMAND ${Java_JAVADOC_EXECUTABLE} ${Java_JAVADOC_LINTING_CMD} -quiet -d ${JAVA_BINARY_DIRECTORY}/javadoc -sourcepath ${JAVA_SOURCE_DIRECTORY} org.itk.simple COMMAND ${Java_JAR_EXECUTABLE} cf ${CMAKE_CURRENT_BINARY_DIR}/${JAVADOC_FILE} -C ${JAVA_BINARY_DIRECTORY}/javadoc org COMMAND ${Java_JAR_EXECUTABLE} cf ${CMAKE_CURRENT_BINARY_DIR}/${JAVA_SOURCE_FILE} org DEPENDS ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} From 9cf4600737e4ecc345f5686713636e87111cbef0 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 4 Mar 2016 13:18:23 -0500 Subject: [PATCH 156/412] Adding JSON validation on precommit and during code generation The version of the SetupForDevelopment.sh has been increase forcing and update to the .git/hooks repository along with updates to the configuration variables. Adding verbose JSON validation before code generation, conditional on having Python. The Lua parser is not strict nor does it give reasonable error messages for parsing errors. The Python's json module provides validation along with verbose error messages including the line and column number. Adding basic precommit hook to check that the json are valid with minimal Python. This hook should be required to commit json changes, but it's expected the developer will use the building JSON validation to get verbose error messages. Change-Id: I933b587579627fa2619356d3979221a0de3548d3 --- CMake/generate_filter_source.cmake | 3 ++ .../DevelopmentSetupScripts/SetupHooks.sh | 6 ++++ Utilities/Hooks/pre-commit | 30 +++++++++++++++++++ Utilities/JSONValidate.py | 14 +++++++++ Utilities/SetupForDevelopment.sh | 2 +- 5 files changed, 54 insertions(+), 1 deletion(-) create mode 100755 Utilities/JSONValidate.py diff --git a/CMake/generate_filter_source.cmake b/CMake/generate_filter_source.cmake index 28eb147c2..950185e71 100644 --- a/CMake/generate_filter_source.cmake +++ b/CMake/generate_filter_source.cmake @@ -111,9 +111,12 @@ macro( expand_template FILENAME input_dir output_dir library_name ) # Make a global list of ImageFilter template filters set ( IMAGE_FILTER_LIST ${IMAGE_FILTER_LIST} ${FILENAME} CACHE INTERNAL "" ) + # validate + # header add_custom_command ( OUTPUT "${output_h}" + COMMAND ${PYTHON_EXECUTABLE} "${SimpleITK_SOURCE_DIR}/Utilities/JSONValidate.py" ${input_json_file} COMMAND ${CMAKE_COMMAND} -E remove -f ${output_h} COMMAND ${SITK_LUA_EXECUTABLE} ${expand_template_script} code ${input_json_file} ${input_dir}/templates/sitk ${template_include_dir} Template.h.in ${output_h} DEPENDS ${input_json_file} ${template_deps} ${template_file_h} diff --git a/Utilities/DevelopmentSetupScripts/SetupHooks.sh b/Utilities/DevelopmentSetupScripts/SetupHooks.sh index e22942af0..00f32229c 100755 --- a/Utilities/DevelopmentSetupScripts/SetupHooks.sh +++ b/Utilities/DevelopmentSetupScripts/SetupHooks.sh @@ -65,4 +65,10 @@ git config hooks.submodule false git config hooks.KWStyle.conf "Utilities/KWStyle/SITK.kws.xml.in" git config hooks.KWStyle.overwriteRulesConf "Utilities/KWStyle/SITKOverwrite.txt" + +echo "Setting up JSON validation with python..." +PYTHON_EXECUTABLE=$(which python) || die "No python found for hooks." +git config hooks.python ${PYTHON_EXECUTABLE} +git config hooks.ValidateJSON true + echo "Done." diff --git a/Utilities/Hooks/pre-commit b/Utilities/Hooks/pre-commit index 25880e7f6..03a51ce55 100755 --- a/Utilities/Hooks/pre-commit +++ b/Utilities/Hooks/pre-commit @@ -69,3 +69,33 @@ test -z "$bad" || die "$bad" #----------------------------------------------------------------------------- # Style hooks. . "${BASH_SOURCE%/*}/pre-commit-style.bash" + +# Validate json files +validate_json() { + changes=$(git diff-files -- "$1") && + if test -n "$changes"; then + die "Cannot validate '$1' with work tree changes." + fi && + out=$($python_exe -c "import sys, json; json.load( file( sys.argv[1], 'r' ) )" "$1" 2>&1) || die "JSON Validation error with \"$file\". +$out" +} + +json_files=$(git diff-index --cached HEAD --diff-filter=AM ) && +if test -n "$json_files"; then + validate=$(git config --get --bool hooks.ValidateJSON || echo true) && + if test "$validate" = "true"; then + python_exe=$(git config hooks.python || type -p python) && + if test -z "$python_exe"; then + die 'Cannont validate SimpleITK JSON files with out Python. +Configure Python's location with: + + git config hooks.python + echo "$json_files" | + while read src_mode dst_mode src_obj dst_obj status file; do + if echo "$file" | egrep-q '\.json$'; then + echo "validating $file" + validate_json "$file" + fi + done + fi +fi diff --git a/Utilities/JSONValidate.py b/Utilities/JSONValidate.py new file mode 100755 index 000000000..730383103 --- /dev/null +++ b/Utilities/JSONValidate.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python +from __future__ import print_function +import json, sys + +try: + json.load( file( sys.argv[1], "r" )) +except ValueError as e: + print( "ValueError: {0}".format( e ) ) + print( "{0}:0:0: error: validating json file.".format( sys.argv[1] ) ) + sys.exit(1) +except TypeError as e: + print( "TypeError: {0}".format( e ) ) + print( "{0}:0:0: error: validating json file.".format( sys.argv[1] ) ) + sys.exit(1) diff --git a/Utilities/SetupForDevelopment.sh b/Utilities/SetupForDevelopment.sh index f1d4c2fb6..0187d43db 100755 --- a/Utilities/SetupForDevelopment.sh +++ b/Utilities/SetupForDevelopment.sh @@ -144,5 +144,5 @@ echo "Suggesting git tips..." echo # Record the version of this setup so Hooks/pre-commit can check it. -SetupForDevelopment_VERSION=1 +SetupForDevelopment_VERSION=2 git config hooks.SetupForDevelopment ${SetupForDevelopment_VERSION} From cfbbd02634f4d2261bc2e4c4bd8429824f3463b4 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 7 Mar 2016 14:50:01 -0500 Subject: [PATCH 157/412] Correct JSON syntax errors detected by validation Change-Id: Id6d8630829422aeecdb7160cc36d3d6508d06a1c --- Code/BasicFilters/json/LevelSetMotionRegistrationFilter.json | 2 +- Code/BasicFilters/json/MaskImageFilter.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/BasicFilters/json/LevelSetMotionRegistrationFilter.json b/Code/BasicFilters/json/LevelSetMotionRegistrationFilter.json index b0df0dace..5ec439307 100644 --- a/Code/BasicFilters/json/LevelSetMotionRegistrationFilter.json +++ b/Code/BasicFilters/json/LevelSetMotionRegistrationFilter.json @@ -9,7 +9,7 @@ "inputs" : [ { "name" : "FixedImage", - "type" : "Image" + "type" : "Image", "custom_itk_cast" : "filter->SetFixedImage( this->CastImageToITK(*inFixedImage) );" }, { diff --git a/Code/BasicFilters/json/MaskImageFilter.json b/Code/BasicFilters/json/MaskImageFilter.json index 9da1c67e2..e6dc14779 100644 --- a/Code/BasicFilters/json/MaskImageFilter.json +++ b/Code/BasicFilters/json/MaskImageFilter.json @@ -24,7 +24,7 @@ "name" : "OutsideValue", "type" : "double", "default" : 0, - "custom_itk_cast" : "typename OutputImageType::PixelType v; NumericTraits::SetLength( v, image1->GetNumberOfComponentsPerPixel() ); ToPixelType( this->m_OutsideValue, v ); filter->SetOutsideValue( v );" + "custom_itk_cast" : "typename OutputImageType::PixelType v; NumericTraits::SetLength( v, image1->GetNumberOfComponentsPerPixel() ); ToPixelType( this->m_OutsideValue, v ); filter->SetOutsideValue( v );", "briefdescriptionSet" : "", "detaileddescriptionSet" : "Method to explicitly set the outside value of the mask. Defaults to 0", "briefdescriptionGet" : "", From 97a4470fccd744c457ee5b9856110a602899a429 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 7 Mar 2016 14:57:46 -0500 Subject: [PATCH 158/412] Adding missing needed changes for JSON validation. Change-Id: I0ca7846c19bbada3341c79e9e27e60e7204a47b4 --- CMake/generate_filter_source.cmake | 7 +++++-- Utilities/Hooks/pre-commit | 10 ++++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/CMake/generate_filter_source.cmake b/CMake/generate_filter_source.cmake index 950185e71..47ebbbf61 100644 --- a/CMake/generate_filter_source.cmake +++ b/CMake/generate_filter_source.cmake @@ -111,12 +111,15 @@ macro( expand_template FILENAME input_dir output_dir library_name ) # Make a global list of ImageFilter template filters set ( IMAGE_FILTER_LIST ${IMAGE_FILTER_LIST} ${FILENAME} CACHE INTERNAL "" ) - # validate + # validate json files if python is available + if ( PYTHON_EXECUTABLE ) + set ( JSON_VALIDATE_COMMAND COMMAND "${PYTHON_EXECUTABLE}" "${SimpleITK_SOURCE_DIR}/Utilities/JSONValidate.py" "${input_json_file}" ) + endif () # header add_custom_command ( OUTPUT "${output_h}" - COMMAND ${PYTHON_EXECUTABLE} "${SimpleITK_SOURCE_DIR}/Utilities/JSONValidate.py" ${input_json_file} + ${JSON_VALIDATE_COMMAND} COMMAND ${CMAKE_COMMAND} -E remove -f ${output_h} COMMAND ${SITK_LUA_EXECUTABLE} ${expand_template_script} code ${input_json_file} ${input_dir}/templates/sitk ${template_include_dir} Template.h.in ${output_h} DEPENDS ${input_json_file} ${template_deps} ${template_file_h} diff --git a/Utilities/Hooks/pre-commit b/Utilities/Hooks/pre-commit index 03a51ce55..cf76db63b 100755 --- a/Utilities/Hooks/pre-commit +++ b/Utilities/Hooks/pre-commit @@ -87,9 +87,15 @@ if test -n "$json_files"; then python_exe=$(git config hooks.python || type -p python) && if test -z "$python_exe"; then die 'Cannont validate SimpleITK JSON files with out Python. -Configure Python's location with: +Configure the Python location with: - git config hooks.python + git config hooks.python "/path/to/python" + +It is NOT recommended to disable this check with: + + git config hooks.validatejson false +' + fi echo "$json_files" | while read src_mode dst_mode src_obj dst_obj status file; do if echo "$file" | egrep-q '\.json$'; then From b226bb09603fd1b9d77df094d608a2fe8ef2e021 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 24 Feb 2016 22:09:24 +0100 Subject: [PATCH 159/412] BUG: Fix JoinSeriesImageFilter GoogleTest should be fixture kaspermarstal/SimpleElastix#14 --- Testing/Unit/sitkImage4DTests.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Testing/Unit/sitkImage4DTests.cxx b/Testing/Unit/sitkImage4DTests.cxx index 7846dd7cc..37f48b2fd 100644 --- a/Testing/Unit/sitkImage4DTests.cxx +++ b/Testing/Unit/sitkImage4DTests.cxx @@ -230,7 +230,7 @@ TEST_F(Image4D,Constructors) { EXPECT_EQ( image.GetDirection(), directionI4D ); // Test the constructors for vector images - std::vector s4d(4, 5); + std::vector s4d(4, 5); image = itk::simple::Image( s4d, itk::simple::sitkVectorUInt8 ); EXPECT_EQ ( image.GetDimension(), 4u ); From 14a7d7b9b0410582f84b4d26653f7c12d0d413a8 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 8 Mar 2016 16:12:10 -0500 Subject: [PATCH 160/412] Adding initial description for MultiLableSTAPLEImageFilter TODO - Add ConfusionMatrix measurement, need to update ITK's method to be const - Add method to set PrioProbabilities - Test order of labels to see if filter can handle non-sequential labels Change-Id: I42464b5393362df7c924b464b4a9e5ef75898050 --- .../json/MultiLabelSTAPLEImageFilter.json | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json diff --git a/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json b/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json new file mode 100644 index 000000000..29370f7ff --- /dev/null +++ b/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json @@ -0,0 +1,51 @@ +{ + "name" : "MultiLabelSTAPLEImageFilter", + "template_code_filename" : "MultiInputImageFilter", + "template_test_filename" : "ImageFilter", + "number_of_inputs" : 1, + "pixel_types" : "UnsignedIntegerPixelIDTypeList", + "filter_type" : "itk::MultiLabelSTAPLEImageFilter", + "members" : [ + { + "name" : "LabelForUndecidedPixels", + "type" : "uint64_t", + "default" : "std::numeric_limits::max()", + "pixeltype" : "Output", + "custom_itk_cast" : "if (m_LabelForUndecidedPixels!=std::numeric_limits::max()) filter->SetLabelForUndecidedPixels(this->m_LabelForUndecidedPixels);", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set label value for undecided pixels.", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Get label value used for undecided pixels. After updating the filter, this function returns the actual label value used for undecided pixels in the current output. Note that this value is overwritten when SetLabelForUndecidedPixels is called and the new value only becomes effective upon the next filter update." + }, + { + "name" : "MaximumNumberOfIterations", + "type" : "unsigned int", + "default" : "std::numeric_limits::max()", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set maximum number of iterations.", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Set/Get the maximum number of iterations after which the STAPLE algorithm will be considered to have converged. In general this SHOULD NOT be set and the algorithm should be allowed to converge on its own." + }, + { + "name" : "TerminationUpdateThreshold", + "type" : "float", + "default" : "1e-5", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set termination threshold based on confusion matrix parameter updates." + } + ], + "measurements" : [], + "tests" : [ + { + "tag" : "basic", + "description" : "Basic usage", + "tolerance" : "1e-5", + "inputs" : [ + "Input/STAPLE1-binary.png", + "Input/STAPLE2-binary.png" + ] + } + ], + "briefdescription" : "This filter performs a pixelwise combination of an arbitrary number of input images, where each of them represents a segmentation of the same scene (i.e., image).", + "detaileddescription" : "The labelings in the images are weighted relative to each other based on their \"performance\" as estimated by an expectation-maximization algorithm. In the process, a ground truth segmentation is estimated, and the estimated performances of the individual segmentations are relative to this estimated ground truth.\n\nThe algorithm is based on the binary STAPLE algorithm by Warfield et al. as published originally in\n\nS. Warfield, K. Zou, W. Wells, \"Validation of image segmentation and expert\nquality with an expectation-maximization algorithm\" in MICCAI 2002: Fifth International Conference on Medical Image Computing and Computer-Assisted Intervention, Springer-Verlag, Heidelberg, Germany, 2002, pp. 298-306\n\nThe multi-label algorithm implemented here is described in detail in\n\nT. Rohlfing, D. B. Russakoff, and C. R. Maurer, Jr., \"Performance-based classifier combination in atlas-based image segmentation using expectation-maximization parameter estimation,\" IEEE Transactions on Medical Imaging, vol. 23, pp. 983-994, Aug. 2004.\n\n\\par INPUTS\nAll input volumes to this filter must be segmentations of an image, that is, they must have discrete pixel values where each value represents a different segmented object.\n\nInput volumes must all contain the same size RequestedRegions. Not all input images must contain all possible labels, but all label values must have the same meaning in all images.\n\nThe filter can optionally be provided with estimates for the a priori class probabilities through the SetPriorProbabilities function. If no estimate is provided, one is automatically generated by analyzing the relative frequencies of the labels in the input images.\n\n\\par OUTPUTS\nThe filter produces a single output volume. Each output pixel contains the label that has the highest probability of being the correct label, based on the performance models of the individual segmentations. If the maximum probaility is not unique, i.e., if more than one label have a maximum probability, then an \"undecided\" label is assigned to that output pixel.\n\nBy default, the label used for undecided pixels is the maximum label value used in the input images plus one. Since it is possible for an image with 8 bit pixel values to use all 256 possible label values, it is permissible to combine 8 bit (i.e., byte) images into a 16 bit (i.e., short) output image.\n\nIn addition to the combined image, the estimated confusion matrices for each of the input segmentations can be obtained through the GetConfusionMatrix member function.\n\n\\par PARAMETERS\nThe label used for \"undecided\" labels can be set using SetLabelForUndecidedPixels. This functionality can be unset by calling UnsetLabelForUndecidedPixels.\n\nA termination threshold for the EM iteration can be defined by calling SetTerminationUpdateThreshold. The iteration terminates once no single parameter of any confusion matrix changes by less than this threshold. Alternatively, a maximum number of iterations can be specified by calling SetMaximumNumberOfIterations. The algorithm may still terminate after a smaller number of iterations if the termination threshold criterion is satisfied.\n\n\\par EVENTS\nThis filter invokes IterationEvent() at each iteration of the E-M algorithm. Setting the AbortGenerateData() flag will cause the algorithm to halt after the current iteration and produce results just as if it had converged. The algorithm makes no attempt to report its progress since the number of iterations needed cannot be known in advance.\n\n\\author Torsten Rohlfing, SRI International, Neuroscience Program" +} From bc5ebfc864a9cba1d7c754ba954dba4ee92ecf54 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 9 Mar 2016 10:20:08 -0500 Subject: [PATCH 161/412] In Python use open over file The file constructor has been removed in Python 3, open is required. Change-Id: I623814a2ed3c5b0c3608d4944c19f5c8f32420e2 --- Utilities/Hooks/pre-commit | 2 +- Utilities/JSONValidate.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Utilities/Hooks/pre-commit b/Utilities/Hooks/pre-commit index cf76db63b..a7b910da0 100755 --- a/Utilities/Hooks/pre-commit +++ b/Utilities/Hooks/pre-commit @@ -76,7 +76,7 @@ validate_json() { if test -n "$changes"; then die "Cannot validate '$1' with work tree changes." fi && - out=$($python_exe -c "import sys, json; json.load( file( sys.argv[1], 'r' ) )" "$1" 2>&1) || die "JSON Validation error with \"$file\". + out=$($python_exe -c "import sys, json; json.load( open( sys.argv[1], 'r' ) )" "$1" 2>&1) || die "JSON Validation error with \"$file\". $out" } diff --git a/Utilities/JSONValidate.py b/Utilities/JSONValidate.py index 730383103..c7d200071 100755 --- a/Utilities/JSONValidate.py +++ b/Utilities/JSONValidate.py @@ -3,7 +3,7 @@ import json, sys try: - json.load( file( sys.argv[1], "r" )) + json.load( open( sys.argv[1], "r" )) except ValueError as e: print( "ValueError: {0}".format( e ) ) print( "{0}:0:0: error: validating json file.".format( sys.argv[1] ) ) From 1611b317f82dd4ef45fad6f09bd22cfa8ac7fa4f Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 10 Mar 2016 15:29:53 -0500 Subject: [PATCH 162/412] Improving order and utilizing default magic values for "unset" state. Change-Id: Icdd211bd1c3ddd267d89f601a887cddc7927f11a --- .../json/MultiLabelSTAPLEImageFilter.json | 28 +++++++++++++------ 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json b/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json index 29370f7ff..2c3423311 100644 --- a/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json +++ b/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json @@ -17,29 +17,39 @@ "briefdescriptionGet" : "", "detaileddescriptionGet" : "Get label value used for undecided pixels. After updating the filter, this function returns the actual label value used for undecided pixels in the current output. Note that this value is overwritten when SetLabelForUndecidedPixels is called and the new value only becomes effective upon the next filter update." }, + { + "name" : "TerminationUpdateThreshold", + "type" : "float", + "default" : "1e-5f", + "briefdescriptionSet" : "", + "detaileddescriptionSet" : "Set termination threshold based on confusion matrix parameter updates." + }, { "name" : "MaximumNumberOfIterations", "type" : "unsigned int", "default" : "std::numeric_limits::max()", + "custom_itk_cast" : "if (m_MaximumNumberOfIterations!=std::numeric_limits::max()) filter->SetMaximumNumberOfIterations(this->m_MaximumNumberOfIterations);", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set maximum number of iterations.", - "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Set/Get the maximum number of iterations after which the STAPLE algorithm will be considered to have converged. In general this SHOULD NOT be set and the algorithm should be allowed to converge on its own." + "detaileddescriptionSet" : "Set maximum number of iterations." }, { - "name" : "TerminationUpdateThreshold", - "type" : "float", - "default" : "1e-5", + "name" : "PriorProbabilities", + "type" : "std::vector", + "default" : "std::vector()", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set termination threshold based on confusion matrix parameter updates." + "custom_itk_cast" : "if (!m_PriorProbabilities.empty()) filter->SetPriorProbabilities(typename FilterType::PriorProbabilitiesType(&this->m_PriorProbabilities[0],this->m_PriorProbabilities.size()));", + "detaileddescriptionSet" : "Set label value for undecided pixels.", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Get prior class probabilities. After updating the filter, this function returns the actual prior class probabilities. If these were not previously set by a call to SetPriorProbabilities, then they are estimated from the input segmentations and the result is available through this function." } ], - "measurements" : [], + "measurements" : [ + ], "tests" : [ { "tag" : "basic", "description" : "Basic usage", - "tolerance" : "1e-5", + "md5hash" : "77ac8604a252c5130602645a5f02cc36", "inputs" : [ "Input/STAPLE1-binary.png", "Input/STAPLE2-binary.png" From e713dd6193abb1a52f136831b8c7b9ce6df0a45b Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 11 Mar 2016 15:48:14 -0500 Subject: [PATCH 163/412] Adding test to verify that the input and output buffers are different Change-Id: I7e2c7eb23327852c7ffad509bd22029178de9321 --- .../Unit/sitkImageFilterTestTemplate.cxx.in | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in index 5688e7caa..951655f1c 100644 --- a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in +++ b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in @@ -28,8 +28,75 @@ #include #include #include +#include #include +namespace { +void * GetBufferAsVoid( itk::simple::Image &sitkImage) +{ + + namespace sitk = itk::simple; + void *sitkBufferPtr = NULL; + + switch( sitkImage.GetPixelIDValue() ) + { + case sitk::sitkUnknown: + break; + case sitk::ConditionalValue< sitk::sitkVectorUInt8 != sitk::sitkUnknown, sitk::sitkVectorUInt8, -14 >::Value: + case sitk::ConditionalValue< sitk::sitkUInt8 != sitk::sitkUnknown, sitk::sitkUInt8, -2 >::Value: + sitkBufferPtr = (void *)sitkImage.GetBufferAsUInt8(); + break; + case sitk::ConditionalValue< sitk::sitkVectorInt8 != sitk::sitkUnknown, sitk::sitkVectorInt8, -15 >::Value: + case sitk::ConditionalValue< sitk::sitkInt8 != sitk::sitkUnknown, sitk::sitkInt8, -3 >::Value: + sitkBufferPtr = (void *)sitkImage.GetBufferAsInt8(); + break; + case sitk::ConditionalValue< sitk::sitkVectorUInt16 != sitk::sitkUnknown, sitk::sitkVectorUInt16, -16 >::Value: + case sitk::ConditionalValue< sitk::sitkUInt16 != sitk::sitkUnknown, sitk::sitkUInt16, -4 >::Value: + sitkBufferPtr = (void *)sitkImage.GetBufferAsUInt16(); + break; + case sitk::ConditionalValue< sitk::sitkVectorInt16 != sitk::sitkUnknown, sitk::sitkVectorInt16, -17 >::Value: + case sitk::ConditionalValue< sitk::sitkInt16 != sitk::sitkUnknown, sitk::sitkInt16, -5 >::Value: + sitkBufferPtr = (void *)sitkImage.GetBufferAsInt16(); + break; + case sitk::ConditionalValue< sitk::sitkVectorUInt32 != sitk::sitkUnknown, sitk::sitkVectorUInt32, -18 >::Value: + case sitk::ConditionalValue< sitk::sitkUInt32 != sitk::sitkUnknown, sitk::sitkUInt32, -6 >::Value: + sitkBufferPtr = (void *)sitkImage.GetBufferAsUInt32(); + break; + case sitk::ConditionalValue< sitk::sitkVectorInt32 != sitk::sitkUnknown, sitk::sitkVectorInt32, -19 >::Value: + case sitk::ConditionalValue< sitk::sitkInt32 != sitk::sitkUnknown, sitk::sitkInt32, -7 >::Value: + sitkBufferPtr = (void *)sitkImage.GetBufferAsInt32(); + break; + case sitk::ConditionalValue< sitk::sitkVectorUInt64 != sitk::sitkUnknown, sitk::sitkVectorUInt64, -20 >::Value: + case sitk::ConditionalValue< sitk::sitkUInt64 != sitk::sitkUnknown, sitk::sitkUInt64, -8 >::Value: + sitkBufferPtr = (void *)sitkImage.GetBufferAsUInt64(); + break; + case sitk::ConditionalValue< sitk::sitkVectorInt64 != sitk::sitkUnknown, sitk::sitkVectorInt64, -21 >::Value: + case sitk::ConditionalValue< sitk::sitkInt64 != sitk::sitkUnknown, sitk::sitkInt64, -9 >::Value: + sitkBufferPtr = (void *)sitkImage.GetBufferAsInt64(); + break; + case sitk::ConditionalValue< sitk::sitkVectorFloat32 != sitk::sitkUnknown, sitk::sitkVectorFloat32, -22 >::Value: + case sitk::ConditionalValue< sitk::sitkFloat32 != sitk::sitkUnknown, sitk::sitkFloat32, -10 >::Value: + sitkBufferPtr = (void *)sitkImage.GetBufferAsFloat(); + break; + case sitk::ConditionalValue< sitk::sitkVectorFloat64 != sitk::sitkUnknown, sitk::sitkVectorFloat64, -23 >::Value: + case sitk::ConditionalValue< sitk::sitkFloat64 != sitk::sitkUnknown, sitk::sitkFloat64, -11 >::Value: + sitkBufferPtr = (void *)sitkImage.GetBufferAsDouble(); + break; + case sitk::ConditionalValue< sitk::sitkComplexFloat32 != sitk::sitkUnknown, sitk::sitkComplexFloat32, -12 >::Value: + //sitkBufferPtr = (void *)sitkImage.GetBufferAsComplexFloat32(); + break; + case sitk::ConditionalValue< sitk::sitkComplexFloat64 != sitk::sitkUnknown, sitk::sitkComplexFloat64, -13 >::Value: + //sitkBufferPtr = (void *)sitkImage.GetBufferAsComplexFloat64(); + break; + break; + default: + ; + } + return sitkBufferPtr; +} + +} + TEST(BasicFilters,${name}) { itk::simple::ImageFileReader reader; @@ -285,6 +352,13 @@ end) // Check that the input is not modified // This will fail if the filter is being run in-place EXPECT_EQ ( inputSHA1hash, itk::simple::Hash( inputs[0] ) ) << "Input was modified by filter."; + + // Check that the input buffer is different that the output + // buffer, this does not check complex or label map pixel types. + if (GetBufferAsVoid(output) != SITK_NULLPTR && GetBufferAsVoid(inputs[0]) != SITK_NULLPTR) + { + EXPECT_NE(GetBufferAsVoid(output), GetBufferAsVoid(inputs[0]) ) << "Input buffer was copyied to output!"; + } } $(if md5hash then From e700e31a99cb6c824c442fd5d1eda856c19f4b04 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 11 Mar 2016 15:49:08 -0500 Subject: [PATCH 164/412] Removing procedural methods for filters with not image output. After adding the prior test, several filters just copy the input image buffer's to the output. This creates alias problem with SimpleITK's image. These filter's procedural methods are now removed, and a blank image is returned. In future version the Execute method may return void or tuples of results. Change-Id: Ie29ffb309899befdfb8f84c1702da3dbcf65ff82 --- Code/BasicFilters/json/BitwiseNotImageFilter.json | 1 - Code/BasicFilters/json/HausdorffDistanceImageFilter.json | 2 ++ Code/BasicFilters/json/LabelOverlapMeasuresImageFilter.json | 2 ++ Code/BasicFilters/json/MinimumMaximumImageFilter.json | 2 ++ Code/BasicFilters/json/SimilarityIndexImageFilter.json | 2 ++ 5 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Code/BasicFilters/json/BitwiseNotImageFilter.json b/Code/BasicFilters/json/BitwiseNotImageFilter.json index 3aec8dfce..31bc1735e 100644 --- a/Code/BasicFilters/json/BitwiseNotImageFilter.json +++ b/Code/BasicFilters/json/BitwiseNotImageFilter.json @@ -3,7 +3,6 @@ "itk_name" : "UnaryFunctorImageFilter", "template_code_filename" : "ImageFilter", "template_test_filename" : "ImageFilter", - "constant_type" : "double", "include_files" : [ "itkBitwiseNotFunctor.h" ], diff --git a/Code/BasicFilters/json/HausdorffDistanceImageFilter.json b/Code/BasicFilters/json/HausdorffDistanceImageFilter.json index c91eff0d3..aab617b44 100644 --- a/Code/BasicFilters/json/HausdorffDistanceImageFilter.json +++ b/Code/BasicFilters/json/HausdorffDistanceImageFilter.json @@ -7,6 +7,8 @@ "pixel_types" : "BasicPixelIDTypeList", "pixel_types2" : "BasicPixelIDTypeList", "filter_type" : "itk::HausdorffDistanceImageFilter", + "no_procedure" : true, + "no_return_image" : true, "members" : [], "measurements" : [ { diff --git a/Code/BasicFilters/json/LabelOverlapMeasuresImageFilter.json b/Code/BasicFilters/json/LabelOverlapMeasuresImageFilter.json index 3fadd9002..c661eec5b 100644 --- a/Code/BasicFilters/json/LabelOverlapMeasuresImageFilter.json +++ b/Code/BasicFilters/json/LabelOverlapMeasuresImageFilter.json @@ -5,6 +5,8 @@ "number_of_inputs" : 2, "pixel_types" : "IntegerPixelIDTypeList", "filter_type" : "itk::LabelOverlapMeasuresImageFilter", + "no_procedure" : true, + "no_return_image" : true, "members" : [], "measurements" : [ { diff --git a/Code/BasicFilters/json/MinimumMaximumImageFilter.json b/Code/BasicFilters/json/MinimumMaximumImageFilter.json index c7feb9c3c..44f8024db 100644 --- a/Code/BasicFilters/json/MinimumMaximumImageFilter.json +++ b/Code/BasicFilters/json/MinimumMaximumImageFilter.json @@ -5,6 +5,8 @@ "number_of_inputs" : 1, "pixel_types" : "BasicPixelIDTypeList", "filter_type" : "itk::MinimumMaximumImageFilter", + "no_procedure" : true, + "no_return_image" : true, "members" : [], "measurements" : [ { diff --git a/Code/BasicFilters/json/SimilarityIndexImageFilter.json b/Code/BasicFilters/json/SimilarityIndexImageFilter.json index dc7b0462e..23f030c86 100644 --- a/Code/BasicFilters/json/SimilarityIndexImageFilter.json +++ b/Code/BasicFilters/json/SimilarityIndexImageFilter.json @@ -6,6 +6,8 @@ "doc" : "Some global documentation", "pixel_types" : "BasicPixelIDTypeList", "filter_type" : "itk::SimilarityIndexImageFilter", + "no_procedure" : true, + "no_return_image" : true, "members" : [], "measurements" : [ { From cd29710241737676167a2f2e8fa62fa5d4305425 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 14 Mar 2016 15:16:22 -0400 Subject: [PATCH 165/412] Add Python support for Get/SetPixel for tuple arguments The C++ Get/SetPixelAs? methods take a std::vector as an argument, this an analogous to using a tuple or array in Python. This enables the return of GetIndexFromPysicalPoint to be used in the GetPixel methods. Change-Id: Ie75caedaaaae97feaabfd9ae9506810835acfb60 --- Testing/Unit/sitkImageTests.py | 7 ++++--- Wrapping/Python/Python.i | 4 ++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/Testing/Unit/sitkImageTests.py b/Testing/Unit/sitkImageTests.py index 95612b0ab..115c453e5 100644 --- a/Testing/Unit/sitkImageTests.py +++ b/Testing/Unit/sitkImageTests.py @@ -67,13 +67,14 @@ def test_legacy(self): image.SetPixel( 0, 0, 1 ) image[ [0,1] ] = 2 image[ 9,9 ] = 3 + image.SetPixel( [0, 2], 4 ) - image.GetPixel( 1,1 ) - #image.GetPixel( [1,1] ) + self.assertEqual(image.GetPixel(1,1), 0 ) + self.assertEqual(image.GetPixel([0,2]), 4 ) image[1,1] image[ [ 1,1 ] ] - self.assertEqual(sum( image ), 6) + self.assertEqual(sum( image ), 10) self.assertEqual(len( image ), 100) diff --git a/Wrapping/Python/Python.i b/Wrapping/Python/Python.i index b374449c5..839e3c3b5 100644 --- a/Wrapping/Python/Python.i +++ b/Wrapping/Python/Python.i @@ -468,6 +468,8 @@ This method takes 2 parameters in 2D: the x and y index, and 3 parameters in 3D: the x, y and z index.""" + if len(idx) == 1: + idx = idx[0] pixelID = self.GetPixelIDValue() if pixelID == sitkUnknown: @@ -535,6 +537,8 @@ if len(args) < 2: raise Exception( "Wrong number of arguments, coordinates arguments then value" ) idx = args[:len(args)-1] + if len(idx) == 1: + idx = idx[0] value = args[-1] if pixelID == sitkInt8: From 803e56087ffb15d3ac1c37e95cc9225e1a40b1a4 Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Tue, 15 Mar 2016 14:08:25 +1100 Subject: [PATCH 166/412] SimpleITK methods returning void are returning NULL when called from R, and the NULL gets printed, which is annoying. This patch forces the NULL to be returned invisibly, and thus not printed by default. --- Wrapping/R/R.i | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Wrapping/R/R.i b/Wrapping/R/R.i index 632707a2c..32745acdb 100644 --- a/Wrapping/R/R.i +++ b/Wrapping/R/R.i @@ -32,6 +32,13 @@ std::vector, std::vector *, std::vector & %{ %} +// stop printing "NULL" when calling a method +// returning void +%typemap(scoerceout) void +%{ + return(invisible($result)) +%} + // some important enumerations don't get evaluate properly. This is a // hack to fix the problem. %inline From 5d7b80397028af6f93dcb74c67fd93ced26176bf Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 15 Mar 2016 15:46:48 -0400 Subject: [PATCH 167/412] Adding support for CMake STRINGS property to superbuild variables. Change-Id: I2e2afae869965ecd46622d91be831d96e7cb0b5d --- CMake/VariableList.cmake | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/CMake/VariableList.cmake b/CMake/VariableList.cmake index 2c7505978..06db4b186 100644 --- a/CMake/VariableList.cmake +++ b/CMake/VariableList.cmake @@ -12,6 +12,7 @@ function( VariableListToCache var_list cache ) get_property( type CACHE ${var} PROPERTY TYPE ) get_property( advanced CACHE ${var} PROPERTY ADVANCED ) get_property( helpstring CACHE ${var} PROPERTY HELPSTRING ) + get_property( strings CACHE ${var} PROPERTY STRINGS ) # apply escape sequences foreach( e "\\" "(" ")" "#" "$" "^" "@" ) @@ -23,10 +24,16 @@ function( VariableListToCache var_list cache ) endif() set( _cache "${_cache} -set( ${var} \"${value}\" CACHE \"${type}\" \"${helpstring}\" FORCE ) -if( ${advanced} ) - mark_as_advanced( ${var} ) -endif()" ) +set( ${var} \"${value}\" CACHE \"${type}\" \"${helpstring}\" FORCE )") + + if( "${advanced}" ) + set( _cache "${_cache} + mark_as_advanced( ${var} )") + endif() + if( NOT "${strings}" STREQUAL "" ) + set( _cache "${_cache} + set_property(CACHE ${var} PROPERTY STRINGS \"${strings}\")") + endif() endif() endforeach() set( ${cache} "${_cache}" PARENT_SCOPE) From aa5b446f57034306a2d7b9cf91366cab59b34e9a Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Thu, 10 Mar 2016 09:53:28 -0500 Subject: [PATCH 168/412] ENH: Added debugging message option to Show Added a boolean parameter, debugOn, to the Show function that will print out debugging messages. When enabled, show will print to stdout 3 things: the search path used to find ImageJ, the full path to ImageJ, and the full command used to invoke ImageJ. Also the sitkShowTest enables these messages for the third call to Show. Change-Id: I8128196713f826edc1f93532e506f356723abf38 --- Code/IO/include/sitkShow.h | 7 ++++- Code/IO/src/sitkShow.cxx | 54 +++++++++++++++++++---------------- Testing/Unit/sitkShowTest.cxx | 2 +- 3 files changed, 37 insertions(+), 26 deletions(-) diff --git a/Code/IO/include/sitkShow.h b/Code/IO/include/sitkShow.h index 84a75a675..001100eac 100644 --- a/Code/IO/include/sitkShow.h +++ b/Code/IO/include/sitkShow.h @@ -81,15 +81,20 @@ namespace simple * appended to the command argument list. * * + * When invoked, Show searches for Fiji first, and then ImageJ. Fiji is the most update-to-date + * version of ImageJ and includes a lot of plugins which facilitate scientific image analysis. * By default, for a 64-bit build of SimpleITK on Macs, sitkShow searches for ImageJ64.app. * For a 32-bit Mac build, sitkShow searches for ImageJ.app. If the user prefers a different * version of ImageJ (or a different image viewer altogether), it can be specified using * the SITK_SHOW_COMMAND environment variable. * + * The boolean parameter debugOn prints the search path Show uses to find ImageJ, the full path + * to the ImageJ it found, and the full command line used to invoke ImageJ. + * **/ - void SITKIO_EXPORT Show ( const Image &image, const std::string title = "" ); + void SITKIO_EXPORT Show ( const Image &image, const std::string& title = "", const bool debugOn=false ); } } diff --git a/Code/IO/src/sitkShow.cxx b/Code/IO/src/sitkShow.cxx index c5426b330..0e5cde283 100644 --- a/Code/IO/src/sitkShow.cxx +++ b/Code/IO/src/sitkShow.cxx @@ -351,7 +351,7 @@ namespace itk // // - static std::string FindApplication(const std::string directory = "", const std::string name = "" ) + static std::string FindApplication(const std::string directory = "", const std::string name = "", const bool debugOn=false ) { std::vector paths; @@ -388,11 +388,7 @@ namespace itk paths.push_back( "/opt/" + directory ); paths.push_back( "/usr/local/" + directory ); -#ifndef NDEBUG - std::cout << paths << std::endl; ExecutableName = itksys::SystemTools::FindDirectory( name.c_str(), paths ); - std::cout << "Result: " << ExecutableName << std::endl; -#endif #else @@ -403,6 +399,12 @@ namespace itk #endif + if (debugOn) + { + std::cout << "FindApplication search path: " << paths << std::endl; + std::cout << "Result: " << ExecutableName << std::endl; + } + return ExecutableName; } @@ -412,17 +414,21 @@ namespace itk * process based on it. It waits for a fraction of a second before * checking it's state, to verify it was launched OK. */ - static void ExecuteShow( const std::vector & cmdLine ) + static void ExecuteShow( const std::vector & cmdLine, const bool debugOn=false ) { + unsigned int i; -#ifndef NDEBUG - std::copy( cmdLine.begin(), cmdLine.end(), std::ostream_iterator( std::cout, "\n" ) ); - std::cout << std::endl; -#endif + if (debugOn) + { + std::cout << "Show command: "; + for ( i = 0; i < cmdLine.size(); ++i ) + std::cout << '\'' << cmdLine[i] << "\' "; + std::cout << std::endl; + } std::vector cmd( cmdLine.size() + 1, NULL ); - for ( unsigned int i = 0; i < cmdLine.size(); ++i ) + for ( i = 0; i < cmdLine.size(); ++i ) { cmd[i] = cmdLine[i].c_str(); } @@ -500,7 +506,7 @@ namespace itk } - void Show( const Image &image, const std::string title) + void Show( const Image &image, const std::string& title, const bool debugOn) { // Try to find ImageJ, write out a file and open std::string ExecutableName; @@ -528,47 +534,47 @@ namespace itk #if defined(_WIN32) // Windows - ExecutableName = FindApplication("Fiji.app", "ImageJ-win64.exe"); + ExecutableName = FindApplication( "Fiji.app", "ImageJ-win64.exe", debugOn ); if (!ExecutableName.length()) { - ExecutableName = FindApplication("Fiji.app", "ImageJ-win32.exe"); + ExecutableName = FindApplication( "Fiji.app", "ImageJ-win32.exe", debugOn ); } if (!ExecutableName.length()) { - ExecutableName = FindApplication("ImageJ", "ImageJ.exe"); + ExecutableName = FindApplication( "ImageJ", "ImageJ.exe", debugOn ); } #elif defined(__APPLE__) - ExecutableName = FindApplication("", "Fiji.app"); + ExecutableName = FindApplication( "", "Fiji.app", debugOn ); if (!ExecutableName.length()) { - ExecutableName = FindApplication( "ImageJ", "ImageJ64.app" ); + ExecutableName = FindApplication( "ImageJ", "ImageJ64.app", debugOn ); } if (!ExecutableName.length()) { - ExecutableName = FindApplication( "ImageJ", "ImageJ.app" ); + ExecutableName = FindApplication( "ImageJ", "ImageJ.app", debugOn ); } #else // Linux and other systems - ExecutableName = FindApplication("Fiji.app", "ImageJ-linux64"); + ExecutableName = FindApplication( "Fiji.app", "ImageJ-linux64", debugOn ); if (!ExecutableName.length()) { - ExecutableName = FindApplication("Fiji.app", "ImageJ-linux32"); + ExecutableName = FindApplication( "Fiji.app", "ImageJ-linux32", debugOn ); } if (!ExecutableName.length()) { - ExecutableName = FindApplication("ImageJ", "imagej"); + ExecutableName = FindApplication( "ImageJ", "imagej", debugOn ); } if (!ExecutableName.length()) { - ExecutableName = FindApplication("imagej"); + ExecutableName = FindApplication( "", "imagej", debugOn ); } #endif - bool fijiFlag = ExecutableName.find("Fiji.app") != std::string::npos; + bool fijiFlag = ExecutableName.find( "Fiji.app" ) != std::string::npos; TempFile = BuildFullFileName(title, fijiFlag); //std::cout << "Full file name:\t" << TempFile << std::endl; @@ -629,7 +635,7 @@ namespace itk CommandLine = ConvertCommand(Command, ExecutableName, TempFile, title); // run the compiled command-line in a process which will detach - ExecuteShow( CommandLine ); + ExecuteShow( CommandLine, debugOn ); } } // namespace simple diff --git a/Testing/Unit/sitkShowTest.cxx b/Testing/Unit/sitkShowTest.cxx index 69ec4d2f1..13922137d 100644 --- a/Testing/Unit/sitkShowTest.cxx +++ b/Testing/Unit/sitkShowTest.cxx @@ -93,7 +93,7 @@ int main (int argc, char *argv[]) std::cout << "Read 3\n"; img = sitk::ReadImage( dataFinder.GetFile ( "Input/cthead1-Float.mha" ) ); std::cout << "Show 3\n"; - sitk::Show(img, "Dave was here"); + sitk::Show(img, "Dave was here", true); } catch (std::exception &e) { From 00e25d709ef2136d564f41b00bf58c5fa9fbced4 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 16 Mar 2016 15:00:25 -0400 Subject: [PATCH 169/412] Fixing unused typedef reported by clang Removing them in manual code, and then suppressing the warning with the generated code. Change-Id: I81dccfbbbda167e6e2a265337d60e24a02f5f7b1 --- .../src/sitkBSplineTransformInitializerFilter.cxx | 3 --- Code/BasicFilters/src/sitkCastImageFilter.hxx | 3 --- .../templates/sitkKernelImageFilterTemplate.cxx.in | 5 +++++ .../templates/sitkMultiInputImageFilterTemplate.cxx.in | 7 +++++++ Code/IO/src/sitkImportImageFilter.cxx | 1 - Code/Registration/src/sitkImageRegistrationMethod.cxx | 4 ++-- 6 files changed, 14 insertions(+), 9 deletions(-) diff --git a/Code/BasicFilters/src/sitkBSplineTransformInitializerFilter.cxx b/Code/BasicFilters/src/sitkBSplineTransformInitializerFilter.cxx index f8c11e199..88f37ee4c 100644 --- a/Code/BasicFilters/src/sitkBSplineTransformInitializerFilter.cxx +++ b/Code/BasicFilters/src/sitkBSplineTransformInitializerFilter.cxx @@ -150,9 +150,6 @@ BSplineTransform BSplineTransformInitializerFilter::ExecuteInternalWithOrder ( // Define the input and output image types typedef itk::ImageBase InputImageType; - //Define output image type - typedef float OutputImageType; - // Get the pointer to the ITK image contained in image1 typename InputImageType::ConstPointer image1 = this->CastImageToITK( inImage1 ); diff --git a/Code/BasicFilters/src/sitkCastImageFilter.hxx b/Code/BasicFilters/src/sitkCastImageFilter.hxx index 94ea4bfdf..61e577125 100644 --- a/Code/BasicFilters/src/sitkCastImageFilter.hxx +++ b/Code/BasicFilters/src/sitkCastImageFilter.hxx @@ -96,10 +96,7 @@ Image CastImageFilter::ExecuteInternalToLabel( const Image& inImage ) { typedef TImageType InputImageType; typedef TOutputImageType OutputImageType; - typedef typename OutputImageType::LabelObjectType LabelObjectType; - typedef typename LabelObjectType::LabelType LabelType; - typedef itk::Image LabelImageType; typename InputImageType::ConstPointer image = this->CastImageToITK( inImage ); diff --git a/Code/BasicFilters/templates/sitkKernelImageFilterTemplate.cxx.in b/Code/BasicFilters/templates/sitkKernelImageFilterTemplate.cxx.in index 44a8ddfa4..a9c44b2c1 100644 --- a/Code/BasicFilters/templates/sitkKernelImageFilterTemplate.cxx.in +++ b/Code/BasicFilters/templates/sitkKernelImageFilterTemplate.cxx.in @@ -112,6 +112,9 @@ $(include CustomCasts.cxx) //---------------------------------------------------------------------------- +sitkClangDiagnosticPush(); +sitkClangWarningIgnore("-Wunused-local-typedef"); + // // ExecuteInternal // @@ -135,6 +138,8 @@ $(include ExecuteInternalUpdateAndReturn.cxx.in) } +sitkClangDiagnosticPop(); + //----------------------------------------------------------------------------- diff --git a/Code/BasicFilters/templates/sitkMultiInputImageFilterTemplate.cxx.in b/Code/BasicFilters/templates/sitkMultiInputImageFilterTemplate.cxx.in index 142b54165..320786ee6 100644 --- a/Code/BasicFilters/templates/sitkMultiInputImageFilterTemplate.cxx.in +++ b/Code/BasicFilters/templates/sitkMultiInputImageFilterTemplate.cxx.in @@ -145,6 +145,11 @@ $(include CustomCasts.cxx) //----------------------------------------------------------------------------- + +sitkClangDiagnosticPush(); +sitkClangWarningIgnore("-Wunused-local-typedef"); + + // // ExecuteInternal // @@ -169,6 +174,8 @@ $(include ExecuteInternalSetITKFilterParameters.cxx.in) $(include ExecuteInternalUpdateAndReturn.cxx.in) } +sitkClangDiagnosticPop(); + // // Function to run the Execute method of this filter // diff --git a/Code/IO/src/sitkImportImageFilter.cxx b/Code/IO/src/sitkImportImageFilter.cxx index e84583492..a4f99b84b 100644 --- a/Code/IO/src/sitkImportImageFilter.cxx +++ b/Code/IO/src/sitkImportImageFilter.cxx @@ -463,7 +463,6 @@ Image ImportImageFilter::ExecuteInternal( ) { typedef TImageType ImageType; - typedef typename ImageType::InternalPixelType PixelType; const unsigned int Dimension = ImageType::ImageDimension; // if the InstantiatedToken is correctly implemented this should diff --git a/Code/Registration/src/sitkImageRegistrationMethod.cxx b/Code/Registration/src/sitkImageRegistrationMethod.cxx index cdc546123..3eb583892 100644 --- a/Code/Registration/src/sitkImageRegistrationMethod.cxx +++ b/Code/Registration/src/sitkImageRegistrationMethod.cxx @@ -631,7 +631,7 @@ Transform ImageRegistrationMethod::ExecuteInternal ( const Image &inFixed, const typedef TImageType FixedImageType; typedef TImageType MovingImageType; const unsigned int ImageDimension = FixedImageType::ImageDimension; - typedef itk::SpatialObject SpatialObjectMaskType; + //typedef itk::SpatialObject SpatialObjectMaskType; typedef itk::ImageRegistrationMethodv4 RegistrationType; @@ -871,7 +871,7 @@ double ImageRegistrationMethod::EvaluateInternal ( const Image &inFixed, const I typedef TImageType FixedImageType; typedef TImageType MovingImageType; const unsigned int ImageDimension = FixedImageType::ImageDimension; - typedef itk::SpatialObject SpatialObjectMaskType; + //typedef itk::SpatialObject SpatialObjectMaskType; typedef itk::ImageRegistrationMethodv4 RegistrationType; From 618ca4454f0fabce142852366fc01a2f12b5e81b Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 17 Mar 2016 14:26:36 -0400 Subject: [PATCH 170/412] Updating virtualenv version to 15.0.1 Change-Id: Ia3d6b9997421fcf196708ba7a11a968311ab6d49 --- SuperBuild/External_virtualenv.cmake | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SuperBuild/External_virtualenv.cmake b/SuperBuild/External_virtualenv.cmake index 2aa580b2d..c103ed327 100644 --- a/SuperBuild/External_virtualenv.cmake +++ b/SuperBuild/External_virtualenv.cmake @@ -7,8 +7,8 @@ set(${CMAKE_CURRENT_LIST_FILENAME}_FILE_INCLUDED 1) set(proj virtualenv) -set(${proj}_TARGET_VERSION 14.0.6) -set(${proj}_DOWNLOAD_SOURCE_HASH "a035037925c82990a7659ecf8764bcdb") +set(${proj}_TARGET_VERSION 15.0.1) +set(${proj}_DOWNLOAD_SOURCE_HASH "28d76a0d9cbd5dc42046dd14e76a6ecc") # based on the standard EP_PREFIX locations, but since we don't build # or install, then standars install directory is also the source From 1a8826bc5830529a5dcfa0c7b2a00f7de8c5cfe6 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 21 Mar 2016 12:53:01 -0400 Subject: [PATCH 171/412] Use PYTHON_EXECUTABLE to call virtualenv If the default version of python was too old or not available determining the version of virtualenv would fail. Now the standard CMake variable PYTHON_EXECUTABLE is use to run the script. Change-Id: I2a6e4a661146c8d608a748577ee6a15493ba8e2d --- CMake/FindPythonVirtualEnv.cmake | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/CMake/FindPythonVirtualEnv.cmake b/CMake/FindPythonVirtualEnv.cmake index ba4a1d0d9..a7c68281d 100644 --- a/CMake/FindPythonVirtualEnv.cmake +++ b/CMake/FindPythonVirtualEnv.cmake @@ -15,9 +15,14 @@ find_program(PYTHON_VIRTUALENV_EXECUTABLE ) if(PYTHON_VIRTUALENV_EXECUTABLE) + + if ("${PYTHON_EXECUTABLE}" STREQUAL "") + find_package(PythonInterp REQUIRED) + endif() + ### PYTHON_VIRTUALENV_VERSION execute_process( - COMMAND ${PYTHON_VIRTUALENV_EXECUTABLE} --version + COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_VIRTUALENV_EXECUTABLE} --version OUTPUT_VARIABLE PYTHON_VIRTUALENV_VERSION_STRING ERROR_VARIABLE @@ -27,7 +32,10 @@ if(PYTHON_VIRTUALENV_EXECUTABLE) OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_STRIP_TRAILING_WHITESPACE ) - if (NOT PYTHON_VIRTUALENV_VERSION_RESULT_VARIABLE) + if (PYTHON_VIRTUALENV_VERSION_RESULT_VARIABLE) + message(ERROR "Unable to determing PythonVirtualEnv version!\n${PYTHON_VIRTUALENV_VERSION_STRING}") + set(PYTHON_VIRTUALENV_VERSION_STRING "") + else() string( REGEX MATCH "([0-9]*)([.])([0-9]*)([.]*)([0-9]*)" PYTHON_VIRTUALENV_VERSION ${PYTHON_VIRTUALENV_VERSION_STRING} ) From 5c427bc2e867f7e4bbf02aebaf3415fd8f73ccb6 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 21 Mar 2016 12:57:13 -0400 Subject: [PATCH 172/412] Rename PYTHON_VIRTUALENV_EXECUTABLE to SCRIPT This change has been made to reflect that script is executed with the python interpreter. Change-Id: Ib70c63f2e4c74c37b5811afe2d720287fad7d1c2 --- CMake/FindPythonVirtualEnv.cmake | 16 ++++++++-------- SuperBuild/External_virtualenv.cmake | 2 +- SuperBuild/SuperBuild.cmake | 2 +- Wrapping/Python/PythonVirtualEnvInstall.cmake.in | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/CMake/FindPythonVirtualEnv.cmake b/CMake/FindPythonVirtualEnv.cmake index a7c68281d..03df7946a 100644 --- a/CMake/FindPythonVirtualEnv.cmake +++ b/CMake/FindPythonVirtualEnv.cmake @@ -6,15 +6,15 @@ # # :: # -# PYTHON_VIRTUALENV_EXECUTABLE - the full path to virtualenv -# PYTHON_VIRTUALENV_EXECUTABLE_FOUND - If false, don't attempt to use lua +# PYTHON_VIRTUALENV_SCRIPT - the full path to virtualenv +# PYTHON_VIRTUALENV_SCRIPT_FOUND - If false, don't attempt to use lua # PYTHON_VIRTUALENV_VERSION_STRING - version of lua found -find_program(PYTHON_VIRTUALENV_EXECUTABLE - NAMES virtualenv virtualenv.py +find_program(PYTHON_VIRTUALENV_SCRIPT + NAMES virtualenv.py virtualenv ) -if(PYTHON_VIRTUALENV_EXECUTABLE) +if(PYTHON_VIRTUALENV_SCRIPT) if ("${PYTHON_EXECUTABLE}" STREQUAL "") find_package(PythonInterp REQUIRED) @@ -22,7 +22,7 @@ if(PYTHON_VIRTUALENV_EXECUTABLE) ### PYTHON_VIRTUALENV_VERSION execute_process( - COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_VIRTUALENV_EXECUTABLE} --version + COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_VIRTUALENV_SCRIPT} --version OUTPUT_VARIABLE PYTHON_VIRTUALENV_VERSION_STRING ERROR_VARIABLE @@ -47,7 +47,7 @@ endif() # all listed variables are TRUE include(FindPackageHandleStandardArgs) find_package_handle_standard_args(PythonVirtualEnv - REQUIRED_VARS PYTHON_VIRTUALENV_EXECUTABLE + REQUIRED_VARS PYTHON_VIRTUALENV_SCRIPT VERSION_VAR PYTHON_VIRTUALENV_VERSION_STRING) -mark_as_advanced(PYTHON_VIRTUALENV_EXECUTABLE) +mark_as_advanced(PYTHON_VIRTUALENV_SCRIPT) diff --git a/SuperBuild/External_virtualenv.cmake b/SuperBuild/External_virtualenv.cmake index 2aa580b2d..f2b204f85 100644 --- a/SuperBuild/External_virtualenv.cmake +++ b/SuperBuild/External_virtualenv.cmake @@ -31,4 +31,4 @@ ExternalProject_Add(${proj} ) set(${proj}_ROOT ${${proj}_source_dir}) -set(PYTHON_VIRTUALENV_EXECUTABLE ${${proj}_source_dir}/virtualenv.py) +set(PYTHON_VIRTUALENV_SCRIPT ${${proj}_source_dir}/virtualenv.py) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index d3e8821ce..3b929db8c 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -303,7 +303,7 @@ else() list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES virtualenv) endif() endif() -list(APPEND SimpleITK_VARS PYTHON_VIRTUALENV_EXECUTABLE) +list(APPEND SimpleITK_VARS PYTHON_VIRTUALENV_SCRIPT) #------------------------------------------------------------------------------ # ITK diff --git a/Wrapping/Python/PythonVirtualEnvInstall.cmake.in b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in index ffd53abd4..68912c061 100644 --- a/Wrapping/Python/PythonVirtualEnvInstall.cmake.in +++ b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in @@ -21,7 +21,7 @@ endif() # execute_process( COMMAND "@PYTHON_EXECUTABLE@" - "@PYTHON_VIRTUALENV_EXECUTABLE@" + "@PYTHON_VIRTUALENV_SCRIPT@" "--python=@PYTHON_EXECUTABLE@" ${VIRTUALENV_ARGS} "@PythonVirtualenvHome@" From a265d8ddcb9c690c65cc3bfae7c934fdb1e174e7 Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Wed, 23 Mar 2016 20:40:23 +1100 Subject: [PATCH 173/412] Missing tests of PixelType enumeration The last few entries of the large if statement, dealing with the various Label pixel types, were not performing the correct equality test. Change-Id: I8fe9743fa3d0055f3d2359a0e5c50a082b553aae --- Code/Common/src/sitkPixelIDValues.cxx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Common/src/sitkPixelIDValues.cxx b/Code/Common/src/sitkPixelIDValues.cxx index 5b9782519..b2f0f4830 100644 --- a/Code/Common/src/sitkPixelIDValues.cxx +++ b/Code/Common/src/sitkPixelIDValues.cxx @@ -129,15 +129,15 @@ const std::string GetPixelIDValueAsString( PixelIDValueType type ) { return "label of 8-bit unsigned integer"; } - else if ( sitkLabelUInt16 ) + else if ( type == sitkLabelUInt16 ) { return "label of 16-bit unsigned integer"; } - else if ( sitkLabelUInt32 ) + else if ( type == sitkLabelUInt32 ) { return "label of 32-bit unsigned integer"; } - else if ( sitkLabelUInt64 ) + else if ( type == sitkLabelUInt64 ) { return "label of 64-bit unsigned integer"; } From 2c90c1d105b47ff0d1022a8fbda7c157a4e8f431 Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Sun, 20 Mar 2016 20:43:00 +1100 Subject: [PATCH 174/412] A nicer way of dealing with the PixelIDValue enumeration. This patch deals with the typelist derived enumeration using a single function with a large if statement, rather than a series of functions wrapping individual enum values. The function is a variant of GetPixelIDValueAsString, but takes the C++ enumeration names as input. The advantage of this approach is that it provides a check that all the possible enumerations are dealt with. This happens because swig generates a R enumeration containing all names, which are then used as arguments to the new function. A marker value is returned when an unrecognised name is passed and a warning is flagged when the R package is loaded. Note that there may problems with the various Label options in GetPixelIDValueAsString, as there is no equality check. Change-Id: I2699b1af0aa98eb4bf7896aa296a778d6f7205c1 --- Code/Common/include/sitkPixelIDValues.h | 16 ++++ Code/Common/src/sitkPixelIDValues.cxx | 121 ++++++++++++++++++++++++ Wrapping/R/Packaging/SimpleITK/R/zA.R | 76 +++------------ Wrapping/R/R.i | 36 ------- 4 files changed, 152 insertions(+), 97 deletions(-) diff --git a/Code/Common/include/sitkPixelIDValues.h b/Code/Common/include/sitkPixelIDValues.h index 9c0e303cd..20f89193f 100644 --- a/Code/Common/include/sitkPixelIDValues.h +++ b/Code/Common/include/sitkPixelIDValues.h @@ -114,6 +114,22 @@ enum PixelIDValueEnum { const std::string SITKCommon_EXPORT GetPixelIDValueAsString( PixelIDValueType type ); const std::string SITKCommon_EXPORT GetPixelIDValueAsString( PixelIDValueEnum type ); +/** \brief Function mapping enumeration names in std::string to values + * + * This function is intended for use by the R bindings. R stores the enumeration values + * using the names : "sitkUnkown", "sitkUInt8", etc from PixelIDValueEnum above. + * This function is used to provide the integer values using calls like: + * + * val = GetPixelIDValueFromString("sitkInt32") + * + * If the pixel type has not been instantiated then the sitkUnknown value (-1) will + * be returned. If the pixel type string is not recognised (i.e. is not in the + * set of tested names) then the return value is -99. The idea is to provide + * a warning (via the R package) if this function needs to be updated to match + * changes to PixelIDValueEnum - i.e. if a new pixel type is added. + */ +PixelIDValueType SITKCommon_EXPORT GetPixelIDValueFromString(const std::string &enumString ); + #ifndef SWIG SITKCommon_EXPORT std::ostream& operator<<(std::ostream& os, const PixelIDValueEnum id); #endif diff --git a/Code/Common/src/sitkPixelIDValues.cxx b/Code/Common/src/sitkPixelIDValues.cxx index 5b9782519..d6aeb5ebf 100644 --- a/Code/Common/src/sitkPixelIDValues.cxx +++ b/Code/Common/src/sitkPixelIDValues.cxx @@ -147,6 +147,127 @@ const std::string GetPixelIDValueAsString( PixelIDValueType type ) } } + +PixelIDValueType GetPixelIDValueFromString(const std::string &enumString ) +{ + + if ( enumString == "sitkUnknown" ) + { + // Unknow must be first because other enums may be -1 if they are + // not instantiated + return sitkUnknown; + } + else if ( enumString == "sitkUInt8" ) + { + return sitkUInt8; + } + else if ( enumString == "sitkInt8" ) + { + return sitkInt8; + } + else if ( enumString == "sitkUInt16" ) + { + return sitkUInt16; + } + else if ( enumString == "sitkInt16" ) + { + return sitkInt16; + } + else if ( enumString == "sitkUInt32" ) + { + return sitkUInt32; + } + else if ( enumString == "sitkInt32" ) + { + return sitkInt32; + } + else if ( enumString == "sitkUInt64" ) + { + return sitkUInt64; + } + else if ( enumString == "sitkInt64" ) + { + return sitkInt64; + } + else if ( enumString == "sitkFloat32" ) + { + return sitkFloat32; + } + else if ( enumString == "sitkFloat64" ) + { + return sitkFloat64; + } + else if ( enumString == "sitkComplexFloat32" ) + { + return sitkComplexFloat32; + } + else if ( enumString == "sitkComplexFloat64" ) + { + return sitkComplexFloat64; + } + else if ( enumString == "sitkVectorUInt8" ) + { + return sitkVectorUInt8; + } + else if ( enumString == "sitkVectorInt8" ) + { + return sitkVectorInt8; + } + else if ( enumString == "sitkVectorUInt16" ) + { + return sitkVectorUInt16; + } + else if ( enumString == "sitkVectorInt16" ) + { + return sitkVectorInt16; + } + else if ( enumString == "sitkVectorUInt32" ) + { + return sitkVectorUInt32; + } + else if ( enumString == "sitkVectorInt32" ) + { + return sitkVectorInt32; + } + else if ( enumString == "sitkVectorUInt64" ) + { + return sitkVectorUInt64; + } + else if ( enumString == "sitkVectorInt64" ) + { + return sitkVectorInt64; + } + else if ( enumString == "sitkVectorFloat32" ) + { + return sitkVectorFloat32; + } + else if ( enumString == "sitkVectorFloat64" ) + { + return sitkVectorFloat64; + } + else if ( enumString == "sitkLabelUInt8" ) + { + return sitkLabelUInt8; + } + else if ( enumString == "sitkLabelUInt16" ) + { + return sitkLabelUInt16; + } + else if ( enumString == "sitkLabelUInt32" ) + { + return sitkLabelUInt32; + } + else if ( enumString == "sitkLabelUInt64" ) + { + return sitkLabelUInt64; + } + else + { + return -99; + } +} + + std::ostream& operator<<(std::ostream& os, const PixelIDValueEnum id) { return (os << GetPixelIDValueAsString(id)); diff --git a/Wrapping/R/Packaging/SimpleITK/R/zA.R b/Wrapping/R/Packaging/SimpleITK/R/zA.R index 85f292188..180f6c5dd 100644 --- a/Wrapping/R/Packaging/SimpleITK/R/zA.R +++ b/Wrapping/R/Packaging/SimpleITK/R/zA.R @@ -1,66 +1,20 @@ +redefineEnumeration <- function(enumerationName, the.function) +{ + current.enum <- get(paste(".__E__", enumerationName, sep = "")) + the.names <- names(current.enum) + values <- sapply(the.names, the.function) + + if (any(values== -99)) + { + warning("Some enumeration names are not recognised\n") + } + names(values) <- the.names + defineEnumeration(enumerationName, values) +} + .onLoad <- function(lib,pkg) { library.dynam("SimpleITK",pkg,lib) - - defineEnumeration('_itk__simple__PixelIDValueEnum', - .values = c( - 'sitkUnknown' = -1, - 'sitkUInt8' = RsitkUInt8(), - 'sitkInt8' = RsitkInt8(), - 'sitkUInt16' = RsitkUInt16(), - 'sitkInt16' = RsitkInt16(), - 'sitkUInt32' = RsitkUInt32(), - 'sitkInt32' = RsitkInt32(), - 'sitkUInt64' = RsitkUInt64(), - 'sitkInt64' = RsitkInt64(), - 'sitkFloat32' = RsitkFloat32(), - 'sitkFloat64' = RsitkFloat64(), - 'sitkComplexFloat32' = RsitkComplexFloat32(), - 'sitkComplexFloat64' = RsitkComplexFloat64(), - 'sitkVectorUInt8' = RsitkVectorUInt8(), - 'sitkVectorInt8' = RsitkVectorInt8(), - 'sitkVectorUInt16' = RsitkVectorUInt16(), - 'sitkVectorInt16' = RsitkVectorInt16(), - 'sitkVectorUInt32' = RsitkVectorUInt32(), - 'sitkVectorInt32' = RsitkVectorInt32(), - 'sitkVectorUInt64' = RsitkVectorUInt64(), - 'sitkVectorInt64' = RsitkVectorInt64(), - 'sitkVectorFloat32' = RsitkVectorFloat32(), - 'sitkVectorFloat64' = RsitkVectorFloat64(), - 'sitkLabelUInt8' = RsitkLabelUInt8(), - 'sitkLabelUInt16' = RsitkLabelUInt16(), - 'sitkLabelUInt32' = RsitkLabelUInt32(), - 'sitkLabelUInt64' = RsitkLabelUInt64() - )) - - defineEnumeration('_itk__simple__PixelGetEnum', - .values = c( - 'sitkUnknown' = -1, - 'Image_GetPixelAsUInt8' = RsitkUInt8(), - 'Image_GetPixelAsInt8' = RsitkInt8(), - 'Image_GetPixelAsiUInt16' = RsitkUInt16(), - 'Image_GetPixelAsInt16' = RsitkInt16(), - 'Image_GetPixelAsUInt32' = RsitkUInt32(), - 'Image_GetPixelAsInt32' = RsitkInt32(), - 'Image_GetPixelAsUInt64' = RsitkUInt64(), - 'Image_GetPixelAsInt64' = RsitkInt64(), - 'Image_GetPixelAsFloat' = RsitkFloat32(), - 'Image_GetPixelAsFloat' = RsitkFloat64() - )) - - defineEnumeration('_itk__simple__PixelSetEnum', - .values = c( - 'sitkUnknown' = -1, - 'Image_SetPixelAsUInt8' = RsitkUInt8(), - 'Image_SetPixelAsInt8' = RsitkInt8(), - 'Image_SetPixelAsiUInt16' = RsitkUInt16(), - 'Image_SetPixelAsInt16' = RsitkInt16(), - 'Image_SetPixelAsUInt32' = RsitkUInt32(), - 'Image_SetPixelAsInt32' = RsitkInt32(), - 'Image_SetPixelAsUInt64' = RsitkUInt64(), - 'Image_SetPixelAsInt64' = RsitkInt64(), - 'Image_SetPixelAsFloat' = RsitkFloat32(), - 'Image_SetPixelAsFloat' = RsitkFloat64() - )) + redefineEnumeration('_itk__simple__PixelIDValueEnum', GetPixelIDValueFromString) createPixLookup() } diff --git a/Wrapping/R/R.i b/Wrapping/R/R.i index 32745acdb..518f65827 100644 --- a/Wrapping/R/R.i +++ b/Wrapping/R/R.i @@ -39,46 +39,10 @@ std::vector, std::vector *, std::vector & return(invisible($result)) %} -// some important enumerations don't get evaluate properly. This is a -// hack to fix the problem. %inline %{ #include "sitkConditional.h" - // causes swig problems - //namespace sitk = itk::simple; - - itk::simple::PixelIDValueType RsitkUInt8 = itk::simple::sitkUInt8; - itk::simple::PixelIDValueType RsitkInt8 = itk::simple::sitkInt8; - itk::simple::PixelIDValueType RsitkUInt16 = itk::simple::sitkUInt16; - itk::simple::PixelIDValueType RsitkInt16 = itk::simple::sitkInt16; - itk::simple::PixelIDValueType RsitkUInt32 = itk::simple::sitkUInt32; - itk::simple::PixelIDValueType RsitkInt32 = itk::simple::sitkInt32; - itk::simple::PixelIDValueType RsitkUInt64 = itk::simple::sitkUInt64; - itk::simple::PixelIDValueType RsitkInt64 = itk::simple::sitkInt64; - itk::simple::PixelIDValueType RsitkFloat32 = itk::simple::sitkFloat32; - itk::simple::PixelIDValueType RsitkFloat64 = itk::simple::sitkFloat64; - - itk::simple::PixelIDValueType RsitkComplexFloat32 = itk::simple::sitkComplexFloat32; - itk::simple::PixelIDValueType RsitkComplexFloat64 = itk::simple::sitkComplexFloat64; - - itk::simple::PixelIDValueType RsitkVectorUInt8 = itk::simple::sitkVectorUInt8; - itk::simple::PixelIDValueType RsitkVectorInt8 = itk::simple::sitkVectorInt8; - itk::simple::PixelIDValueType RsitkVectorUInt16 = itk::simple::sitkVectorUInt16; - itk::simple::PixelIDValueType RsitkVectorInt16 = itk::simple::sitkVectorInt16; - itk::simple::PixelIDValueType RsitkVectorUInt32 = itk::simple::sitkVectorUInt32; - itk::simple::PixelIDValueType RsitkVectorInt32 = itk::simple::sitkVectorInt32; - itk::simple::PixelIDValueType RsitkVectorUInt64 = itk::simple::sitkVectorUInt64; - itk::simple::PixelIDValueType RsitkVectorInt64 = itk::simple::sitkVectorInt64; - itk::simple::PixelIDValueType RsitkVectorFloat32 = itk::simple::sitkVectorFloat32; - itk::simple::PixelIDValueType RsitkVectorFloat64 = itk::simple::sitkVectorFloat64; - - - itk::simple::PixelIDValueType RsitkLabelUInt8 = itk::simple::sitkLabelUInt8; - itk::simple::PixelIDValueType RsitkLabelUInt16 = itk::simple::sitkLabelUInt16; - itk::simple::PixelIDValueType RsitkLabelUInt32 = itk::simple::sitkLabelUInt32; - itk::simple::PixelIDValueType RsitkLabelUInt64 = itk::simple::sitkLabelUInt64; - // functions for image content access via bracket operator itk::simple::Image SingleBracketOperator(std::vector xcoord, std::vector ycoord, std::vector zcoord, const itk::simple::Image src) From a04b0c679834a55b703c70ec96aac59819d02a1a Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 25 Mar 2016 14:34:01 -0400 Subject: [PATCH 175/412] Fix TemplateComponent active member parameter name Do not assume it's label use the json value. Change-Id: I179eb47fc57cba42940befae4cf7f1e31a1d1357 --- TemplateComponents/CustomCasts.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TemplateComponents/CustomCasts.cxx b/TemplateComponents/CustomCasts.cxx index dedf1e231..15ec3200f 100644 --- a/TemplateComponents/CustomCasts.cxx +++ b/TemplateComponents/CustomCasts.cxx @@ -32,7 +32,7 @@ end if label_map then OUT=OUT..[[f->GetOutput()->GetLabelObject(label)->Get${name}()]] else - OUT=OUT..[[f->Get${name}(label)]] + OUT=OUT..[[f->Get${name}(${parameters[1].name})]] end if custom_cast then OUT=OUT..')' From ca3cb8f87e01e17a2745d1ee33189af643b82c18 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 24 Mar 2016 13:15:56 -0400 Subject: [PATCH 176/412] try_compile test for allowing undefined symbols in shared libraries On Linux (ELF) libraries dynamically loaded by an executable can use the run-time environment of the executable. This is the recommended way for Python modules[1] along with other languages loadable modules. This patch adds a test to determine if the linker allows unresolved symbols in shared library, this presumably indicates that the operating system support loading symbols from the executable into a loaded module to resolve the module's symbols at run-time. [1] https://mail.python.org/pipermail/distutils-sig/2016-February/028275.html Change-Id: I6188d8f74ac1b480906c7fdb1fc715605e2a5af2 --- CMake/sitkCheckUndefinedSymbolsAllowed.cmake | 58 ++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 CMake/sitkCheckUndefinedSymbolsAllowed.cmake diff --git a/CMake/sitkCheckUndefinedSymbolsAllowed.cmake b/CMake/sitkCheckUndefinedSymbolsAllowed.cmake new file mode 100644 index 000000000..a368dd646 --- /dev/null +++ b/CMake/sitkCheckUndefinedSymbolsAllowed.cmake @@ -0,0 +1,58 @@ +# +# Check if the linker allows undefined symbols for shared libraries. +# +# SITK_UNDEFINED_SYMBOLS_ALLOWED - true if the linker will allow +# undefined symbols for shared libraries +# + +function(_sitkCheckUndefinedSymbolsAllowed) + + set(VARIABLE "SITK_UNDEFINED_SYMBOLS_ALLOWED") + set(cache_var "${VARIABLE}_hash") + + # hash the CMAKE_FLAGS passed and check cache to know if we need to rerun + string(MD5 cmake_flags_hash "${CMAKE_SHARED_LINKER_FLAGS}") + + if(NOT DEFINED "${cache_var}" ) + unset("${VARIABLE}" CACHE) + elseif(NOT "${${cache_var}}" STREQUAL "${cmake_flags_hash}" ) + unset("${VARIABLE}" CACHE) + endif() + + if(NOT DEFINED "${VARIABLE}") + set(test_project_dir "${PROJECT_BINARY_DIR}/CMakeTmp/${VARIABLE}") + + file(WRITE "${test_project_dir}/CMakeLists.txt" +" +project(undefined C) +add_library(foo SHARED \"foo.c\") +") + + file(WRITE "${test_project_dir}/foo.c" +" +extern int bar(void); +int foo(void) {return bar()+1;} +") + + try_compile(${VARIABLE} + "${test_project_dir}" + "${test_project_dir}" + undefined + CMAKE_FLAGS + "-DCMAKE_SHARED_LINKER_FLAGS='${CMAKE_SHARED_LINKER_FLAGS}'" + OUTPUT_VARIABLE output) + + set(${cache_var} "${cmake_flags_hash}" CACHE INTERNAL "hashed try_compile flags") + + if(${VARIABLE}) + message(STATUS "Performing Test ${VARIABLE} - Success") + else() + message(STATUS "Performing Test ${VARIABLE} - Failed") + file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log + "Performing Test ${VARIABLE} failed with the following output:\n" + "${OUTPUT}\n") + endif() + endif() +endfunction() + +_sitkCheckUndefinedSymbolsAllowed() From 4124f81602fb083bc310a8a7e1e7be0596d6d8d5 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 25 Mar 2016 15:59:09 -0400 Subject: [PATCH 177/412] Improve flag hashing with C++11 try_compiles Change-Id: Id8ba59e50d6269b80d98cce930c27012479c632e --- CMake/sitkCheckCXX11.cmake | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/CMake/sitkCheckCXX11.cmake b/CMake/sitkCheckCXX11.cmake index 70225d058..b27cd63e8 100644 --- a/CMake/sitkCheckCXX11.cmake +++ b/CMake/sitkCheckCXX11.cmake @@ -17,25 +17,33 @@ # Function to wrap try compiles on the aggregate cxx test file1 # function(sitkCXX11Test VARIABLE) - # use the hash of the dependent cxx flags in the variable name to - # cache the results. - string(MD5 cmake_cxx_flags_hash "${CMAKE_CXX_FLAGS}") - set(cache_var "${VARIABLE}_${hash_cmake_cxx_flags_hash}") - if(NOT DEFINED "${cache_var}") + # use the hash of the dependent cxx flags in the cached variable + # value to know if the arguments have changed, and need to rerun + string(MD5 cmake_flags_hash "${CMAKE_CXX_FLAGS}") + set(cache_var "${VARIABLE}_hash") + + if(NOT DEFINED "${cache_var}" ) + unset("${VARIABLE}" CACHE) + elseif(NOT "${${cache_var}}" STREQUAL "${cmake_flags_hash}" ) + unset("${VARIABLE}" CACHE) + endif() + + if(NOT DEFINED "${VARIABLE}") message(STATUS "Performing Test ${VARIABLE}") set(requred_definitions "${CMAKE_REQUIRED_DEFINITIONS} -D${VARIABLE}") try_compile(${VARIABLE} - ${SimpleITK_BINARY_DIR}/CMakeTmp - ${SimpleITK_SOURCE_DIR}/CMake/sitk_check_cxx11.cxx + "${PROJECT_BINARY_DIR}/CMakeTmp" + "${CMAKE_CURRENT_LIST_DIR}/sitk_check_cxx11.cxx" CMAKE_FLAGS -DCOMPILE_DEFINITIONS:STRING=${requred_definitions} OUTPUT_VARIABLE output) + + set(${cache_var} "${cmake_flags_hash}" CACHE INTERNAL "hashed try_compile flags") + if(${VARIABLE}) - set(${cache_var} 1 CACHE INTERNAL "SimpleITK test ${FUNCTION}") message(STATUS "Performing Test ${VARIABLE} - Success") else() message(STATUS "Performing Test ${VARIABLE} - Failed") - set(${cache_var} 0 CACHE INTERNAL "SimpleITKTest ${FUNCTION}") file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "Performing Test ${VARIABLE} failed with the following output:\n" "${OUTPUT}\n") From a5a9386fa7c8be4b2d6ba4ff951a781bd5a1d395 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 25 Mar 2016 16:06:46 -0400 Subject: [PATCH 178/412] Use localized cmake list variable for paths. Using better CMake variable to improve portability of the code. Change-Id: Ib3888a079406211cd615ec0b489527f14182509f --- CMake/sitkCheckRequiredFlags.cmake | 4 ++-- CMake/sitkSourceVersion.cmake | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CMake/sitkCheckRequiredFlags.cmake b/CMake/sitkCheckRequiredFlags.cmake index 5dba0ac45..0f8d65dc5 100644 --- a/CMake/sitkCheckRequiredFlags.cmake +++ b/CMake/sitkCheckRequiredFlags.cmake @@ -43,8 +43,8 @@ if(required LESS 0) message(STATUS "Checking if c++11 is required...") try_compile(SITK_CHECK_CXX11_REQUIRED - ${SimpleITK_BINARY_DIR}/CMakeTmp - ${SimpleITK_SOURCE_DIR}/CMake/sitk_check_cxx11_required.cxx + "${PROJECT_BINARY_DIR}/CMakeTmp" + "${CMAKE_CURRENT_LIST_DIR}/sitk_check_cxx11_required.cxx" OUTPUT_VARIABLE OUTPUT) if(${SITK_CHECK_CXX11_REQUIRED}) message(STATUS "Checking if c++11 is required... NO" ) diff --git a/CMake/sitkSourceVersion.cmake b/CMake/sitkSourceVersion.cmake index bca2ed126..78f14027a 100644 --- a/CMake/sitkSourceVersion.cmake +++ b/CMake/sitkSourceVersion.cmake @@ -35,7 +35,7 @@ get_git_head_revision(GIT_REFVAR _GIT_VERSION_HASH) # which should contain this additional cmake file with the # _GIT_VERSION variables if(_GIT_VERSION_HASH STREQUAL "GITDIR-NOTFOUND") - include( "${CMAKE_CURRENT_SOURCE_DIR}/CMake/sitkSourceVersionVars.cmake" ) + include( "${CMAKE_CURRENT_LIST_DIR}/sitkSourceVersionVars.cmake" ) return() endif() @@ -113,5 +113,5 @@ else() endif() # save variable in a configuration file in case we have no git directory -configure_file("${CMAKE_CURRENT_SOURCE_DIR}/CMake/sitkSourceVersionVars.cmake.in" +configure_file("${CMAKE_CURRENT_LIST_DIR}/sitkSourceVersionVars.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/sitkSourceVersionVars.cmake" @ONLY) From 6e7c5851219dcf531b0608d6a5573a0ac4236426 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 25 Mar 2016 14:25:50 -0400 Subject: [PATCH 179/412] Don't link to language libraries on linux If the linker allows unresolved symbols, then don't link to the language libraries. Change-Id: I6f60092db81dbbe7bf5c6ec6528bc9c17d5fde5d --- CMake/sitkCheckUndefinedSymbolsAllowed.cmake | 3 ++- CMake/sitkExtras.cmake | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CMake/sitkCheckUndefinedSymbolsAllowed.cmake b/CMake/sitkCheckUndefinedSymbolsAllowed.cmake index a368dd646..ea646b5c6 100644 --- a/CMake/sitkCheckUndefinedSymbolsAllowed.cmake +++ b/CMake/sitkCheckUndefinedSymbolsAllowed.cmake @@ -10,6 +10,7 @@ function(_sitkCheckUndefinedSymbolsAllowed) set(VARIABLE "SITK_UNDEFINED_SYMBOLS_ALLOWED") set(cache_var "${VARIABLE}_hash") + # hash the CMAKE_FLAGS passed and check cache to know if we need to rerun string(MD5 cmake_flags_hash "${CMAKE_SHARED_LINKER_FLAGS}") @@ -39,7 +40,7 @@ int foo(void) {return bar()+1;} "${test_project_dir}" undefined CMAKE_FLAGS - "-DCMAKE_SHARED_LINKER_FLAGS='${CMAKE_SHARED_LINKER_FLAGS}'" + "-DCMAKE_SHARED_LINKER_FLAGS='${CMAKE_SHARED_LINKER_FLAGS}'" OUTPUT_VARIABLE output) set(${cache_var} "${cmake_flags_hash}" CACHE INTERNAL "hashed try_compile flags") diff --git a/CMake/sitkExtras.cmake b/CMake/sitkExtras.cmake index a03ea48d7..110c7ecf3 100644 --- a/CMake/sitkExtras.cmake +++ b/CMake/sitkExtras.cmake @@ -10,11 +10,20 @@ # simular to using "-shared" on Linux where undefined symbols are # ignored. # +# Additionally, the linker is checked to see if it supports undefined +# symbols when linking a shared library. If it does then the library +# is not linked when specified with this function. +# # http://blog.tim-smith.us/2015/09/python-extension-modules-os-x/ # + +include(sitkCheckUndefinedSymbolsAllowed) + macro( sitk_target_link_libraries_with_dynamic_lookup target ) if ( ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" ) set_target_properties( ${target} PROPERTIES LINK_FLAGS "-undefined dynamic_lookup" ) + elseif(SITK_UNDEFINED_SYMBOLS_ALLOWED) + # linker allows undefined symbols, let's just not link else() target_link_libraries ( ${target} ${ARGN} ) endif() From 41ed82fd911e4312d726aacd424f173927c363e3 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 11 Dec 2015 15:05:51 -0500 Subject: [PATCH 180/412] Check for name of current project in stead of related variable Change-Id: I562379c2f47ad3bde173145ff4e7655d34585c21 --- Examples/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index 6fd1e052e..66305bbe1 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 2.8) project(SimpleITKExamples) -if(NOT SimpleITK_SOURCE_DIR) +if(NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK") find_package(SimpleITK REQUIRED) include(${SimpleITK_USE_FILE}) From ce965ab38d7ae910b5a922e407c19f249d648af8 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 11 Dec 2015 15:07:09 -0500 Subject: [PATCH 181/412] Split FORBID_DOWNLOADS cmake flag into separate file Change-Id: Ic1ec9393d85d05581ed82e258737a9523ddb3d5b --- CMake/sitkForbidDownloadsOption.cmake | 12 ++++++++++++ CMakeLists.txt | 14 +------------- 2 files changed, 13 insertions(+), 13 deletions(-) create mode 100644 CMake/sitkForbidDownloadsOption.cmake diff --git a/CMake/sitkForbidDownloadsOption.cmake b/CMake/sitkForbidDownloadsOption.cmake new file mode 100644 index 000000000..aaa96f7b6 --- /dev/null +++ b/CMake/sitkForbidDownloadsOption.cmake @@ -0,0 +1,12 @@ + +#----------------------------------------------------------------------------- +# Forbid downloading resources from the network during a build. This helps +# when building on systems without network connectivity to determine which +# resources much be obtained manually and made available to the build. +option(SITK_FORBID_DOWNLOADS "Do not download source code or data from the network" OFF) +mark_as_advanced(SITK_FORBID_DOWNLOADS) +macro(sitk_enforce_forbid_downloads _name) + if(SITK_FORBID_DOWNLOADS) + message(SEND_ERROR "Attempted to download ${_name} when SITK_FORBID_DOWNLOADS is ON") + endif() +endmacro() diff --git a/CMakeLists.txt b/CMakeLists.txt index fbf470117..d5cf99794 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -125,19 +125,7 @@ option( SITK_4D_IMAGES "Add Image and I/O support for four spatial dimensions." mark_as_advanced( SITK_4D_IMAGES ) -#----------------------------------------------------------------------------- -# Forbid downloading resources from the network during a build. This helps -# when building on systems without network connectivity to determine which -# resources much be obtained manually and made available to the build. -option(SITK_FORBID_DOWNLOADS "Do not download source code or data from the network" OFF) -mark_as_advanced(SITK_FORBID_DOWNLOADS) -macro(sitk_enforce_forbid_downloads _name) - if(SITK_FORBID_DOWNLOADS) - message(SEND_ERROR "Attempted to download ${_name} when SITK_FORBID_DOWNLOADS is ON") - endif() -endmacro() - - +include( sitkForbidDownloadsOption ) # Setup build locations. if(NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY) From 8954fe1d7129b5bb98a75d789a556d3067cdf6ed Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 11 Dec 2015 15:07:57 -0500 Subject: [PATCH 182/412] Move Strip option and function to separate file Change-Id: I4950cff4865c38bd2f94574c1113889fef72454e --- CMake/sitkStripOption.cmake | 30 ++++++++++++++++++++++++++++++ CMakeLists.txt | 30 +----------------------------- 2 files changed, 31 insertions(+), 29 deletions(-) create mode 100644 CMake/sitkStripOption.cmake diff --git a/CMake/sitkStripOption.cmake b/CMake/sitkStripOption.cmake new file mode 100644 index 000000000..49677e1b0 --- /dev/null +++ b/CMake/sitkStripOption.cmake @@ -0,0 +1,30 @@ + +#------------------------------------------------------------------------------ +# Strip Option + +# Add option to strip wrapping libraries. +# Since the wrapping libraries don't get installed by the normal cmake +# installation process, this option enables stripping of the libraries +# as part of the build process. It should be used on the laguage +# targets and the the SimpleITK iterface, as those can be installed +# into the system. +option(SimpleITK_BUILD_STRIP "Strip executables and libraries after building." OFF) +mark_as_advanced(SimpleITK_BUILD_STRIP) +set(CMAKE_STRIP_FLAGS "-x" CACHE STRING "Flags used by strip in the post_build.") +mark_as_advanced(CMAKE_STRIP_FLAGS) +separate_arguments(CMAKE_STRIP_FLAGS) + +function(sitk_strip_target tgt) + if(NOT SimpleITK_BUILD_STRIP) + return() + endif() + get_property(type TARGET ${tgt} PROPERTY TYPE) + if(NOT type STREQUAL STATIC_LIBRARY) + add_custom_command( + TARGET ${tgt} + POST_BUILD + COMMAND ${CMAKE_STRIP} ${CMAKE_STRIP_FLAGS} "$" + ) + endif() + +endfunction() diff --git a/CMakeLists.txt b/CMakeLists.txt index d5cf99794..68afedbb9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -223,35 +223,7 @@ function(sitk_install_exported_target tgt) ) endfunction() -#------------------------------------------------------------------------------ -# Strip Option - -# Add option to strip wrapping libraries. -# Since the wrapping libraries don't get installed by the normal cmake -# installation process, this option enables stripping of the libraries -# as part of the build process. It should be used on the laguage -# targets and the the SimpleITK iterface, as those can be installed -# into the system. -option(SimpleITK_BUILD_STRIP "Strip executables and libraries after building." OFF) -mark_as_advanced(SimpleITK_BUILD_STRIP) -set(CMAKE_STRIP_FLAGS "-x" CACHE STRING "Flags used by strip in the post_build.") -mark_as_advanced(CMAKE_STRIP_FLAGS) -separate_arguments(CMAKE_STRIP_FLAGS) - -function(sitk_strip_target tgt) - if(NOT SimpleITK_BUILD_STRIP) - return() - endif() - get_property(type TARGET ${tgt} PROPERTY TYPE) - if(NOT type STREQUAL STATIC_LIBRARY) - add_custom_command( - TARGET ${tgt} - POST_BUILD - COMMAND ${CMAKE_STRIP} ${CMAKE_STRIP_FLAGS} "$" - ) - endif() - -endfunction() +include(sitkStripOption) #------------------------------------------------------------------------------ # These are some system specific compiler options needed to build SimpleITK From b29e9ebd9a2eb1b6ebac69067f8944e6c56f9ceb Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 11 Dec 2015 15:09:18 -0500 Subject: [PATCH 183/412] Remove WRAP_PYTHON conditional in Python sub-directory for dist Change-Id: I16aafdd94851aae978c887b92edfdf478ae5642b --- Wrapping/Python/dist/CMakeLists.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Wrapping/Python/dist/CMakeLists.txt b/Wrapping/Python/dist/CMakeLists.txt index b40de44ae..331bd9d3e 100644 --- a/Wrapping/Python/dist/CMakeLists.txt +++ b/Wrapping/Python/dist/CMakeLists.txt @@ -1,14 +1,13 @@ # # Packaging # - if( SimpleITK_PYTHON_EGG OR SimpleITK_PYTHON_WHEEL ) if( NOT SITK_PYTHON_USE_VIRTUALENV ) message( STATUS "Not using SimpleITK's virtualenv for distribution!\ Using unknown versions of pip, setuptools and/or wheel packages/" ) endif() - set(bdist_setup "${SimpleITK_BINARY_DIR}/Wrapping/Python/Packaging/setupegg.py") + set(bdist_setup "${CMAKE_CURRENT_BINARY_DIR}/Packaging/setupegg.py") set(bdist_commands "") if( SimpleITK_PYTHON_EGG ) @@ -21,11 +20,12 @@ Using unknown versions of pip, setuptools and/or wheel packages/" ) add_custom_target( dist.Python ${VIRTUAL_PYTHON_EXECUTABLE} ${bdist_setup} ${bdist_commands} - WORKING_DIRECTORY ${SimpleITK_BINARY_DIR}/Wrapping/Python + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} DEPENDS ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} COMMENT "Creating Python binary distribution" ) add_dependencies( dist.Python PythonVirtualEnv) add_dependencies( dist dist.Python ) - +elseif() + message( STATUS "Not creating dist.Python target since SITK_FORBID_DOWNLOADS is enabled" ) endif() From 3d5429f9250f65a9d86170c3647aa4277c4c1542 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 11 Dec 2015 15:45:44 -0500 Subject: [PATCH 184/412] Move Java variables to sub-directory Change-Id: I7a3352b859f9d55da92954b1e3f08c5ce4a0dc9d --- CMakeLists.txt | 7 ------- Testing/Unit/CMakeLists.txt | 4 +++- Wrapping/Java/CMakeLists.txt | 4 ++++ 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 68afedbb9..8e5592d7a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -161,13 +161,6 @@ set ( GENERATED_TEST_LIST "" CACHE INTERNAL "" ) set ( GENERATED_FILTER_LIST "" CACHE INTERNAL "" ) set ( GENERATED_TEST_SOURCE_LIST "" CACHE INTERNAL "" ) - - -set(JAR_FILE "simpleitk-${SimpleITK_VERSION}.jar") -set(JAVADOC_FILE "simpleitk-javadoc-${SimpleITK_VERSION}.jar") -set(JAVA_SOURCE_FILE "simpleitk-source-${SimpleITK_VERSION}.jar") - - # Create cached list of all template components file( GLOB template_components ${SimpleITK_SOURCE_DIR}/TemplateComponents/*.h.in diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index e27154b64..8d78bfe63 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -48,7 +48,9 @@ file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/JavaTests/org/itk/simple/testing file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/CSharpTests) # Adjust Python to run in the virtualenv -set( PythonVirtualenvHome ${SimpleITK_BINARY_DIR}/Testing/Installation/PythonVirtualenv ) +set( PythonVirtualenvHome ${SimpleITK_BINARY_DIR}/Testing/Installation/PythonVirtualenv ) + +set(JAR_FILE "simpleitk-${SimpleITK_VERSION}.jar") add_executable(SimpleITKUnitTestDriver0 SimpleITKUnitTestDriver.cxx ${SimpleITKUnitTestSource}) diff --git a/Wrapping/Java/CMakeLists.txt b/Wrapping/Java/CMakeLists.txt index 4dd3db03b..4c856a15a 100644 --- a/Wrapping/Java/CMakeLists.txt +++ b/Wrapping/Java/CMakeLists.txt @@ -2,6 +2,10 @@ find_package ( Java REQUIRED ) find_package ( JNI REQUIRED ) include_directories ( ${JAVA_INCLUDE_PATH} ${JNI_INCLUDE_DIRS} ) +set(JAR_FILE "simpleitk-${SimpleITK_VERSION}.jar") +set(JAVADOC_FILE "simpleitk-javadoc-${SimpleITK_VERSION}.jar") +set(JAVA_SOURCE_FILE "simpleitk-source-${SimpleITK_VERSION}.jar") + set_source_files_properties ( SimpleITK.i PROPERTIES CPLUSPLUS ON ) FIND_PROGRAM(Java_JAVADOC_EXECUTABLE From 2867ceb740fff0c8441ad69170a2c8b244c90d41 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 29 Mar 2016 15:43:34 -0400 Subject: [PATCH 185/412] Moving CSharp Java dependencies to individual file generations step. Change-Id: Id338adbb5fef06104ce42b299a4e3ea6e489acf3 --- Testing/Unit/CMakeLists.txt | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index 8d78bfe63..ad4e733f4 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -185,7 +185,7 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) COMMAND ${CMAKE_COMMAND} -E remove -f "${OUTPUT_TEST_FILENAME}" COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Java ${template_include_dir} TestTemplate.java.in "${OUTPUT_TEST_FILENAME}" COMMAND ${Java_JAVAC_EXECUTABLE} -classpath ${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE} ${SimpleITK_BINARY_DIR}/Testing/Unit/JavaTests/org/itk/simple/testing/${FILTERNAME}Test.java - DEPENDS ${filter_json_file} ${JAVA_TEMPLATE_FILES} ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} + DEPENDS ${filter_json_file} ${JAVA_TEMPLATE_FILES} ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} org_itk_simple_jar ) add_test( NAME Java.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=Java.${FILTERNAME} ) set ( WRAPPED_GENERATED_TEST_SOURCE ${WRAPPED_GENERATED_TEST_SOURCE} ${OUTPUT_TEST_FILENAME}) @@ -207,7 +207,7 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) /t:exe /platform:${CSHARP_PLATFORM} /lib:${CSHARP_BINARY_DIRECTORY} /reference:System.dll /reference:SimpleITKCSharpManaged.dll /out:${CSHARP_BINARY_DIRECTORY}/Test${FILTERNAME}.exe ${OUTPUT_TEST_FILENAME_SAFE} - DEPENDS ${filter_json_file} ${CSHARP_TEMPLATE_FILES} + DEPENDS ${filter_json_file} ${CSHARP_TEMPLATE_FILES} SimpleITKCSharpManaged ) add_test( NAME CSharp.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=CSharp.${FILTERNAME} ) set ( WRAPPED_GENERATED_TEST_SOURCE ${WRAPPED_GENERATED_TEST_SOURCE} ${OUTPUT_TEST_FILENAME}) @@ -249,16 +249,6 @@ if(MSVC_VERSION EQUAL 1700) add_definitions(-DGTEST_HAS_TR1_TUPLE=0 ) endif() -# Add org.itk.simple.jar dependency if necessary -if( WRAP_JAVA ) - add_dependencies(WrappedGeneratedTests org_itk_simple_jar) -endif() - -# Add C# dependency if necessary -if( WRAP_CSHARP ) - add_dependencies(WrappedGeneratedTests SimpleITKCSharpManaged) -endif() - add_executable(sitkShowTest sitkShowTest.cxx ) target_link_libraries ( sitkShowTest ${SimpleITK_LIBRARIES} ) From 365014a1e67f9b8e5a04e68a52245d0a54019440 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 29 Mar 2016 15:44:30 -0400 Subject: [PATCH 186/412] Moved location of org_itk_simple_jar target. Change-Id: I4bb5bc77fa8f3ae723dd9e01beea8c60293b33e0 --- Wrapping/Java/CMakeLists.txt | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Wrapping/Java/CMakeLists.txt b/Wrapping/Java/CMakeLists.txt index 4c856a15a..72c4a555f 100644 --- a/Wrapping/Java/CMakeLists.txt +++ b/Wrapping/Java/CMakeLists.txt @@ -29,9 +29,7 @@ target_link_libraries( ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} ${SimpleITK_LIBR set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") sitk_strip_target( ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} ) -# Add target for org.itk.simple.jar -add_custom_target(org_itk_simple_jar ALL DEPENDS ${JAR_FILE}) -set(JAVA_SOURCE_CODE ${JAVA_SOURCE_DIRECTORY}/org/itk/simple/*.java) +set(JAVA_SOURCE_CODE "${JAVA_SOURCE_DIRECTORY}/org/itk/simple/*.java") # Java 1.8 javadoc treats linting errors as build errors by default # so linting should be opt-in for this version @@ -58,6 +56,10 @@ add_custom_command( DEPENDS ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} ) +# Add target for org.itk.simple.jar +add_custom_target(org_itk_simple_jar ALL DEPENDS ${JAR_FILE}) + + # Get the location of the extension directory string(REGEX REPLACE "include" "jre/lib/ext" JAVA_EXTENSION_DIR ${JAVA_INCLUDE_PATH} ) From 6fa2758e3cd0f332efc263d9321b26f5ccd8350d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 28 Mar 2016 11:00:43 -0400 Subject: [PATCH 187/412] Make wrapped languages independent projects. CMake code was re factored into a common file to get the environment setup for in SimpleITK project builds and outside. Various paths were updated to be valid for both building locations. Currently the testing does not working outside the SimpleITK project. Change-Id: I415a3563a8b66f7e925a2bc83049fcac193bb82a --- CMake/sitkProjectLanguageCommon.cmake | 75 +++++++++++++++++++++++++++ Wrapping/CMakeLists.txt | 46 ---------------- Wrapping/CSharp/CMakeLists.txt | 42 ++++++++------- Wrapping/CSharp/dist/CMakeLists.txt | 2 +- Wrapping/Java/CMakeLists.txt | 6 +++ Wrapping/Java/dist/CMakeLists.txt | 6 +-- Wrapping/Lua/CMakeLists.txt | 17 +++++- Wrapping/Python/CMakeLists.txt | 22 +++++++- Wrapping/R/CMakeLists.txt | 15 ++++++ Wrapping/Ruby/CMakeLists.txt | 5 ++ Wrapping/Tcl/CMakeLists.txt | 5 ++ 11 files changed, 170 insertions(+), 71 deletions(-) create mode 100644 CMake/sitkProjectLanguageCommon.cmake diff --git a/CMake/sitkProjectLanguageCommon.cmake b/CMake/sitkProjectLanguageCommon.cmake new file mode 100644 index 000000000..a91fd3a6b --- /dev/null +++ b/CMake/sitkProjectLanguageCommon.cmake @@ -0,0 +1,75 @@ + +# +# Project setup +# + +if (NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK" ) + + set( SimpleITK_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../.." ) + list(APPEND CMAKE_MODULE_PATH "${SimpleITK_SOURCE_DIR}/CMake") + + #HACK - we should not be using anything from this directory + set( SimpleITK_BINARY_DIR ${SimpleITK_DIR} ) + + find_package(SimpleITK REQUIRED) + include(${SimpleITK_USE_FILE}) + + # Add compiler flags needed to use SimpleITK. + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SimpleITK_REQUIRED_C_FLAGS}") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SimpleITK_REQUIRED_CXX_FLAGS}") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") + set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") + +endif() + +if(NOT TARGET dist) + add_custom_target( dist cmake -E echo "Finished generating wrapped packages for distribution..." ) +endif() + +# TODO these should be moved into UseSimpleITK +if(NOT SimpleITK_DOC_FILES) + set ( SimpleITK_DOC_FILES + "${SimpleITK_SOURCE_SOURCE_DIR}/LICENSE" + "${SimpleITK_SOURCE_SOURCE_DIR}/NOTICE" + "${SimpleITK_SOURCE_SOURCE_DIR}/Readme.md" + ) +endif() + +# +# General SWIG configuration +# + +find_package ( SWIG 2 REQUIRED ) + +include (UseSWIGLocal) + +file(GLOB SWIG_EXTRA_DEPS + "${SimpleITK_SOURCE_DIR}/Code/Common/include/*.h" + "${SimpleITK_SOURCE_DIR}/Code/Registration/include/*.h" + "${SimpleITK_SOURCE_DIR}/Code/IO/include/*.h") + +# make a manual list of dependencies for the Swig.i files +list( APPEND SWIG_EXTRA_DEPS "${SimpleITK_BINARY_DIR}/Code/BasicFilters/include/SimpleITKBasicFiltersGeneratedHeaders.i" + "${SimpleITK_BINARY_DIR}/Code/BasicFilters/include/SimpleITKBasicFiltersGeneratedHeaders.h" + ${SimpleITKBasicFiltersGeneratedHeader} + ) + +# check if uint64_t is the same as unsigned long +try_compile(SITK_ULONG_SAME_AS_UINT64 + ${PROJECT_BINARY_DIR}/CMakeTmp + ${SimpleITK_SOURCE_DIR}/CMake/same_uint64_ulong.cxx ) + +# when "-DSWIGWORDSIZE64" is defined SWIG used unsigned long for uint64_t types +if(${SITK_ULONG_SAME_AS_UINT64} ) + set ( CMAKE_SWIG_GLOBAL_FLAGS "-DSWIGWORDSIZE64" ) +endif() + +set(SIMPLEITK_WRAPPING_COMMON_DIR + ${SimpleITK_SOURCE_DIR}/Wrapping/Common) + +set ( CMAKE_SWIG_GLOBAL_FLAGS -I${SIMPLEITK_WRAPPING_COMMON_DIR} ${CMAKE_SWIG_GLOBAL_FLAGS} ) + +include(sitkExtras) +include(sitkStripOption) +include(sitkForbidDownloadsOption) diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index 7ceedc45a..91dd86ac9 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -1,52 +1,6 @@ -if(POLICY CMP0026) - # Allow use of the LOCATION target property. - # - # These locations are use in a convoluted fashion with the runtime - # configuration. This system should be refactored to support - # generator expression. This would allow the use of the new policy. - cmake_policy(SET CMP0026 OLD) -endif() -# -# General SWIG configuration -# -if ( WRAP_LUA OR WRAP_PYTHON OR WRAP_JAVA OR WRAP_CSHARP OR WRAP_TCL OR WRAP_R OR WRAP_RUBY ) - find_package ( SWIG 2 REQUIRED ) - - include (UseSWIGLocal) - - file(GLOB SWIG_EXTRA_DEPS - "${SimpleITK_SOURCE_DIR}/Code/Common/include/*.h" - "${SimpleITK_SOURCE_DIR}/Code/Registration/include/*.h" - "${SimpleITK_SOURCE_DIR}/Code/IO/include/*.h") - - # make a manual list of dependencies for the Swig.i files - list( APPEND SWIG_EXTRA_DEPS "${SimpleITK_BINARY_DIR}/Code/BasicFilters/include/SimpleITKBasicFiltersGeneratedHeaders.i" - "${SimpleITK_BINARY_DIR}/Code/BasicFilters/include/SimpleITKBasicFiltersGeneratedHeaders.h" - ${SimpleITKBasicFiltersGeneratedHeader} - ) - - # check if uint64_t is the same as unsigned long - try_compile(SITK_ULONG_SAME_AS_UINT64 - ${SimpleITK_BINARY_DIR}/CMakeTmp - ${SimpleITK_SOURCE_DIR}/CMake/same_uint64_ulong.cxx ) - - # when "-DSWIGWORDSIZE64" is defined SWIG used unsigned long for uint64_t types - if(${SITK_ULONG_SAME_AS_UINT64} ) - set ( CMAKE_SWIG_GLOBAL_FLAGS "-DSWIGWORDSIZE64" ) - endif() - - set(SIMPLEITK_WRAPPING_COMMON_DIR - ${SimpleITK_SOURCE_DIR}/Wrapping/Common) - -set ( CMAKE_SWIG_GLOBAL_FLAGS -I${SIMPLEITK_WRAPPING_COMMON_DIR} ${CMAKE_SWIG_GLOBAL_FLAGS} ) - -endif() - - # A general packaging target, not built by default, to build packages for each # language. This should depend on all language specific targets. -add_custom_target( dist cmake -E echo "Finished generating wrapped packages for distribution..." ) # diff --git a/Wrapping/CSharp/CMakeLists.txt b/Wrapping/CSharp/CMakeLists.txt index cadc54ba0..b2cc7f820 100644 --- a/Wrapping/CSharp/CMakeLists.txt +++ b/Wrapping/CSharp/CMakeLists.txt @@ -1,3 +1,9 @@ +cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) + +project( SimpleITK_CSharp ) + +include(../../CMake/sitkProjectLanguageCommon.cmake) + # Find C# find_package( CSharp REQUIRED ) @@ -8,27 +14,27 @@ set_source_files_properties ( SimpleITK.i PROPERTIES CPLUSPLUS ON ) # CSharp version requirements: http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.aspx # major.minor[.build[.revision]] where all components are 16-bit unsigned integers set(_build 0) -if(DEFINED SimpleITK_VERSION_POST) +if(DEFINED SimpleITK_VERSION_POST AND NOT "${SimpleITK_VERSION_POST}" STREQUAL "") math(EXPR _build "${SimpleITK_VERSION_POST}") - elseif(DEFINED SimpleITK_VERSION_DEV) - math(EXPR _build "32768+${SimpleITK_VERSION_DEV}") - endif() - if(_build GREATER 65535) - message(WARNING "CSharp build component overflowed, setting to 65535 instead of ${_build}.") - set(_build 65535) - endif() +elseif(DEFINED SimpleITK_VERSION_DEV AND NOT "${SimpleITK_VERSION_DEV}" STREQUAL "") + math(EXPR _build "32768+${SimpleITK_VERSION_DEV}") +endif() +if(_build GREATER 65535) + message(WARNING "CSharp build component overflowed, setting to 65535 instead of ${_build}.") + set(_build 65535) +endif() - set(_revision 0) - if(DEFINED SimpleITK_VERSION_PATCH) - math(EXPR _revision "${SimpleITK_VERSION_PATCH}<<8") - if(DEFINED SimpleITK_VERSION_TWEAK) - math(EXPR _revision "_revision+${SimpleITK_VERSION_TWEAK}") - endif() - endif() - if(_revision GREATER 65535) - message(WARNING "CSharp revision component overflowed, setting to 65535 instead of ${_revision}.") - set(_revision 65535) +set(_revision 0) +if(DEFINED SimpleITK_VERSION_PATCH) + math(EXPR _revision "${SimpleITK_VERSION_PATCH}<<8") + if(DEFINED SimpleITK_VERSION_TWEAK) + math(EXPR _revision "${_revision}+${SimpleITK_VERSION_TWEAK}") endif() +endif() +if(_revision GREATER 65535) + message(WARNING "CSharp revision component overflowed, setting to 65535 instead of ${_revision}.") + set(_revision 65535) +endif() set(SimpleITK_VERSION_CSHARP_AssemblyVersion "${SimpleITK_VERSION_MAJOR}.${SimpleITK_VERSION_MINOR}.${_build}.${_revision}") diff --git a/Wrapping/CSharp/dist/CMakeLists.txt b/Wrapping/CSharp/dist/CMakeLists.txt index 154c28bd7..562f26404 100644 --- a/Wrapping/CSharp/dist/CMakeLists.txt +++ b/Wrapping/CSharp/dist/CMakeLists.txt @@ -2,7 +2,7 @@ # # CSharp Packaging # -if( WRAP_CSHARP AND Java_JAR_EXECUTABLE ) +if( Java_JAR_EXECUTABLE ) set(_files "") list( APPEND _files diff --git a/Wrapping/Java/CMakeLists.txt b/Wrapping/Java/CMakeLists.txt index 72c4a555f..6e2c47be5 100644 --- a/Wrapping/Java/CMakeLists.txt +++ b/Wrapping/Java/CMakeLists.txt @@ -1,3 +1,9 @@ +cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) + +project( SimpleITK_Java ) + +include(../../CMake/sitkProjectLanguageCommon.cmake) + find_package ( Java REQUIRED ) find_package ( JNI REQUIRED ) include_directories ( ${JAVA_INCLUDE_PATH} ${JNI_INCLUDE_DIRS} ) diff --git a/Wrapping/Java/dist/CMakeLists.txt b/Wrapping/Java/dist/CMakeLists.txt index afbfcf33d..e3793e32b 100644 --- a/Wrapping/Java/dist/CMakeLists.txt +++ b/Wrapping/Java/dist/CMakeLists.txt @@ -5,9 +5,9 @@ set(_files "") list( APPEND _files ${SimpleITK_DOC_FILES} - ${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE} - ${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAVA_SOURCE_FILE} - ${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAVADOC_FILE} + ${SimpleITK_Java_BINARY_DIR}/${JAR_FILE} + ${SimpleITK_Java_BINARY_DIR}/${JAVA_SOURCE_FILE} + ${SimpleITK_Java_BINARY_DIR}/${JAVADOC_FILE} ) if(NOT DEFINED SIMPLEITK_JAVA_ARCH) diff --git a/Wrapping/Lua/CMakeLists.txt b/Wrapping/Lua/CMakeLists.txt index 37f3660d8..93dec564f 100644 --- a/Wrapping/Lua/CMakeLists.txt +++ b/Wrapping/Lua/CMakeLists.txt @@ -1,9 +1,22 @@ +cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) + +project( SimpleITK_Lua ) + +include(../../CMake/sitkProjectLanguageCommon.cmake) + if (CMAKE_VERSION VERSION_LESS "3") - find_package ( Lua51 REQUIRED ) + find_package ( Lua51 ${_QUIET} ) + if ( NOT LUA_FOUND ) + find_package ( Lua50 ${_QUIET} ) + endif() else() - find_package ( Lua REQUIRED ) + find_package ( Lua ${_QUIET} ) endif() + +set( LUA_ADDITIONAL_LIBRARIES "" CACHE STRING "Additional libraries which may be needed for lua such as readline.") +mark_as_advanced( LUA_ADDITIONAL_LIBRARIES ) + include_directories ( ${LUA_INCLUDE_DIR} ) set_source_files_properties ( SimpleITK.i PROPERTIES CPLUSPLUS ON ) diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index 34d72f78e..24cde4230 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -1,7 +1,27 @@ +cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) + +project( SimpleITK_Python ) + + +if(POLICY CMP0026) + # Allow use of the LOCATION target property. + # + # These locations are use in a convoluted fashion with the runtime + # configuration. This system should be refactored to support + # generator expression. This would allow the use of the new policy. + cmake_policy(SET CMP0026 OLD) +endif() + +include(../../CMake/sitkProjectLanguageCommon.cmake) + + find_package ( PythonLibs REQUIRED ) find_package ( PythonInterp REQUIRED ) include_directories ( ${PYTHON_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ) +# +# Options +# option ( SimpleITK_PYTHON_THREADS "Enable threaded python usage by unlocking the GIL." ON ) mark_as_advanced( SimpleITK_PYTHON_THREADS ) option ( SimpleITK_PYTHON_EGG "Add building of python eggs to the dist target." ON ) @@ -100,7 +120,7 @@ if (SITK_PYTHON_USE_VIRTUALENV) # # Setup Python Virtual Enviroment for testing and packaging # - set( PythonVirtualenvHome "${SimpleITK_BINARY_DIR}/Testing/Installation/PythonVirtualenv" ) + set( PythonVirtualenvHome "${${CMAKE_PROJECT_NAME}_BINARY_DIR}/Testing/Installation/PythonVirtualenv" ) # virtualenv places the python executable in different # locations. Also note than on windows installations where python is diff --git a/Wrapping/R/CMakeLists.txt b/Wrapping/R/CMakeLists.txt index c73ac9a90..da8593aab 100644 --- a/Wrapping/R/CMakeLists.txt +++ b/Wrapping/R/CMakeLists.txt @@ -1,3 +1,18 @@ +cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) + +project( SimpleITK_R ) + +if(POLICY CMP0026) + # Allow use of the LOCATION target property. + # + # These locations are use in a convoluted fashion with the runtime + # configuration. This system should be refactored to support + # generator expression. This would allow the use of the new policy. + cmake_policy(SET CMP0026 OLD) +endif() + +include(../../CMake/sitkProjectLanguageCommon.cmake) + find_package ( R REQUIRED ) include_directories ( ${R_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/Wrapping/Ruby/CMakeLists.txt b/Wrapping/Ruby/CMakeLists.txt index 5ab1d8e0d..bc959d75c 100644 --- a/Wrapping/Ruby/CMakeLists.txt +++ b/Wrapping/Ruby/CMakeLists.txt @@ -1,3 +1,8 @@ +cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) + +project( SimpleITK_Lua ) + +include(../../CMake/sitkProjectLanguageCommon.cmake) find_package( Ruby REQUIRED ) include_directories( ${RUBY_INCLUDE_DIRS} ) diff --git a/Wrapping/Tcl/CMakeLists.txt b/Wrapping/Tcl/CMakeLists.txt index bdc686bff..6dcfc268c 100644 --- a/Wrapping/Tcl/CMakeLists.txt +++ b/Wrapping/Tcl/CMakeLists.txt @@ -1,3 +1,8 @@ +cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) + +project( SimpleITK_TCL ) + +include(../../CMake/sitkProjectLanguageCommon.cmake) find_package ( TCL REQUIRED ) include_directories ( ${TCL_INCLUDE_PATH} ) From 99870b2df6621a27d6abdb41702b83da7bb0dece Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 31 Mar 2016 13:15:41 -0400 Subject: [PATCH 188/412] Moved location of CMake sitk_target_link_libraries_with_dynamic_lookup Consolidated needed try_compile test, CheckUndefinedSymbolsAllowes, with function into a single file. Change-Id: Ica703e35b04d10d5be9f5e6b4654e4ce80de2043 --- CMake/sitkExtras.cmake | 30 ----------------- ...argetLinkLibrariesWithDynamicLookup.cmake} | 33 +++++++++++++++++++ 2 files changed, 33 insertions(+), 30 deletions(-) delete mode 100644 CMake/sitkExtras.cmake rename CMake/{sitkCheckUndefinedSymbolsAllowed.cmake => sitkTargetLinkLibrariesWithDynamicLookup.cmake} (56%) diff --git a/CMake/sitkExtras.cmake b/CMake/sitkExtras.cmake deleted file mode 100644 index 110c7ecf3..000000000 --- a/CMake/sitkExtras.cmake +++ /dev/null @@ -1,30 +0,0 @@ - -# -# Link a library to a target such that the symbols are resolved at -# run-time not link-time. This should be used when compiling a -# loadable module when the symbols should be resolve from the run-time -# environment where the module is loaded, and not a specific system -# library. -# -# Specifically, for OSX it uses undefined dynamic_lookup. This is -# simular to using "-shared" on Linux where undefined symbols are -# ignored. -# -# Additionally, the linker is checked to see if it supports undefined -# symbols when linking a shared library. If it does then the library -# is not linked when specified with this function. -# -# http://blog.tim-smith.us/2015/09/python-extension-modules-os-x/ -# - -include(sitkCheckUndefinedSymbolsAllowed) - -macro( sitk_target_link_libraries_with_dynamic_lookup target ) - if ( ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" ) - set_target_properties( ${target} PROPERTIES LINK_FLAGS "-undefined dynamic_lookup" ) - elseif(SITK_UNDEFINED_SYMBOLS_ALLOWED) - # linker allows undefined symbols, let's just not link - else() - target_link_libraries ( ${target} ${ARGN} ) - endif() -endmacro() diff --git a/CMake/sitkCheckUndefinedSymbolsAllowed.cmake b/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake similarity index 56% rename from CMake/sitkCheckUndefinedSymbolsAllowed.cmake rename to CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake index ea646b5c6..e3d0e5385 100644 --- a/CMake/sitkCheckUndefinedSymbolsAllowed.cmake +++ b/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake @@ -1,4 +1,27 @@ # +# - This module provides the function +# sitk_target_link_libraries_with_dynamic_lookup which can be used to +# "weakly" link loadable module. +# +# Link a library to a target such that the symbols are resolved at +# run-time not link-time. This should be used when compiling a +# loadable module when the symbols should be resolve from the run-time +# environment where the module is loaded, and not a specific system +# library. +# +# Specifically, for OSX it uses undefined dynamic_lookup. This is +# simular to using "-shared" on Linux where undefined symbols are +# ignored. +# +# Additionally, the linker is checked to see if it supports undefined +# symbols when linking a shared library. If it does then the library +# is not linked when specified with this function. +# +# http://blog.tim-smith.us/2015/09/python-extension-modules-os-x/ +# + +# Function: _sitkCheckUndefinedSymbolsAllowed +# # Check if the linker allows undefined symbols for shared libraries. # # SITK_UNDEFINED_SYMBOLS_ALLOWED - true if the linker will allow @@ -57,3 +80,13 @@ int foo(void) {return bar()+1;} endfunction() _sitkCheckUndefinedSymbolsAllowed() + +macro( sitk_target_link_libraries_with_dynamic_lookup target ) + if ( ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" ) + set_target_properties( ${target} PROPERTIES LINK_FLAGS "-undefined dynamic_lookup" ) + elseif(SITK_UNDEFINED_SYMBOLS_ALLOWED) + # linker allows undefined symbols, let's just not link + else() + target_link_libraries ( ${target} ${ARGN} ) + endif() +endmacro() From 12c09dc030c9921c9e0d3e3df8179a8645238e2c Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 31 Mar 2016 13:15:41 -0400 Subject: [PATCH 189/412] Moved location of CMake sitk_target_link_libraries_with_dynamic_lookup Consolidated needed try_compile test, CheckUndefinedSymbolsAllowes, with function into a single file. Change-Id: Ica703e35b04d10d5be9f5e6b4654e4ce80de2043 --- CMake/sitkExtras.cmake | 30 ----------------- ...argetLinkLibrariesWithDynamicLookup.cmake} | 33 +++++++++++++++++++ CMakeLists.txt | 2 +- 3 files changed, 34 insertions(+), 31 deletions(-) delete mode 100644 CMake/sitkExtras.cmake rename CMake/{sitkCheckUndefinedSymbolsAllowed.cmake => sitkTargetLinkLibrariesWithDynamicLookup.cmake} (56%) diff --git a/CMake/sitkExtras.cmake b/CMake/sitkExtras.cmake deleted file mode 100644 index 110c7ecf3..000000000 --- a/CMake/sitkExtras.cmake +++ /dev/null @@ -1,30 +0,0 @@ - -# -# Link a library to a target such that the symbols are resolved at -# run-time not link-time. This should be used when compiling a -# loadable module when the symbols should be resolve from the run-time -# environment where the module is loaded, and not a specific system -# library. -# -# Specifically, for OSX it uses undefined dynamic_lookup. This is -# simular to using "-shared" on Linux where undefined symbols are -# ignored. -# -# Additionally, the linker is checked to see if it supports undefined -# symbols when linking a shared library. If it does then the library -# is not linked when specified with this function. -# -# http://blog.tim-smith.us/2015/09/python-extension-modules-os-x/ -# - -include(sitkCheckUndefinedSymbolsAllowed) - -macro( sitk_target_link_libraries_with_dynamic_lookup target ) - if ( ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" ) - set_target_properties( ${target} PROPERTIES LINK_FLAGS "-undefined dynamic_lookup" ) - elseif(SITK_UNDEFINED_SYMBOLS_ALLOWED) - # linker allows undefined symbols, let's just not link - else() - target_link_libraries ( ${target} ${ARGN} ) - endif() -endmacro() diff --git a/CMake/sitkCheckUndefinedSymbolsAllowed.cmake b/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake similarity index 56% rename from CMake/sitkCheckUndefinedSymbolsAllowed.cmake rename to CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake index ea646b5c6..e3d0e5385 100644 --- a/CMake/sitkCheckUndefinedSymbolsAllowed.cmake +++ b/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake @@ -1,4 +1,27 @@ # +# - This module provides the function +# sitk_target_link_libraries_with_dynamic_lookup which can be used to +# "weakly" link loadable module. +# +# Link a library to a target such that the symbols are resolved at +# run-time not link-time. This should be used when compiling a +# loadable module when the symbols should be resolve from the run-time +# environment where the module is loaded, and not a specific system +# library. +# +# Specifically, for OSX it uses undefined dynamic_lookup. This is +# simular to using "-shared" on Linux where undefined symbols are +# ignored. +# +# Additionally, the linker is checked to see if it supports undefined +# symbols when linking a shared library. If it does then the library +# is not linked when specified with this function. +# +# http://blog.tim-smith.us/2015/09/python-extension-modules-os-x/ +# + +# Function: _sitkCheckUndefinedSymbolsAllowed +# # Check if the linker allows undefined symbols for shared libraries. # # SITK_UNDEFINED_SYMBOLS_ALLOWED - true if the linker will allow @@ -57,3 +80,13 @@ int foo(void) {return bar()+1;} endfunction() _sitkCheckUndefinedSymbolsAllowed() + +macro( sitk_target_link_libraries_with_dynamic_lookup target ) + if ( ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" ) + set_target_properties( ${target} PROPERTIES LINK_FLAGS "-undefined dynamic_lookup" ) + elseif(SITK_UNDEFINED_SYMBOLS_ALLOWED) + # linker allows undefined symbols, let's just not link + else() + target_link_libraries ( ${target} ${ARGN} ) + endif() +endmacro() diff --git a/CMakeLists.txt b/CMakeLists.txt index fbf470117..68c060671 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -56,7 +56,7 @@ find_package(ITK REQUIRED ) #we require certain packages be turned on in ITK include(sitkCheckForITKModuleDependencies) -include(sitkExtras) +include(sitkTargetLinkLibrariesWithDynamicLookup) if(ITK_FOUND) From 9f9c26c9411f0170669723cd9582f7b87a767c92 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 1 Apr 2016 09:11:54 -0400 Subject: [PATCH 190/412] Update name of CMake file for linking with dynamic lookup Change-Id: I6c8b6ac4e6d55b8cf76fede232eba806ddda158b --- CMake/sitkProjectLanguageCommon.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMake/sitkProjectLanguageCommon.cmake b/CMake/sitkProjectLanguageCommon.cmake index a91fd3a6b..fe179050a 100644 --- a/CMake/sitkProjectLanguageCommon.cmake +++ b/CMake/sitkProjectLanguageCommon.cmake @@ -70,6 +70,6 @@ set(SIMPLEITK_WRAPPING_COMMON_DIR set ( CMAKE_SWIG_GLOBAL_FLAGS -I${SIMPLEITK_WRAPPING_COMMON_DIR} ${CMAKE_SWIG_GLOBAL_FLAGS} ) -include(sitkExtras) +include(sitkTargetLinkLibrariesWithDynamicLookup) include(sitkStripOption) include(sitkForbidDownloadsOption) From 910aaaf555db0997a1d223ca429e9d907cdc4960 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 1 Apr 2016 10:21:44 -0400 Subject: [PATCH 191/412] Explicitly use required ITK modules This reduces the number of include while building some SimpleITK libraries. Change-Id: I9e981a3f4fd9dc3ce2feb94223f6b8f9314ff134 --- Code/Common/src/CMakeLists.txt | 2 ++ Code/Explicit/src/CMakeLists.txt | 2 ++ Code/IO/src/CMakeLists.txt | 9 +++++++++ Code/Registration/src/CMakeLists.txt | 1 + 4 files changed, 14 insertions(+) diff --git a/Code/Common/src/CMakeLists.txt b/Code/Common/src/CMakeLists.txt index 0893afd25..bebb12252 100644 --- a/Code/Common/src/CMakeLists.txt +++ b/Code/Common/src/CMakeLists.txt @@ -29,6 +29,8 @@ set ( SimpleITKCommonSource ) set ( ITK_NO_IO_FACTORY_REGISTER_MANAGER 1 ) +find_package(ITK COMPONENTS ITKCommon ITKImageCompose + ITKImageIntensity ITKLabelMap ITKTransform ITKIOTransformBase ITKDisplacementField REQUIRED) include(${ITK_USE_FILE}) add_library ( SimpleITKCommon ${SimpleITKCommonSource} ${SimpleITKAncillarySource} ) diff --git a/Code/Explicit/src/CMakeLists.txt b/Code/Explicit/src/CMakeLists.txt index 4e15a980a..befea99dc 100644 --- a/Code/Explicit/src/CMakeLists.txt +++ b/Code/Explicit/src/CMakeLists.txt @@ -23,6 +23,8 @@ set ( SimpleITKExplicitSource # these files are the instantiated ITK filter, but they do not do IO, # so we don't need to register the IO factoried here. set ( ITK_NO_IO_FACTORY_REGISTER_MANAGER 1 ) + +find_package(ITK COMPONENTS ITKCommon ITKImageCompose ITKImageIntensity ITKLabelMap REQUIRED) include(${ITK_USE_FILE}) if ( MSVC AND SITK_BUILD_SHARED_LIBS ) diff --git a/Code/IO/src/CMakeLists.txt b/Code/IO/src/CMakeLists.txt index 8538d1cf9..ec131c89e 100644 --- a/Code/IO/src/CMakeLists.txt +++ b/Code/IO/src/CMakeLists.txt @@ -11,6 +11,15 @@ set( SimpleITKIOSource include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ) +set(REQUIRED_ITK_MODULES ITKCommon ITKLabelMap ITKImageCompose + ITKImageIntensity ITKIOImageBase ITKIOTransformBase ITKIOGDCM ) +foreach( mod IN LISTS ITK_MODULES_ENABLED) + if( ${mod} MATCHES "IO") + list(APPEND REQUIRED_ITK_MODULES ${mod}) + endif() +endforeach() + +find_package(ITK COMPONENTS REQUIRED) include(${ITK_USE_FILE}) add_library ( SimpleITKIO ${SimpleITKIOSource} ) diff --git a/Code/Registration/src/CMakeLists.txt b/Code/Registration/src/CMakeLists.txt index b9dd65bed..c80142d24 100644 --- a/Code/Registration/src/CMakeLists.txt +++ b/Code/Registration/src/CMakeLists.txt @@ -10,6 +10,7 @@ include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ) # these files are the instantiated ITK filter, but they do not do IO, # so we don't need to register the IO factories here. set ( ITK_NO_IO_FACTORY_REGISTER_MANAGER 1 ) +find_package(ITK COMPONENTS ITKCommon ITKLabelMap ITKOptimizersv4 ITKMetricsv4 ITKRegistrationMethodsv4 REQUIRED) include(${ITK_USE_FILE}) add_library ( SimpleITKRegistration ${SimpleITKRegistration} ) From 2c4d338ecaa790e7901ea19d62f09945f13e30b1 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 1 Apr 2016 10:34:36 -0400 Subject: [PATCH 192/412] Update Superbuild download URLs to use https Change-Id: Iaa36839a8b52b753e9853705664801e81b88c0a5 --- SuperBuild/External_GTest.cmake | 2 +- SuperBuild/External_Lua.cmake | 2 +- SuperBuild/External_PCRE.cmake | 2 +- SuperBuild/External_Swig.cmake | 4 ++-- SuperBuild/External_virtualenv.cmake | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/SuperBuild/External_GTest.cmake b/SuperBuild/External_GTest.cmake index 9591218e9..718356d05 100644 --- a/SuperBuild/External_GTest.cmake +++ b/SuperBuild/External_GTest.cmake @@ -43,7 +43,7 @@ endif() ExternalProject_Add(${proj} - URL http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${GTEST_DOWNLOAD_SOURCE_HASH}&name=swig-${GTEST_TARGET_VERSION}.zip + URL https://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${GTEST_DOWNLOAD_SOURCE_HASH}&name=swig-${GTEST_TARGET_VERSION}.zip URL_MD5 ${GTEST_DOWNLOAD_SOURCE_HASH} INSTALL_DIR ${GTEST_install_dir} CMAKE_GENERATOR ${gen} diff --git a/SuperBuild/External_Lua.cmake b/SuperBuild/External_Lua.cmake index a59ac738d..b1e9bee13 100644 --- a/SuperBuild/External_Lua.cmake +++ b/SuperBuild/External_Lua.cmake @@ -21,7 +21,7 @@ set(lua_PATCH_COMMAND ${CMAKE_COMMAND} -E copy_if_different ) ExternalProject_Add(Lua - URL http://www.lua.org/ftp/lua-5.1.5.tar.gz + URL https://www.lua.org/ftp/lua-5.1.5.tar.gz URL_MD5 2e115fe26e435e33b0d5c022e4490567 PATCH_COMMAND ${lua_PATCH_COMMAND} CMAKE_GENERATOR ${gen} diff --git a/SuperBuild/External_PCRE.cmake b/SuperBuild/External_PCRE.cmake index 3044cb937..1b4fb2b8c 100644 --- a/SuperBuild/External_PCRE.cmake +++ b/SuperBuild/External_PCRE.cmake @@ -35,7 +35,7 @@ if(NOT PCRE_DIR) set ( pcre_CONFIGURE_COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/pcre_configure_step.cmake ) ExternalProject_add(PCRE - URL http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${PCRE_DOWNLOAD_SOURCE_HASH}&name=pcre-${PCRE_TARGET_VERSION}.tar.gz + URL https://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${PCRE_DOWNLOAD_SOURCE_HASH}&name=pcre-${PCRE_TARGET_VERSION}.tar.gz URL_MD5 "${PCRE_DOWNLOAD_SOURCE_HASH}" CONFIGURE_COMMAND ${pcre_CONFIGURE_COMMAND} DEPENDS "${PCRE_DEPENDENCIES}" diff --git a/SuperBuild/External_Swig.cmake b/SuperBuild/External_Swig.cmake index a70638ba5..b6ef3129b 100644 --- a/SuperBuild/External_Swig.cmake +++ b/SuperBuild/External_Swig.cmake @@ -26,7 +26,7 @@ if(NOT SWIG_DIR) # swig.exe available as pre-built binary on Windows: ExternalProject_Add(Swig - URL http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${SWIG_DOWNLOAD_WIN_HASH}&name=swigwin-${SWIG_TARGET_VERSION}.zip + URL https://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${SWIG_DOWNLOAD_WIN_HASH}&name=swigwin-${SWIG_TARGET_VERSION}.zip URL_MD5 ${SWIG_DOWNLOAD_WIN_HASH} SOURCE_DIR ${CMAKE_CURRENT_BINARY_DIR}/swigwin-${SWIG_TARGET_VERSION} CONFIGURE_COMMAND "" @@ -74,7 +74,7 @@ if(NOT SWIG_DIR) ExternalProject_add(Swig - URL http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${SWIG_DOWNLOAD_SOURCE_HASH}&name=swig-${SWIG_TARGET_VERSION}.tar.gz + URL https://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${SWIG_DOWNLOAD_SOURCE_HASH}&name=swig-${SWIG_TARGET_VERSION}.tar.gz URL_MD5 ${SWIG_DOWNLOAD_SOURCE_HASH} CONFIGURE_COMMAND ${swig_CONFIGURE_COMMAND} DEPENDS "${Swig_DEPENDENCIES}" diff --git a/SuperBuild/External_virtualenv.cmake b/SuperBuild/External_virtualenv.cmake index b3ec4ce43..645af579c 100644 --- a/SuperBuild/External_virtualenv.cmake +++ b/SuperBuild/External_virtualenv.cmake @@ -18,7 +18,7 @@ set(${proj}_install_dir ${CMAKE_CURRENT_BINARY_DIR}/${proj}) ExternalProject_Add(${proj} - URL http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${${proj}_DOWNLOAD_SOURCE_HASH}&name=virtualenv-${${proj}_TARGET_VERSION}.tar.gz + URL https://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${${proj}_DOWNLOAD_SOURCE_HASH}&name=virtualenv-${${proj}_TARGET_VERSION}.tar.gz URL_MD5 ${${proj}_DOWNLOAD_SOURCE_HASH} SOURCE_DIR ${${proj}_source_dir} BINARY_DIR ${${proj}_binary_dir} From 03af20372387e5f8d83d9e1944c14c1662fbd216 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 1 Apr 2016 10:35:06 -0400 Subject: [PATCH 193/412] Update upload data script to use https Change-Id: I08a38d392edc7d863476aefbdf16052276ace1f3 --- Utilities/UploadBinaryData.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Utilities/UploadBinaryData.py b/Utilities/UploadBinaryData.py index 87f84ea66..a8cab39fc 100755 --- a/Utilities/UploadBinaryData.py +++ b/Utilities/UploadBinaryData.py @@ -23,7 +23,7 @@ The Midas server at - http://midas3.kitware.com/midas/ + https://midas3.kitware.com/midas/ is an ITK community resource where any community member can upload binary data files. This script automates the upload of data to the server and generation of @@ -53,7 +53,7 @@ def connect_to_midas(email=None, api_key=None): - midas_url = 'http://midas3.kitware.com/midas/' + midas_url = 'https://midas3.kitware.com/midas/' #pydas.login(url=midas_url, email=email, api_key=api_key) try: pydas.login(url=midas_url, email=email, api_key=api_key) From 4b483eacd276ecce9094927398a7022ac7e3440c Mon Sep 17 00:00:00 2001 From: Ziv Yaniv Date: Mon, 4 Apr 2016 15:24:54 -0400 Subject: [PATCH 194/412] Adding test for BSplineTransformInitializer. BSplineTransformInitializer is expected to ignore the given image's requested region which it does not. Change-Id: If2cc3cda41cccab8e425b29a6e9431a84a1cffce --- Testing/Unit/sitkBasicFiltersTests.cxx | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Testing/Unit/sitkBasicFiltersTests.cxx b/Testing/Unit/sitkBasicFiltersTests.cxx index af8ff1606..f17d1b264 100644 --- a/Testing/Unit/sitkBasicFiltersTests.cxx +++ b/Testing/Unit/sitkBasicFiltersTests.cxx @@ -496,6 +496,36 @@ TEST(BasicFilters,BSplineTransformInitializer) { EXPECT_VECTOR_DOUBLE_NEAR( outTx.TransformPoint( v3(1.123,0.0,2.0) ), v3(1.123,0.0,2.0), 1e-17); EXPECT_VECTOR_DOUBLE_NEAR( outTx.TransformPoint( v3(0.0,0.0,5.0) ), v3(0.0,0.0,5.0), 1e-17); EXPECT_VECTOR_DOUBLE_NEAR( outTx.TransformPoint( v3(5.0,7.0,9.0) ), v3(5.0,7.0,9.0), 1e-17); + + //check that changing the image's requested region does not change + //the BSplineTransformInitializer + img = sitk::Image( 482, 360, 141, sitk::sitkFloat32 ); + img.SetSpacing( v3(0.97656, 0.97656, 2) ); + std::vector extractSize(3); + extractSize[0] = 482; + extractSize[1] = 0; + extractSize[2] = 141; + std::vector extractIndex(3); + extractIndex[0] = 0; + extractIndex[1] = 176; + extractIndex[2] = 0; + + std::vector transformDomainMeshSize(3); + transformDomainMeshSize[0] = 9; + transformDomainMeshSize[1] = 7; + transformDomainMeshSize[2] = 6; + sitk::BSplineTransform transformBefore(3), transformAfter(3); + transformBefore = sitk::BSplineTransformInitializer( img, transformDomainMeshSize ); + + sitk::Extract(img, extractSize, extractIndex); + + transformAfter = sitk::BSplineTransformInitializer( img, transformDomainMeshSize ); + + //the extract filter should not have any effect on the + //BSplineTransformInitializer, it only changed the image's + //requested region + EXPECT_VECTOR_DOUBLE_NEAR( transformBefore.GetTransformDomainPhysicalDimensions(), transformAfter.GetTransformDomainPhysicalDimensions(), 1e-17 ); + EXPECT_VECTOR_DOUBLE_NEAR( transformBefore.GetTransformDomainOrigin(), transformAfter.GetTransformDomainOrigin(), 1e-17 ); } From e86dcda20bef035ea316086023c4cd6c3543866d Mon Sep 17 00:00:00 2001 From: Ziv Yaniv Date: Mon, 4 Apr 2016 16:18:06 -0400 Subject: [PATCH 195/412] Separated the BSplineTransformInitializer test in two. Separated the test with regard to requested region from the previous test. Change-Id: I3f7bc2f30e61eb64f843d772a46cf6fc99c4e558 --- Testing/Unit/sitkBasicFiltersTests.cxx | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Testing/Unit/sitkBasicFiltersTests.cxx b/Testing/Unit/sitkBasicFiltersTests.cxx index f17d1b264..6070f59cf 100644 --- a/Testing/Unit/sitkBasicFiltersTests.cxx +++ b/Testing/Unit/sitkBasicFiltersTests.cxx @@ -497,9 +497,14 @@ TEST(BasicFilters,BSplineTransformInitializer) { EXPECT_VECTOR_DOUBLE_NEAR( outTx.TransformPoint( v3(0.0,0.0,5.0) ), v3(0.0,0.0,5.0), 1e-17); EXPECT_VECTOR_DOUBLE_NEAR( outTx.TransformPoint( v3(5.0,7.0,9.0) ), v3(5.0,7.0,9.0), 1e-17); +} + +TEST(BasicFilters, BSplineTransformInitializerRequestedRegion) { + namespace sitk = itk::simple; + //check that changing the image's requested region does not change //the BSplineTransformInitializer - img = sitk::Image( 482, 360, 141, sitk::sitkFloat32 ); + sitk::Image img( 482, 360, 141, sitk::sitkFloat32 ); img.SetSpacing( v3(0.97656, 0.97656, 2) ); std::vector extractSize(3); extractSize[0] = 482; @@ -526,8 +531,8 @@ TEST(BasicFilters,BSplineTransformInitializer) { //requested region EXPECT_VECTOR_DOUBLE_NEAR( transformBefore.GetTransformDomainPhysicalDimensions(), transformAfter.GetTransformDomainPhysicalDimensions(), 1e-17 ); EXPECT_VECTOR_DOUBLE_NEAR( transformBefore.GetTransformDomainOrigin(), transformAfter.GetTransformDomainOrigin(), 1e-17 ); -} +} TEST(BasicFilters,CenteredTransformInitializer) { namespace sitk = itk::simple; From 5b530f63bfac5aa91005864d22450afc4a306bb4 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 31 Mar 2016 13:15:41 -0400 Subject: [PATCH 196/412] Replace sitkExtra with now TargetLink CMake module in top-level Change-Id: I817507d533cab0ecd06be20ac6da8b55c58168f1 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index fbf470117..68c060671 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -56,7 +56,7 @@ find_package(ITK REQUIRED ) #we require certain packages be turned on in ITK include(sitkCheckForITKModuleDependencies) -include(sitkExtras) +include(sitkTargetLinkLibrariesWithDynamicLookup) if(ITK_FOUND) From 2647c5665034b23dbac4ebb2ef7fa367430d716a Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Wed, 6 Apr 2016 10:31:40 +1000 Subject: [PATCH 197/412] R documentation from doxygen. Support for basic R documentation using a modification of the infrastructure for python docstrings. The conversion to .Rd files is far from perfect, as the doc structure doesn't match the OO style generated by Swig, but hopefully it is useful. There is one file per filter, with a .Rd suffix. They get dumped in Wrapping/R/Packaging/SimpleITK/man. I guess the files generated will be added to the repo, like the python docstrings, but I haven't done this yet. Future work is to provide some basic help for the procedural interface, at least giving signatures. However it appears this will need further (separate) parser customizations. Change-Id: I66a43794ca114b13b6cc72920a09b753e62209de --- Utilities/GenerateDocs/SwigDocUpdate.sh | 6 + Utilities/GenerateDocs/doxy2swig.py | 161 ++++++++++++++++++++++++ Utilities/GenerateDocs/doxyall.py | 51 +++++++- 3 files changed, 212 insertions(+), 6 deletions(-) diff --git a/Utilities/GenerateDocs/SwigDocUpdate.sh b/Utilities/GenerateDocs/SwigDocUpdate.sh index a2e520597..666078492 100755 --- a/Utilities/GenerateDocs/SwigDocUpdate.sh +++ b/Utilities/GenerateDocs/SwigDocUpdate.sh @@ -22,8 +22,14 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Load configuration variable from file . ${DIR}/config_vars.sh || die 'Unable to find local \"config_vars.sh\" configuration file.' + [ -e ${SITK_BUILD_DIR}/Documentation/xml/sitkImage_8h.xml ] || die "Uable to find SimpleITK Doxygen XML! SimpleITK Doxygen needs to be generated with the Documentation target!" ${PYTHON_EXECUTABLE} doxyall.py ${SITK_BUILD_DIR}/Documentation/xml/ ${SIMPLEITK}/Wrapping/Python/PythonDocstrings.i ${PYTHON_EXECUTABLE} doxyall.py -j ${SITK_BUILD_DIR}/Documentation/xml/ ${SIMPLEITK}/Wrapping/Java/JavaDoc.i + +if [ ! -d ${SIMPLEITK}/Wrapping/R/Packaging/SimpleITK/man/ ] ; then + mkdir -p ${SIMPLEITK}/Wrapping/R/Packaging/SimpleITK/man/ +fi +${PYTHON_EXECUTABLE} doxyall.py -r ${SITK_BUILD_DIR}/Documentation/xml/ ${SIMPLEITK}/Wrapping/R/Packaging/SimpleITK/man/ diff --git a/Utilities/GenerateDocs/doxy2swig.py b/Utilities/GenerateDocs/doxy2swig.py index 6ec25866f..c492fb85c 100755 --- a/Utilities/GenerateDocs/doxy2swig.py +++ b/Utilities/GenerateDocs/doxy2swig.py @@ -408,6 +408,167 @@ def clean_pieces(self, pieces): ret.extend([_tmp, '\n\n']) return ret +class Doxy2R(Doxy2SWIG): + def __init__(self, src, javaFlag=0): + Doxy2SWIG.__init__(self, src, javaFlag) + """ Turns on the title, brief description and detailed description markup. + Turn them off when inside member documentatation. + + """ + self.FilterTitle = True + self.sitkClassName='' + self.EmptyText = False + + def parse_Text(self, node): + txt = node.data + txt = txt.replace('\\', r'\\\\') + txt = txt.replace('"', r'\"') + # ignore pure whitespace + m = self.space_re.match(txt) + if m and len(m.group()) == len(txt): + # Flag the text being empty + self.EmptyText = True + pass + else: + self.add_text(textwrap.fill(txt)) + + + def do_compoundname(self, node): + self.add_text('\n\n') + data = node.firstChild.data + self.add_text('\\name{%s}\n'%data) + self.sitkClassName=data + + def do_compounddef(self, node): + kind = node.attributes['kind'].value + if kind in ('class', 'struct'): + prot = node.attributes['prot'].value + if prot != 'public': + return + names = ('compoundname', 'briefdescription', + 'detaileddescription', 'includes') + first = self.get_specific_nodes(node, names) + for n in names: + if n in first: + self.parse(first[n]) + for n in node.childNodes: + if n not in list(first.values()): + self.parse(n) + elif kind in ('file', 'namespace'): + nodes = node.getElementsByTagName('sectiondef') + for n in nodes: + self.parse(n) + + def do_includes(self, node): + self.add_text('%C++ includes: ') + self.generic_parse(node, pad=1) + + def do_detaileddescription(self, node): + if self.FilterTitle: + self.add_text('\\details{') + self.generic_parse(node, pad=1) + if self.FilterTitle: + # check that we actually got a detailed description. + # Not having a title is illegal in R + # use the class name otherwise + self.add_text('}\n') + def do_briefdescription(self, node): + # there are brief descriptions all over the place and + # we don't want them all to be titles + if self.FilterTitle: + self.add_text('\\description{') + self.generic_parse(node, pad=0) + if self.FilterTitle: + # if the title is empty, then we'll use the name + if self.EmptyText: + self.add_text(self.sitkClassName) + self.add_text('}\n') + self.EmptyText = False + + def do_memberdef(self, node): + prot = node.attributes['prot'].value + id = node.attributes['id'].value + kind = node.attributes['kind'].value + tmp = node.parentNode.parentNode.parentNode + compdef = tmp.getElementsByTagName('compounddef')[0] + cdef_kind = compdef.attributes['kind'].value + + self.FilterTitle = False; + + if prot == 'public': + first = self.get_specific_nodes(node, ('definition', 'name')) + name = first['name'].firstChild.data + if name[:8] == 'operator': # Don't handle operators yet. + return + + defn = first['definition'].firstChild.data + self.add_text('\n') + self.add_text('\\item{') + anc = node.parentNode.parentNode + # don't need to worry about documenting these in sitk + if cdef_kind in ('file', 'namespace'): + ns_node = anc.getElementsByTagName('innernamespace') + if not ns_node and cdef_kind == 'namespace': + ns_node = anc.getElementsByTagName('compoundname') + if ns_node: + ns = ns_node[0].firstChild.data + self.add_text('%s %s'%(name, defn)) + if self.java: + self.add_text(' %s::%s "/**\n%s'%(ns, name, defn)) + else: + self.add_text(' %s::%s "\n'%(ns, name)) + else: + self.add_text('YY %s TT %s'%(name, defn)) + if self.java: + self.add_text(' %s "/**\n%s'%(name, defn)) + else: + self.add_text(' %s "\n'%(name)) + ## everything will be a class + elif cdef_kind in ('class', 'struct'): + # Get the full function name. + anc_node = anc.getElementsByTagName('compoundname') + cname = anc_node[0].firstChild.data + argstring = node.getElementsByTagName('argsstring')[0] + arguments = argstring.firstChild.data + returnType = node.getElementsByTagName('type')[0] + if returnType.firstChild == None: + returnType = '' + else: + ## search through the return type - 2 levels should be enough + ## usually there's a link around it. + if returnType.firstChild.firstChild != None: + returnType = returnType.firstChild.firstChild.nodeValue + else: + returnType = returnType.firstChild.nodeValue + + self.add_text('%s %s%s'%(returnType, name, arguments)) + + for n in node.childNodes: + if n not in list(first.values()): + self.parse(n) + self.add_text('}\n') + self.FilterTitle=True; + + def do_sectiondef(self, node): + kind = node.attributes['kind'].value + if kind in ('public-func', 'func'): + self.add_text('\\arguments{\n') + self.generic_parse(node) + self.add_text('}\n') + + def do_doxygenindex(self, node): + self.multi = 1 + comps = node.getElementsByTagName('compound') + for c in comps: + refid = c.attributes['refid'].value + fname = refid + '.xml' + if not os.path.exists(fname): + fname = os.path.join(self.my_dir, fname) +# print "parsing file: %s"%fname + p = Doxy2R(fname) + p.generate() + self.pieces.extend(self.clean_pieces(p.pieces)) + def main(input, output): p = Doxy2SWIG(input) diff --git a/Utilities/GenerateDocs/doxyall.py b/Utilities/GenerateDocs/doxyall.py index 8b0d7cd24..e88ebac1a 100755 --- a/Utilities/GenerateDocs/doxyall.py +++ b/Utilities/GenerateDocs/doxyall.py @@ -6,17 +6,20 @@ def usage(): - print( "\ndoxyall.py [options] doxygen_xml_dir output.i" ) + print( "\ndoxyall.py [options] doxygen_xml_dir output.i|outputdir" ) print( "" ) print( " -h, --help This help message" ) print( " -j, --java Java style output" ) + print( " -r, --R R style output - destination must be a directory" ) + print( "" ) javaFlag = 0 +rFlag = 0 try: - opts, args = getopt.getopt(sys.argv[1:], "hj", [ "help", "java", ] ) + opts, args = getopt.getopt(sys.argv[1:], "hjr", [ "help", "java", "R" ] ) except getopt.GetoptErr, err: print( str(err) ) usage() @@ -28,6 +31,8 @@ def usage(): sys.exit() elif o in ("-j", "--java"): javaFlag = 1 + elif o in ("-r", "--R"): + rFlag = 1 else: assert False, "Unhandled option" @@ -39,6 +44,9 @@ def usage(): indir = args[0] outfile = args[1] +if rFlag: + outdir = args[1] + files = glob.glob(indir+"/*.xml") files.sort() @@ -47,7 +55,8 @@ def usage(): logfd, logfile = tempfile.mkstemp(suffix=".txt", prefix="doxyall.", text=True) -fout = open(outfile, "w") +if not rFlag: + fout = open(outfile, "w") flog = open(logfile, "w") @@ -63,10 +72,28 @@ def usage(): flog.write("Processing " + x + "\n") try: - p = Doxy2SWIG(x, javaFlag) + if (rFlag): + p = Doxy2R(x) + else: + p = Doxy2SWIG(x, javaFlag) + p.generate() p.write(tmpfile) + if (rFlag): + ThisClassName = p.sitkClassName; + # also exclude ones starting with detail or that are template instantiations + if ThisClassName.find("detail::") >=0 or ThisClassName.find("<") >=0: + continue + + ThisClassName = ThisClassName.replace("itk::simple::", "") + ThisClassName = ThisClassName.replace("itk::Functor::", "") + + outfile=outdir + "/" + ThisClassName + ".Rd" + fout = open(outfile, "w") + + + fin = open(tmpfile, "r") for line in fin: @@ -74,14 +101,26 @@ def usage(): line2 = line2.rstrip() fout.write(line2) fout.write('\n') - + if (rFlag): + ## Need to duplicate the name entry to alias + if line2.find("\\name{") >= 0: + line3=line2.replace("\\name{", "\\alias{") + line4=line2.replace("\\name{", "\\title{") + fout.write(line3) + fout.write('\n') + fout.write(line4) + fout.write('\n') + + if (rFlag): + fout.close() fin.close() except: flog.write( "Error on file " + x + "\n") print( "Error on file " + x + "\n") errorCount = errorCount+1 +if ( not rFlag): + fout.close() -fout.close() flog.close() os.close(tmpfd) From 6baf7beffc998e4d69133df87a78891ce7203d26 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 5 Apr 2016 15:24:54 -0400 Subject: [PATCH 198/412] Rename some CMake file with sitkPrefix This should help to prevent naming conflicts. Change-Id: Ia00f470fbcc04f1c4aa5993b4a685626a363650e --- CMake/PreventInSourceBuilds.cmake | 45 ------------------- ...e.cmake => sitkGenerateFilterSource.cmake} | 0 ...cmake => sitkPreventInBuildInstalls.cmake} | 0 CMake/sitkPreventInSourceBuilds.cmake | 18 ++++++++ Code/BasicFilters/CMakeLists.txt | 2 +- SuperBuild/SuperBuild.cmake | 4 +- 6 files changed, 21 insertions(+), 48 deletions(-) delete mode 100644 CMake/PreventInSourceBuilds.cmake rename CMake/{generate_filter_source.cmake => sitkGenerateFilterSource.cmake} (100%) rename CMake/{PreventInBuildInstalls.cmake => sitkPreventInBuildInstalls.cmake} (100%) create mode 100644 CMake/sitkPreventInSourceBuilds.cmake diff --git a/CMake/PreventInSourceBuilds.cmake b/CMake/PreventInSourceBuilds.cmake deleted file mode 100644 index 78f6b4e63..000000000 --- a/CMake/PreventInSourceBuilds.cmake +++ /dev/null @@ -1,45 +0,0 @@ -# -# This function will prevent in-source builds -function(AssureOutOfSourceBuilds) - # make sure the user doesn't play dirty with symlinks - get_filename_component(srcdir "${CMAKE_SOURCE_DIR}" REALPATH) - get_filename_component(bindir "${CMAKE_BINARY_DIR}" REALPATH) - - # disallow in-source builds - if("${srcdir}" STREQUAL "${bindir}") - message("######################################################") - message("# ITK should not be configured & built in the ITK source directory") - message("# You must run cmake in a build directory.") - message("# For example:") - message("# mkdir ITK-Sandbox ; cd ITK-sandbox") - message("# git clone git://itk.org/ITK.git # or download & unpack the source tarball") - message("# mkdir ITK-build") - message("# this will create the following directory structure") - message("#") - message("# ITK-Sandbox") - message("# +--ITK") - message("# +--ITK-build") - message("#") - message("# Then you can proceed to configure and build") - message("# by using the following commands") - message("#") - message("# cd ITK-build") - message("# cmake ../ITK # or ccmake, or cmake-gui ") - message("# make") - message("#") - message("# NOTE: Given that you already tried to make an in-source build") - message("# CMake have already created several files & directories") - message("# in your source tree. run 'git status' to find them and") - message("# remove them by doing:") - message("#") - message("# cd ITK-Sandbox/ITK") - message("# git clean -n -d") - message("# git clean -f -d") - message("# git checkout --") - message("#") - message("######################################################") - message(FATAL_ERROR "Quitting configuration") - endif() -endfunction() - -AssureOutOfSourceBuilds() diff --git a/CMake/generate_filter_source.cmake b/CMake/sitkGenerateFilterSource.cmake similarity index 100% rename from CMake/generate_filter_source.cmake rename to CMake/sitkGenerateFilterSource.cmake diff --git a/CMake/PreventInBuildInstalls.cmake b/CMake/sitkPreventInBuildInstalls.cmake similarity index 100% rename from CMake/PreventInBuildInstalls.cmake rename to CMake/sitkPreventInBuildInstalls.cmake diff --git a/CMake/sitkPreventInSourceBuilds.cmake b/CMake/sitkPreventInSourceBuilds.cmake new file mode 100644 index 000000000..a9cfdbb79 --- /dev/null +++ b/CMake/sitkPreventInSourceBuilds.cmake @@ -0,0 +1,18 @@ +# +# This function will prevent in-source builds +function(AssureOutOfSourceBuilds) + # make sure the user doesn't play dirty with symlinks + get_filename_component(srcdir "${CMAKE_SOURCE_DIR}" REALPATH) + get_filename_component(bindir "${CMAKE_BINARY_DIR}" REALPATH) + + # disallow in-source builds + if("${srcdir}" STREQUAL "${bindir}") + message("######################################################") + message("# SimpleITK should not be configured & built in the SimpleITK source directory") + message("# You must run cmake in a build directory.") + message("######################################################") + message(FATAL_ERROR "Quitting configuration") + endif() +endfunction() + +AssureOutOfSourceBuilds() diff --git a/Code/BasicFilters/CMakeLists.txt b/Code/BasicFilters/CMakeLists.txt index f14d2a066..2790677bd 100644 --- a/Code/BasicFilters/CMakeLists.txt +++ b/Code/BasicFilters/CMakeLists.txt @@ -1,7 +1,7 @@ # Set up code generation -include(${SimpleITK_SOURCE_DIR}/CMake/generate_filter_source.cmake) +include(sitkGenerateFilterSource) generate_filter_source() add_subdirectory( src ) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 3b929db8c..cd3b1002b 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -53,8 +53,8 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ) -include(PreventInSourceBuilds) -include(PreventInBuildInstalls) +include(sitkPreventInSourceBuilds) +include(sitkPreventInBuildInstalls) include(VariableList) From 4c81942615e1bd6f6bc99d012b14b8ca4ba7d3a6 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 5 Apr 2016 15:30:19 -0400 Subject: [PATCH 199/412] Rename UseSWIGLocal to sitkUseSWIG Change-Id: I83c8e9938444ad32339ac57532d77e6c20f5a432 --- CMake/sitkProjectLanguageCommon.cmake | 2 +- CMake/{UseSWIGLocal.cmake => sitkUseSWIG.cmake} | 0 SuperBuild/SuperBuild.cmake | 1 - 3 files changed, 1 insertion(+), 2 deletions(-) rename CMake/{UseSWIGLocal.cmake => sitkUseSWIG.cmake} (100%) diff --git a/CMake/sitkProjectLanguageCommon.cmake b/CMake/sitkProjectLanguageCommon.cmake index fe179050a..9072fe1bd 100644 --- a/CMake/sitkProjectLanguageCommon.cmake +++ b/CMake/sitkProjectLanguageCommon.cmake @@ -42,7 +42,7 @@ endif() find_package ( SWIG 2 REQUIRED ) -include (UseSWIGLocal) +include (sitkUseSWIG) file(GLOB SWIG_EXTRA_DEPS "${SimpleITK_SOURCE_DIR}/Code/Common/include/*.h" diff --git a/CMake/UseSWIGLocal.cmake b/CMake/sitkUseSWIG.cmake similarity index 100% rename from CMake/UseSWIGLocal.cmake rename to CMake/sitkUseSWIG.cmake diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index cd3b1002b..8fd4e0e23 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -267,7 +267,6 @@ option ( USE_SYSTEM_SWIG "Use a pre-compiled version of SWIG 2.0 previously conf mark_as_advanced(USE_SYSTEM_SWIG) if(USE_SYSTEM_SWIG) find_package ( SWIG 2 REQUIRED ) - include ( UseSWIGLocal ) else() include(External_Swig) list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES Swig) From bc2fc3519abde7ffff482bbc4edafd5988dbfe43 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 8 Apr 2016 15:22:37 -0400 Subject: [PATCH 200/412] Update ITK Superbuild version along release towards 4.9.1 Change-Id: I16dc343b5eff75ca51f13582fc00b5ebfb7cb18f --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 5f20409c9..337be1903 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY git://itk.org/ITK.git) # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG v4.9.0 ) +set(ITK_TAG_COMMAND GIT_TAG 863e0e3d6ae63f1099b454ebb0148c4948eaa3df ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From f3656195986c410b6fc634211cc0f361b7ca589c Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 11 Mar 2016 10:18:53 -0500 Subject: [PATCH 201/412] Adding ConfusionMatrix measurement This patch requires and update to ITK. Change-Id: Ifabcfd6a8231683b23137e892ef485d4096e5ddd --- .../json/MultiLabelSTAPLEImageFilter.json | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json b/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json index 2c3423311..51e94fe49 100644 --- a/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json +++ b/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json @@ -44,6 +44,21 @@ } ], "measurements" : [ + { + "name" : "ConfusionMatrix", + "type" : "std::vector", + "no_print" : true, + "custom_cast" : "std::vector(value.begin(), value.end())", + "active" : true, + "parameters" : [ + { + "name" : "input", + "type" : "unsigned int" + } + ], + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Get confusion matrix for the i-th input segmentation." + } ], "tests" : [ { From 2e43c9ab7dda03d5e67cc7dbb2007d4d0e21fc31 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 8 Apr 2016 15:24:48 -0400 Subject: [PATCH 202/412] Fix the path of setupegg.py used for packaging Change-Id: Ie4222ad8cf35a07ecd40564de3032aefa2be893b --- Wrapping/Python/dist/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Wrapping/Python/dist/CMakeLists.txt b/Wrapping/Python/dist/CMakeLists.txt index 331bd9d3e..b37d874dc 100644 --- a/Wrapping/Python/dist/CMakeLists.txt +++ b/Wrapping/Python/dist/CMakeLists.txt @@ -7,7 +7,7 @@ if( SimpleITK_PYTHON_EGG OR SimpleITK_PYTHON_WHEEL ) Using unknown versions of pip, setuptools and/or wheel packages/" ) endif() - set(bdist_setup "${CMAKE_CURRENT_BINARY_DIR}/Packaging/setupegg.py") + set(bdist_setup "${SimpleITK_Python_BINARY_DIR}/Packaging/setupegg.py") set(bdist_commands "") if( SimpleITK_PYTHON_EGG ) From 824bf42dd254715ebbaa31e812b4e0ef86f9850d Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Mon, 11 Apr 2016 12:49:50 +1000 Subject: [PATCH 203/412] Support for building swig from a git repository. The swig github site is the default repository, and the lastest release hash is the default tag. This option requires that automake tools are installed, but there is currently no check for them in the cmake files. The option is disabled for MSVC, but this is an assumption on my part. Change-Id: Idbb37ae1d3c44d74ca6ce7b289eb937a28ff6a0c --- SuperBuild/External_Swig.cmake | 38 ++++++++++++++++++++----- SuperBuild/swig_configure_step.cmake.in | 9 ++++++ 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/SuperBuild/External_Swig.cmake b/SuperBuild/External_Swig.cmake index b6ef3129b..a60ce6620 100644 --- a/SuperBuild/External_Swig.cmake +++ b/SuperBuild/External_Swig.cmake @@ -12,11 +12,23 @@ endif() if(NOT SWIG_DIR) + if (NOT MSVC) + option(USE_SWIG_FROM_GIT "Use a version of swig pulled from the git repo. This will require automake tools and does not work under windows." OFF ) + + mark_as_advanced(USE_SWIG_FROM_GIT) + endif() + + if( USE_SWIG_FROM_GIT ) + set(SWIG_GIT_REPOSITORY "git://github.com/swig/swig.git" CACHE STRING "URL of swig git repo") + set(SWIG_GIT_TAG "ec91de75b72ccb7ec20fffd5568dd38a966806e7" CACHE STRING "Tag in swig git repo") + mark_as_advanced(SWIG_GIT_REPO) + mark_as_advanced(SWIG_GIT_TAG) + endif() + set(SWIG_TARGET_VERSION 3.0.8) set(SWIG_DOWNLOAD_SOURCE_HASH "c96a1d5ecb13d38604d7e92148c73c97") set(SWIG_DOWNLOAD_WIN_HASH "07bc00f7511b7d57516c50f59d705efa") - if(WIN32) # binary SWIG for windows #------------------------------------------------------------------------------ @@ -55,9 +67,12 @@ if(NOT SWIG_DIR) # # swig uses bison find it by cmake and pass it down - find_package(BISON) - set(BISON_FLAGS "" CACHE STRING "Flags used by bison") - mark_as_advanced( BISON_FLAGS) + if(USE_SWIG_FROM_GIT) + set(BISON_REQUIRED "REQUIRED") + endif() + find_package(BISON ${BISON_REQUIRED}) + set(BISON_FLAGS "-y" CACHE STRING "Flags used by bison") + mark_as_advanced(BISON_FLAGS) # follow the standard EP_PREFIX locations @@ -72,13 +87,22 @@ if(NOT SWIG_DIR) @ONLY) set(swig_CONFIGURE_COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/swig_configure_step.cmake) + if(USE_SWIG_FROM_GIT) + set(SWIG_DOWNLOAD_STEP + GIT_REPOSITORY "${SWIG_GIT_REPOSITORY}" + GIT_TAG "${SWIG_GIT_TAG}" + ) + else() + set(SWIG_DOWNLOAD_STEP + URL "https://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${SWIG_DOWNLOAD_SOURCE_HASH}&name=swig-${SWIG_TARGET_VERSION}.tar.gz" + URL_MD5 "${SWIG_DOWNLOAD_SOURCE_HASH}" + ) + endif() ExternalProject_add(Swig - URL https://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${SWIG_DOWNLOAD_SOURCE_HASH}&name=swig-${SWIG_TARGET_VERSION}.tar.gz - URL_MD5 ${SWIG_DOWNLOAD_SOURCE_HASH} + ${SWIG_DOWNLOAD_STEP} CONFIGURE_COMMAND ${swig_CONFIGURE_COMMAND} DEPENDS "${Swig_DEPENDENCIES}" - ) set(SWIG_DIR ${swig_install_dir}/share/swig/${SWIG_TARGET_VERSION}) diff --git a/SuperBuild/swig_configure_step.cmake.in b/SuperBuild/swig_configure_step.cmake.in index 3b029e469..8a85b41c7 100644 --- a/SuperBuild/swig_configure_step.cmake.in +++ b/SuperBuild/swig_configure_step.cmake.in @@ -4,6 +4,8 @@ # enviroment. If there is a problem with them in the future they can # be addressed in CMake with the same structure. +cmake_policy(SET CMP0012 NEW) + set(ENV{CC} "@CMAKE_C_COMPILER@ @CMAKE_C_COMPILER_ARG1@") set(ENV{CFLAGS} "@CMAKE_C_FLAGS@ @CMAKE_C_FLAGS_RELEASE@") set(ENV{LDFLAGS} "@CMAKE_LINKER_FLAGS@ @CMAKE_LINKER_FLAGS_RELEASE@") @@ -18,6 +20,13 @@ set(ENV{CXXFLAGS} "@CMAKE_CXX_FLAGS@ @CMAKE_CXX_FLAGS_RELEASE@") set(ENV{YACC} "@BISON_EXECUTABLE@" ) set(ENV{YFLAGS} "@BISON_FLAGS@" ) +if(@USE_SWIG_FROM_GIT@) + execute_process( + COMMAND sh @swig_source_dir@/autogen.sh + WORKING_DIRECTORY @swig_source_dir@ + ) +endif() + execute_process( COMMAND sh @swig_source_dir@/configure --prefix=@swig_install_dir@ From cbe9e1ab6ba67ad92f11d14c2bfe8020f105278d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 12 Apr 2016 15:34:50 -0400 Subject: [PATCH 204/412] Make R's DESCRIPTION file configured This automatically adds the correct SimpleITK version to the file, along with the compilation date. Change-Id: Ic30f4c85e20bc03ccf8671cc3321c39e8c2c59a6 --- Wrapping/R/CMakeLists.txt | 34 ++++++++++++++++--- .../SimpleITK/{DESCRIPTION => DESCRIPTION.in} | 6 ++-- 2 files changed, 32 insertions(+), 8 deletions(-) rename Wrapping/R/Packaging/SimpleITK/{DESCRIPTION => DESCRIPTION.in} (79%) diff --git a/Wrapping/R/CMakeLists.txt b/Wrapping/R/CMakeLists.txt index da8593aab..f18841fc9 100644 --- a/Wrapping/R/CMakeLists.txt +++ b/Wrapping/R/CMakeLists.txt @@ -43,12 +43,36 @@ sitk_strip_target( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ) set(SWIG_MODULE_SimpleITKR_TARGET_NAME "${SWIG_MODULE_SimpleITK_TARGET_NAME}") +if (WIN32) + execute_process(COMMAND "cmd" " /C date /T" OUTPUT_VARIABLE DATE OUTPUT_STRIP_TRAILING_WHITESPACE) + string(REGEX REPLACE "(..)/(..)/(....).*" "\\3-\\2-\\1" ${DATE} DATE) +elseif(UNIX) + execute_process(COMMAND "date" "+%Y-%m-%d" OUTPUT_VARIABLE DATE OUTPUT_STRIP_TRAILING_WHITESPACE) +else() + message(WARNING "date not implemented") + set(DATE 00-00-0000) +endif() + # copy the R files a binary package -add_custom_command( TARGET ${SWIG_MODULE_SimpleITK_TARGET_NAME} - PRE_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_directory ${SimpleITK_SOURCE_DIR}/Wrapping/R/Packaging ${CMAKE_CURRENT_BINARY_DIR}/Packaging - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/data/ - ) +file( COPY "${CMAKE_CURRENT_SOURCE_DIR}/Packaging" + DESTINATION "${CMAKE_CURRENT_BINARY_DIR}" + PATTERN "*.in" EXCLUDE ) +file(MAKE_DIRECTORY + "${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/data/" ) + + +set(SimpleITKR_VERSION "${SimpleITK_VERSION_MAJOR}.${SimpleITK_VERSION_MINOR}") +if(DEFINED SimpleITK_VERSION_PATCH) + set(SimpleITK_VERSIONR "${SimpleITKR_VERSION}.${SimpleITK_VERSION_PATCH}") + if(DEFINED SimpleITK_VERSION_TWEAK) + set(SimpleITKR_VERSION "${SimpleITKR_VERSION}.${SimpleITK_VERSION_TWEAK}") + endif() +endif() + +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/Packaging/SimpleITK/DESCRIPTION.in" + "${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/DESCRIPTION" + @ONLY ) # download sample images, if allowed if(NOT SITK_FORBID_DOWNLOADS) diff --git a/Wrapping/R/Packaging/SimpleITK/DESCRIPTION b/Wrapping/R/Packaging/SimpleITK/DESCRIPTION.in similarity index 79% rename from Wrapping/R/Packaging/SimpleITK/DESCRIPTION rename to Wrapping/R/Packaging/SimpleITK/DESCRIPTION.in index 3d5e235f9..d754ae169 100644 --- a/Wrapping/R/Packaging/SimpleITK/DESCRIPTION +++ b/Wrapping/R/Packaging/SimpleITK/DESCRIPTION.in @@ -1,6 +1,6 @@ Package: SimpleITK -Version: 0.9.0 -Date: 2012-04-05 +Version: @SimpleITKR_VERSION@ +Date: @DATE@ Title: Bindings to SimpleITK Image segmentation and registration toolkit. Authors@R: c(person("Richard", "Beare", role = c("aut", "cre"), email = "Richard.Beare@ieee.org"), @@ -9,7 +9,7 @@ Authors@R: c(person("Richard", "Beare", role = c("aut", "cre"), Author: Richard Beare, Bradley Lowekamp, plus loads of others Depends: R (>= 2.14), methods Description: This package is an interface to SimpleITK, which is a simplified - interface to the Insight Toolkit (ITK) for medical image segmentation + interface to the Insight Toolkit (ITKv@ITK_VERSION_MAJOR@.@ITK_VERSION_MINOR@.@ITK_VERSION_PATCH@) for medical image segmentation and registration. License: Apache 2.0 URL: http://www.simpleitk.org, http://www.itk.org From 49c36da9bc60fccc97312a6eb59b2c928474cfbc Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 13 Apr 2016 11:23:22 -0400 Subject: [PATCH 205/412] Remove unneeded LOCATION property of SimpleITKR library Change-Id: I79544604e26a0e0ae083b509e527738c5d2a0670 --- Wrapping/R/CMakeLists.txt | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/Wrapping/R/CMakeLists.txt b/Wrapping/R/CMakeLists.txt index f18841fc9..fe6e22739 100644 --- a/Wrapping/R/CMakeLists.txt +++ b/Wrapping/R/CMakeLists.txt @@ -2,15 +2,6 @@ cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) project( SimpleITK_R ) -if(POLICY CMP0026) - # Allow use of the LOCATION target property. - # - # These locations are use in a convoluted fashion with the runtime - # configuration. This system should be refactored to support - # generator expression. This would allow the use of the new policy. - cmake_policy(SET CMP0026 OLD) -endif() - include(../../CMake/sitkProjectLanguageCommon.cmake) find_package ( R REQUIRED ) @@ -32,10 +23,6 @@ endif() set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") -get_target_property( SIMPLEITKR_BINARY_MODULE ${SWIG_MODULE_SimpleITK_TARGET_NAME} LOCATION ) -file(TO_NATIVE_PATH "${SIMPLEITKR_BINARY_MODULE}" SIMPLEITKR_NATIVE_BINARY_MODULE ) - - # set the output directory for the R library to the binary packaging location set_target_properties( ${SWIG_MODULE_SimpleITK_TARGET_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/src/) From e4f979b24c02edd1925d6d8d5b68bf7704493415 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 13 Apr 2016 13:45:27 -0400 Subject: [PATCH 206/412] Move md5 data files into R packaging directory Change the data files form hard codes in CMake to explicit MD5 data files in the source tree. This files will be downloaded and copied into the binary directory for packaging. Change-Id: I7090eadaa9988c976b8841fd51f6313bfaaad978 --- Wrapping/R/CMakeLists.txt | 12 ++++++------ .../R/Packaging/SimpleITK/data/cthead1-Float.mha.md5 | 1 + Wrapping/R/Packaging/SimpleITK/data/cthead1.png.md5 | 1 + 3 files changed, 8 insertions(+), 6 deletions(-) create mode 100644 Wrapping/R/Packaging/SimpleITK/data/cthead1-Float.mha.md5 create mode 100644 Wrapping/R/Packaging/SimpleITK/data/cthead1.png.md5 diff --git a/Wrapping/R/CMakeLists.txt b/Wrapping/R/CMakeLists.txt index fe6e22739..26a3146e9 100644 --- a/Wrapping/R/CMakeLists.txt +++ b/Wrapping/R/CMakeLists.txt @@ -43,9 +43,7 @@ endif() # copy the R files a binary package file( COPY "${CMAKE_CURRENT_SOURCE_DIR}/Packaging" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}" - PATTERN "*.in" EXCLUDE ) -file(MAKE_DIRECTORY - "${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/data/" ) + REGEX "(.*\\.in)|(.*\\.md5)" EXCLUDE ) set(SimpleITKR_VERSION "${SimpleITK_VERSION_MAJOR}.${SimpleITK_VERSION_MINOR}") @@ -65,14 +63,16 @@ configure_file( if(NOT SITK_FORBID_DOWNLOADS) include(sitkExternalData) - foreach(link ${SimpleITK_SOURCE_DIR}/Testing/Data/Input/cthead1.png.md5 ${SimpleITK_SOURCE_DIR}/Testing/Data/Input/cthead1-Float.mha.md5) + file( GLOB_RECURSE content_links RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "*.md5" ) + + foreach(link ${content_links}) + message("linking: ${link}") string( REGEX REPLACE "\\.md5$" "" link ${link} ) - ExternalData_Expand_Arguments( SimpleITKRpackageData + ExternalData_Expand_Arguments( SimpleITKRpackageData link_location DATA{${link}} ) set( COPY_DATA_COMMAND ${COPY_DATA_COMMAND} COMMAND ${CMAKE_COMMAND} -E copy ${link_location} ${CMAKE_CURRENT_BINARY_DIR}/Packaging/SimpleITK/data/ ) - endforeach() if(COMMAND ExternalData_Add_Target ) diff --git a/Wrapping/R/Packaging/SimpleITK/data/cthead1-Float.mha.md5 b/Wrapping/R/Packaging/SimpleITK/data/cthead1-Float.mha.md5 new file mode 100644 index 000000000..815300480 --- /dev/null +++ b/Wrapping/R/Packaging/SimpleITK/data/cthead1-Float.mha.md5 @@ -0,0 +1 @@ +25de5707b18c0c684fd5fa30351bf787 \ No newline at end of file diff --git a/Wrapping/R/Packaging/SimpleITK/data/cthead1.png.md5 b/Wrapping/R/Packaging/SimpleITK/data/cthead1.png.md5 new file mode 100644 index 000000000..16027314d --- /dev/null +++ b/Wrapping/R/Packaging/SimpleITK/data/cthead1.png.md5 @@ -0,0 +1 @@ +b23198c9e44a48edfd5b83f075eb455c From 8191a29632228892f4aca633abdcc8b9ba44da23 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 13 Apr 2016 13:58:13 -0400 Subject: [PATCH 207/412] Remove empty R library check Dynamic symbol look-up with unresolved symbols is now handled by a utility function. Change-Id: Id32146ab8df01555578d7e8ca8f1d1bf18b295b4 --- Wrapping/R/CMakeLists.txt | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Wrapping/R/CMakeLists.txt b/Wrapping/R/CMakeLists.txt index 26a3146e9..4096828a5 100644 --- a/Wrapping/R/CMakeLists.txt +++ b/Wrapping/R/CMakeLists.txt @@ -16,10 +16,7 @@ set(SWIG_MODULE_SimpleITK_EXTRA_DEPS ${SWIG_EXTRA_DEPS} ${CMAKE_CURRENT_SOURCE_D SWIG_add_module ( SimpleITK r SimpleITK.i sitkRCommand.cxx ) target_link_libraries ( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ${SimpleITK_LIBRARIES} ) -# on some platforms the r libraries are not required at link time... -if(R_LIBRARIES) - sitk_target_link_libraries_with_dynamic_lookup ( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ${R_LIBRARIES} ) -endif() +sitk_target_link_libraries_with_dynamic_lookup ( ${SWIG_MODULE_SimpleITK_TARGET_NAME} ${R_LIBRARIES} ) set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") From 800ff8ea4e8599052df076640491e3d883a49e56 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 13 Apr 2016 14:20:47 -0400 Subject: [PATCH 208/412] Remove message statement with debug information. Change-Id: I49e4d8ba90f4599235a937551148ce6cd2adef9d --- Wrapping/R/CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/Wrapping/R/CMakeLists.txt b/Wrapping/R/CMakeLists.txt index 4096828a5..87753adc1 100644 --- a/Wrapping/R/CMakeLists.txt +++ b/Wrapping/R/CMakeLists.txt @@ -63,7 +63,6 @@ if(NOT SITK_FORBID_DOWNLOADS) file( GLOB_RECURSE content_links RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "*.md5" ) foreach(link ${content_links}) - message("linking: ${link}") string( REGEX REPLACE "\\.md5$" "" link ${link} ) ExternalData_Expand_Arguments( SimpleITKRpackageData link_location From 95de1ed912b195f3954c595f2c9bd844c20a4555 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 13 Apr 2016 16:29:47 -0400 Subject: [PATCH 209/412] Restore using hash in variable name The undefined lookup was running multiple times with different whitespace flags. This patch restores the original hashing in the variable name so that multiple results can be saved and looked up. Change-Id: I39968b72e6c8b1b000ecf667e1643c734d4fddac --- CMake/sitkCheckCXX11.cmake | 20 ++++++++----------- ...TargetLinkLibrariesWithDynamicLookup.cmake | 15 +++++--------- 2 files changed, 13 insertions(+), 22 deletions(-) diff --git a/CMake/sitkCheckCXX11.cmake b/CMake/sitkCheckCXX11.cmake index b27cd63e8..dc28ce51f 100644 --- a/CMake/sitkCheckCXX11.cmake +++ b/CMake/sitkCheckCXX11.cmake @@ -17,18 +17,14 @@ # Function to wrap try compiles on the aggregate cxx test file1 # function(sitkCXX11Test VARIABLE) - # use the hash of the dependent cxx flags in the cached variable - # value to know if the arguments have changed, and need to rerun - string(MD5 cmake_flags_hash "${CMAKE_CXX_FLAGS}") - set(cache_var "${VARIABLE}_hash") + # use the hash of the dependent cxx flags in the variable name to + # cache the results. + string(MD5 cmake_cxx_flags_hash "#${CMAKE_CXX_FLAGS}") + set(cache_var "${VARIABLE}_${cmake_cxx_flags_hash}") - if(NOT DEFINED "${cache_var}" ) - unset("${VARIABLE}" CACHE) - elseif(NOT "${${cache_var}}" STREQUAL "${cmake_flags_hash}" ) - unset("${VARIABLE}" CACHE) - endif() - - if(NOT DEFINED "${VARIABLE}") + if(DEFINED "${cache_var}") + set(${VARIABLE} "${${cache_var}}" CACHE INTERNAL "Using hashed value from TRY_COMPILE") + else() message(STATUS "Performing Test ${VARIABLE}") set(requred_definitions "${CMAKE_REQUIRED_DEFINITIONS} -D${VARIABLE}") try_compile(${VARIABLE} @@ -38,7 +34,7 @@ function(sitkCXX11Test VARIABLE) -DCOMPILE_DEFINITIONS:STRING=${requred_definitions} OUTPUT_VARIABLE output) - set(${cache_var} "${cmake_flags_hash}" CACHE INTERNAL "hashed try_compile flags") + set(${cache_var} ${${VARIABLE}} CACHE INTERNAL "hashed flags with try_compile results") if(${VARIABLE}) message(STATUS "Performing Test ${VARIABLE} - Success") diff --git a/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake b/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake index e3d0e5385..078d4cd07 100644 --- a/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake +++ b/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake @@ -31,19 +31,14 @@ function(_sitkCheckUndefinedSymbolsAllowed) set(VARIABLE "SITK_UNDEFINED_SYMBOLS_ALLOWED") - set(cache_var "${VARIABLE}_hash") - # hash the CMAKE_FLAGS passed and check cache to know if we need to rerun string(MD5 cmake_flags_hash "${CMAKE_SHARED_LINKER_FLAGS}") + set(cache_var "${VARIABLE}_${cmake_flags_hash}") - if(NOT DEFINED "${cache_var}" ) - unset("${VARIABLE}" CACHE) - elseif(NOT "${${cache_var}}" STREQUAL "${cmake_flags_hash}" ) - unset("${VARIABLE}" CACHE) - endif() - - if(NOT DEFINED "${VARIABLE}") + if(DEFINED "${cache_var}") + set(${VARIABLE} "${${cache_var}}" CACHE INTERNAL "Using hash (${cmake_flags_hash}) value from TRY_COMPILE") + else() set(test_project_dir "${PROJECT_BINARY_DIR}/CMakeTmp/${VARIABLE}") file(WRITE "${test_project_dir}/CMakeLists.txt" @@ -66,7 +61,7 @@ int foo(void) {return bar()+1;} "-DCMAKE_SHARED_LINKER_FLAGS='${CMAKE_SHARED_LINKER_FLAGS}'" OUTPUT_VARIABLE output) - set(${cache_var} "${cmake_flags_hash}" CACHE INTERNAL "hashed try_compile flags") + set(${cache_var} ${${VARIABLE}} CACHE INTERNAL "hashed flags with try_compile results") if(${VARIABLE}) message(STATUS "Performing Test ${VARIABLE} - Success") From 74402ecd9c8d726b5c265e5a140dbbef4d463ab6 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 13 Apr 2016 16:32:49 -0400 Subject: [PATCH 210/412] Remove unneeded include of DynamicLookup cmake module Change-Id: I1ff341c96bb555e122a36f7c60a0b589a1cf32f8 --- CMakeLists.txt | 2 -- 1 file changed, 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7d1b6930a..ee9e8eeef 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -56,8 +56,6 @@ find_package(ITK REQUIRED ) #we require certain packages be turned on in ITK include(sitkCheckForITKModuleDependencies) -include(sitkTargetLinkLibrariesWithDynamicLookup) - if(ITK_FOUND) # NOTE: We are purposely not calling UseITK yet. However, we must make From 1a7e6b0d44219f5b62ef8bde5251801cad3c424a Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 5 Apr 2016 11:50:13 -0400 Subject: [PATCH 211/412] Remove checking for warning flags at the Superbuild level Change-Id: Ic709c4c0f99ab7bbf0a5511f7c46d6bda6e4957c --- SuperBuild/SuperBuild.cmake | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 8fd4e0e23..dcddfb2ab 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -111,8 +111,6 @@ endif() #------------------------------------------------------------------------- # augment compiler flags #------------------------------------------------------------------------- -include(CompilerFlagSettings) - # the hidden visibility for inline methods should be consistent between ITK and SimpleITK if(NOT WIN32 AND CMAKE_COMPILER_IS_GNUCXX AND BUILD_SHARED_LIBS) @@ -360,7 +358,7 @@ ExternalProject_Add(${proj} ${ep_simpleitk_args} ${ep_common_args} -DBUILD_SHARED_LIBS:BOOL=${BUILD_SHARED_LIBS} - -DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS}\ ${CXX_ADDITIONAL_WARNING_FLAGS} + -DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS} -DCMAKE_INSTALL_PREFIX:PATH= -DCMAKE_LIBRARY_OUTPUT_DIRECTORY:PATH=/lib -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY:PATH=/lib From 6d7bf6037d152ab29be975bad710e5870f595c5b Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 5 Apr 2016 13:11:43 -0400 Subject: [PATCH 212/412] Check if C++11 is require at the Superbuild level. Moving the check ensures that ITK and SimpleITK are build with the same C++ version. Change-Id: Ibcada863de294a874a2e09246d2e0ed501577736 --- CMake/sitkCheckRequiredFlags.cmake | 19 +++++++++++++++++-- CMakeLists.txt | 1 + SuperBuild/SuperBuild.cmake | 6 +++++- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/CMake/sitkCheckRequiredFlags.cmake b/CMake/sitkCheckRequiredFlags.cmake index 0f8d65dc5..53a625951 100644 --- a/CMake/sitkCheckRequiredFlags.cmake +++ b/CMake/sitkCheckRequiredFlags.cmake @@ -1,9 +1,24 @@ # +# Sets the following variables: +# SimpleITK_REQUIRED_C_FLAGS +# SimpleITK_REQUIRED_CXX_FLAGS +# SimpleITK_REQUIRED_LINK_FLAGS # -# +# In particular, this marks the "-std=", and the "-stdlib=" as +# required, if present and check if c++11 is needed. include(CheckCXXCompilerFlag) +if( NOT DEFINED SimpleITK_REQUIRED_C_FLAGS ) + set(SimpleITK_REQUIRED_C_FLAGS "") +endif() +if( NOT DEFINED SimpleITK_REQUIRED_CXX_FLAGS ) + set(SimpleITK_REQUIRED_CXX_FLAGS "") +endif() +if( NOT DEFINED SimpleITK_REQUIRED_LINK_FLAGS ) + set(SimpleITK_REQUIRED_LINK_FLAGS "") +endif() + # # Search CMAKE_CXX_FLAGS for flags that should be considered required, # and propagated to other projects, via the @@ -50,7 +65,7 @@ if(required LESS 0) message(STATUS "Checking if c++11 is required... NO" ) else() message(STATUS "Checking if c++11 is required... YES" ) - file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log + file(APPEND ${CMAKE_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/CMakeError.log "Checking if C++11 required try_compile failed with the following output:\n" "${OUTPUT}\n") set(SimpleITK_REQUIRED_CXX_FLAGS "${SimpleITK_REQUIRED_CXX_FLAGS} -std=c++11") diff --git a/CMakeLists.txt b/CMakeLists.txt index ee9e8eeef..10027dd12 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -50,6 +50,7 @@ message(STATUS "Building SimpleITK version \"${SimpleITK_VERSION}\"") # This must be done before any other try compiles based tests are # done. include(sitkCheckRequiredFlags) +include(CompilerFlagSettings) find_package(ITK REQUIRED ) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index dcddfb2ab..07dbe2d45 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -111,6 +111,8 @@ endif() #------------------------------------------------------------------------- # augment compiler flags #------------------------------------------------------------------------- +include(sitkCheckRequiredFlags) +set ( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SimpleITK_REQUIRED_CXX_FLAGS}" ) # the hidden visibility for inline methods should be consistent between ITK and SimpleITK if(NOT WIN32 AND CMAKE_COMPILER_IS_GNUCXX AND BUILD_SHARED_LIBS) @@ -330,7 +332,9 @@ foreach (_varName ${_varNames}) if(_varName MATCHES "^SimpleITK_" OR _varName MATCHES "^SITK_" ) if (NOT _varName MATCHES "^SITK_LANGUAGES_VARS" AND - NOT _varName MATCHES "^SimpleITK_VARS") + NOT _varName MATCHES "^SimpleITK_VARS" + AND + NOT _varName MATCHES "^SimpleITK_REQUIRED_") message( STATUS "Passing variable \"${_varName}=${${_varName}}\" to SimpleITK external project.") list(APPEND SimpleITK_VARS ${_varName}) endif() From 61f214ad08d62a60e5634f4a1b825b5113def65d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 14 Apr 2016 15:47:02 -0400 Subject: [PATCH 213/412] Update ITK to v4.9.1 release tag Change-Id: I14af6851bddec18e5c66e665043d9c642f4f7a87 --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 337be1903..b010edb75 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY git://itk.org/ITK.git) # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG 863e0e3d6ae63f1099b454ebb0148c4948eaa3df ) +set(ITK_TAG_COMMAND GIT_TAG v4.9.1 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 1840b2bb909871fbab721653ded00280ec6d0187 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 14 Apr 2016 15:48:17 -0400 Subject: [PATCH 214/412] Fix CMP0042 Warning in try compile Explicitly set CMAKE_MACOSX_RPATH in test code, to avoid CMP warning and different behavior. Change-Id: Ie758243440e8fc4b95435e3f9f7dda47bde1a491 --- CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake | 1 + 1 file changed, 1 insertion(+) diff --git a/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake b/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake index 078d4cd07..10e0a5675 100644 --- a/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake +++ b/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake @@ -44,6 +44,7 @@ function(_sitkCheckUndefinedSymbolsAllowed) file(WRITE "${test_project_dir}/CMakeLists.txt" " project(undefined C) +set( CMAKE_MACOSX_RPATH 1) add_library(foo SHARED \"foo.c\") ") From b186fc91591e0405a574b13bf6bc71cc0b8cc4e4 Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Tue, 19 Apr 2016 14:43:56 +1000 Subject: [PATCH 215/412] R vectors of images Test added using Tile filter Change-Id: Ia6479744d0e477400ffbf952aa63060ef553cdc8 --- Testing/Unit/AdditionalTests.cmake | 3 +++ Testing/Unit/RImageListArguments.R | 18 ++++++++++++++ Wrapping/R/R.i | 40 +++++++++++++++++++++++++++++- 3 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 Testing/Unit/RImageListArguments.R diff --git a/Testing/Unit/AdditionalTests.cmake b/Testing/Unit/AdditionalTests.cmake index d18b76e24..92d8d7428 100644 --- a/Testing/Unit/AdditionalTests.cmake +++ b/Testing/Unit/AdditionalTests.cmake @@ -57,6 +57,9 @@ sitk_add_r_test( Arithmetic sitk_add_r_test( PixelIndexing "--file=${SimpleITK_SOURCE_DIR}/Testing/Unit/RPixelAccess.R" ) +sitk_add_r_test( ImageListArguments + "--file=${SimpleITK_SOURCE_DIR}/Testing/Unit/RImageListArguments.R" + ) # diff --git a/Testing/Unit/RImageListArguments.R b/Testing/Unit/RImageListArguments.R new file mode 100644 index 000000000..e82f3bb8f --- /dev/null +++ b/Testing/Unit/RImageListArguments.R @@ -0,0 +1,18 @@ +## tests of image pixel access. +## helps to check whether the rtype entries for std:vector in R.i are OK. +library(SimpleITK) + +imsize <- 64 +img1 = Image(imsize, imsize, "sitkFloat32") +img2 = Image(imsize, imsize, "sitkFloat32") + +arglist <- list(img1, img2, img1) + +h<-Tile(arglist, c(length(arglist),1)) +sz <- h$GetSize() + +if (any(sz != c(imsize*length(arglist), imsize))) +{ + cat("Failure in tiling with image list arguments\n") + quit(save="no", status=1) +} diff --git a/Wrapping/R/R.i b/Wrapping/R/R.i index 518f65827..0831c0fd5 100644 --- a/Wrapping/R/R.i +++ b/Wrapping/R/R.i @@ -32,6 +32,25 @@ std::vector, std::vector *, std::vector & %{ %} +// Experiments on lists/vectors of images +// it would be nice to generalise this to vectors of SWIG_TYPE +// Are there use cases beyond vectors of images - e.g. vectors of filters? +%typemap("rtype") std::vector, std::vector& "list"; +%typemap("rtypecheck") std::vector, std::vector& +%{ + (is.list($arg) & all(sapply($arg, inherits, what='_p_itk__simple__Image'))) +%} +%typemap("scoercein") std::vector, std::vector& +%{ + $input=ImListToVec($input); + $input=slot($input, "ref") +%} + +%typemap("scoerceout") std::vector, std::vector& +%{ + $result=ImportSwigVec($result); +%} + // stop printing "NULL" when calling a method // returning void %typemap(scoerceout) void @@ -598,5 +617,24 @@ itk::simple::Image ArrayAsIm(SEXP arr, setMethod('print', 'C++Reference', function(x, ...)cat(x$ToString())) setMethod('show', 'C++Reference', function(object)cat(object$ToString())) - %} +ImportSwigVec <- function(ImVec) +{ + # an import function for unsupported std::vector types + # intended for vectors of sitk images + l <- ImVec$'__len__'() + return(lapply(1:l, function(idx, V)return(V$'__getitem__'(idx-1)))) +} + +ImListToVec <- function(ImList) +{ + l <- length(ImList) + cppvec <- VectorOfImage() + for (idx in 1:l) + { + cppvec$push_back(ImList[[idx]]) + } + return(cppvec) +} + +%} #endif From e629740f48022aaec20ded02d05a26327841dbae Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 22 Apr 2016 14:10:34 -0400 Subject: [PATCH 216/412] Splitting the Wrapping directory into separate language directories --- Examples/CMakeLists.txt | 21 + Examples/CSharp/CMakeLists.txt | 26 ++ .../{ => CSharp}/FilterProgressReporting.cs | 0 Examples/{ => CSharp}/ImageGetBuffer.cs | 0 Examples/{ => CSharp}/SimpleGaussian.cs | 0 Examples/Java/CMakeLists.txt | 19 + .../{ => Java}/FilterProgressReporting.java | 0 Examples/{ => Java}/ImageConnection.java | 0 Examples/{ => Java}/SimpleGaussian.java | 0 Examples/Lua/CMakeLists.txt | 29 ++ Examples/{ => Lua}/DicomSeriesReader.lua | 0 .../{ => Lua}/ImageRegistrationMethod1.lua | 0 Examples/{ => Lua}/SimpleDerivative.lua | 0 Examples/{ => Lua}/SimpleGaussian.lua | 0 Examples/{ => Python}/BoarderSegmentation.py | 0 Examples/Python/CMakeLists.txt | 273 +++++++++++ Examples/{ => Python}/CannyEdge.py | 0 .../ConnectedThresholdImageFilter.py | 0 Examples/{ => Python}/DemonsRegistration1.py | 0 Examples/{ => Python}/DemonsRegistration2.py | 0 Examples/{ => Python}/DicomSeriesReader.py | 0 Examples/{ => Python}/DicomSeriesReader2.py | 0 Examples/{ => Python}/ExtractSlice.py | 0 Examples/{ => Python}/FFTConvolution.py | 0 .../{ => Python}/FilterProgressReporting.py | 0 .../GeodesicActiceContourSegmentation.py | 0 Examples/{ => Python}/ImageCreateAndSet.py | 0 .../{ => Python}/ImageRegistrationMethod1.py | 0 .../{ => Python}/ImageRegistrationMethod2.py | 0 .../{ => Python}/ImageRegistrationMethod3.py | 0 .../{ => Python}/ImageRegistrationMethod4.py | 0 .../ImageRegistrationMethodBSpline1.py | 0 .../ImageRegistrationMethodBSpline2.py | 0 .../ImageRegistrationMethodDisplacement1.py | 0 .../ImageRegistrationMethodExhaustive.py | 0 .../{ => Python}/N4BiasFieldCorrection.py | 0 .../NeighborhoodConnectedImageFilter.py | 0 Examples/{ => Python}/ReadAndShow.py | 0 Examples/{ => Python}/SimpleGaussian.py | 0 .../{ => Python}/SimpleGaussianProcedural.py | 0 Examples/R/CMakeLists.txt | 31 ++ Examples/{ => R}/FilterProgressReporting.R | 0 Examples/{ => R}/ImageRegistrationMethod1.R | 0 Examples/{ => R}/SimpleGaussian.R | 0 Examples/Ruby/CMakeLists.txt | 8 + .../{ => Ruby}/FilterProgressReporting.rb | 0 Examples/{ => Ruby}/SimpleGaussian.rb | 0 Examples/Tcl/CMakeLists.txt | 10 + Examples/{ => Tcl}/SimpleGaussian.tcl | 0 Examples/test/CMakeLists.txt | 425 ------------------ 50 files changed, 417 insertions(+), 425 deletions(-) create mode 100644 Examples/CSharp/CMakeLists.txt rename Examples/{ => CSharp}/FilterProgressReporting.cs (100%) rename Examples/{ => CSharp}/ImageGetBuffer.cs (100%) rename Examples/{ => CSharp}/SimpleGaussian.cs (100%) create mode 100644 Examples/Java/CMakeLists.txt rename Examples/{ => Java}/FilterProgressReporting.java (100%) rename Examples/{ => Java}/ImageConnection.java (100%) rename Examples/{ => Java}/SimpleGaussian.java (100%) create mode 100644 Examples/Lua/CMakeLists.txt rename Examples/{ => Lua}/DicomSeriesReader.lua (100%) rename Examples/{ => Lua}/ImageRegistrationMethod1.lua (100%) rename Examples/{ => Lua}/SimpleDerivative.lua (100%) rename Examples/{ => Lua}/SimpleGaussian.lua (100%) rename Examples/{ => Python}/BoarderSegmentation.py (100%) create mode 100644 Examples/Python/CMakeLists.txt rename Examples/{ => Python}/CannyEdge.py (100%) rename Examples/{Segmentation => Python}/ConnectedThresholdImageFilter.py (100%) rename Examples/{ => Python}/DemonsRegistration1.py (100%) rename Examples/{ => Python}/DemonsRegistration2.py (100%) rename Examples/{ => Python}/DicomSeriesReader.py (100%) rename Examples/{ => Python}/DicomSeriesReader2.py (100%) rename Examples/{ => Python}/ExtractSlice.py (100%) rename Examples/{ => Python}/FFTConvolution.py (100%) rename Examples/{ => Python}/FilterProgressReporting.py (100%) rename Examples/{ => Python}/GeodesicActiceContourSegmentation.py (100%) rename Examples/{ => Python}/ImageCreateAndSet.py (100%) rename Examples/{ => Python}/ImageRegistrationMethod1.py (100%) rename Examples/{ => Python}/ImageRegistrationMethod2.py (100%) rename Examples/{ => Python}/ImageRegistrationMethod3.py (100%) rename Examples/{ => Python}/ImageRegistrationMethod4.py (100%) rename Examples/{ => Python}/ImageRegistrationMethodBSpline1.py (100%) rename Examples/{ => Python}/ImageRegistrationMethodBSpline2.py (100%) rename Examples/{ => Python}/ImageRegistrationMethodDisplacement1.py (100%) rename Examples/{ => Python}/ImageRegistrationMethodExhaustive.py (100%) rename Examples/{ => Python}/N4BiasFieldCorrection.py (100%) rename Examples/{Segmentation => Python}/NeighborhoodConnectedImageFilter.py (100%) rename Examples/{ => Python}/ReadAndShow.py (100%) rename Examples/{ => Python}/SimpleGaussian.py (100%) rename Examples/{ => Python}/SimpleGaussianProcedural.py (100%) create mode 100644 Examples/R/CMakeLists.txt rename Examples/{ => R}/FilterProgressReporting.R (100%) rename Examples/{ => R}/ImageRegistrationMethod1.R (100%) rename Examples/{ => R}/SimpleGaussian.R (100%) create mode 100644 Examples/Ruby/CMakeLists.txt rename Examples/{ => Ruby}/FilterProgressReporting.rb (100%) rename Examples/{ => Ruby}/SimpleGaussian.rb (100%) create mode 100644 Examples/Tcl/CMakeLists.txt rename Examples/{ => Tcl}/SimpleGaussian.tcl (100%) diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index 66305bbe1..91d40a5dd 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -51,6 +51,27 @@ target_link_libraries ( DemonsRegistration2 ${SimpleITK_LIBRARIES} ) # Add subdirectories add_subdirectory(Segmentation) +# Test data directory +set(TEST_HARNESS_TEMP_DIRECTORY ${SimpleITK_BINARY_DIR}/Testing/Temporary) +set(TEST_HARNESS_DATA_DIRECTORY ${SimpleITK_BINARY_DIR}/ExternalData/Testing/Data) +set(ITK_TEST_DRIVER "itkTestDriver") + + +macro(add_language_subdirectory lang) + string(TOUPPER ${lang} LANG) + if ( WRAP_${LANG} ) + add_subdirectory(${lang}) + endif() +endmacro() + +add_language_subdirectory( CSharp ) +add_language_subdirectory( Java ) +add_language_subdirectory( Python ) +add_language_subdirectory( R ) +add_language_subdirectory( Ruby ) +add_language_subdirectory( Tcl ) + + if ( BUILD_TESTING ) add_subdirectory( test ) endif() diff --git a/Examples/CSharp/CMakeLists.txt b/Examples/CSharp/CMakeLists.txt new file mode 100644 index 000000000..7bdfd4e0c --- /dev/null +++ b/Examples/CSharp/CMakeLists.txt @@ -0,0 +1,26 @@ +# +# CSharp Examples +# +sitk_add_csharp_test( Example.SimpleGaussian + "${CMAKE_CURRENT_SOURCE_DIR}/SimpleGaussian.cs" + --compare + "${TEST_HARNESS_TEMP_DIRECTORY}/CSharp.SimpleGaussian.nrrd" + DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} + "2.0" + "${TEST_HARNESS_TEMP_DIRECTORY}/CSharp.SimpleGaussian.nrrd" ) + +sitk_add_csharp_test( Example.ImageGetBuffer + "${CMAKE_CURRENT_SOURCE_DIR}/ImageGetBuffer.cs" + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd}) +set_tests_properties( CSharp.Example.ImageGetBuffer + PROPERTIES PASS_REGULAR_EXPRESSION "total: 1009713" ) + +sitk_add_csharp_test( Example.FilterProgressReporting + "${CMAKE_CURRENT_SOURCE_DIR}/FilterProgressReporting.cs" + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} + "2.0" + "${TEST_HARNESS_TEMP_DIRECTORY}/CSharp.FilterProgressReporting.nrrd" + ) +set_tests_properties( CSharp.Example.FilterProgressReporting + PROPERTIES PASS_REGULAR_EXPRESSION "DiscreteGaussianImageFilter Progress" ) diff --git a/Examples/FilterProgressReporting.cs b/Examples/CSharp/FilterProgressReporting.cs similarity index 100% rename from Examples/FilterProgressReporting.cs rename to Examples/CSharp/FilterProgressReporting.cs diff --git a/Examples/ImageGetBuffer.cs b/Examples/CSharp/ImageGetBuffer.cs similarity index 100% rename from Examples/ImageGetBuffer.cs rename to Examples/CSharp/ImageGetBuffer.cs diff --git a/Examples/SimpleGaussian.cs b/Examples/CSharp/SimpleGaussian.cs similarity index 100% rename from Examples/SimpleGaussian.cs rename to Examples/CSharp/SimpleGaussian.cs diff --git a/Examples/Java/CMakeLists.txt b/Examples/Java/CMakeLists.txt new file mode 100644 index 000000000..722f8e1cd --- /dev/null +++ b/Examples/Java/CMakeLists.txt @@ -0,0 +1,19 @@ + +sitk_add_java_test( Example.SimpleGaussian + "${CMAKE_CURRENT_SOURCE_DIR}/SimpleGaussian.java" + --compare + "${TEST_HARNESS_TEMP_DIRECTORY}/Java.SimpleGaussian.nrrd" + DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} + "2.0" + "${TEST_HARNESS_TEMP_DIRECTORY}/Java.SimpleGaussian.nrrd" ) + +sitk_add_java_test( Example.FilterProgressReporting + "${CMAKE_CURRENT_SOURCE_DIR}/FilterProgressReporting.java" + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} + "2.0" + "${TEST_HARNESS_TEMP_DIRECTORY}/Java.FilterProgressReporting.nrrd" + ) +set_tests_properties( Java.Example.FilterProgressReporting + PROPERTIES PASS_REGULAR_EXPRESSION "DiscreteGaussianImageFilter Progress" ) + diff --git a/Examples/FilterProgressReporting.java b/Examples/Java/FilterProgressReporting.java similarity index 100% rename from Examples/FilterProgressReporting.java rename to Examples/Java/FilterProgressReporting.java diff --git a/Examples/ImageConnection.java b/Examples/Java/ImageConnection.java similarity index 100% rename from Examples/ImageConnection.java rename to Examples/Java/ImageConnection.java diff --git a/Examples/SimpleGaussian.java b/Examples/Java/SimpleGaussian.java similarity index 100% rename from Examples/SimpleGaussian.java rename to Examples/Java/SimpleGaussian.java diff --git a/Examples/Lua/CMakeLists.txt b/Examples/Lua/CMakeLists.txt new file mode 100644 index 000000000..20d9c4809 --- /dev/null +++ b/Examples/Lua/CMakeLists.txt @@ -0,0 +1,29 @@ +sitk_add_lua_test( Example.SimpleGaussian + "${CMAKE_CURRENT_SOURCE_DIR}/SimpleGaussian.lua" + --compare + "${TEST_HARNESS_TEMP_DIRECTORY}/Lua.SimpleGaussian.nrrd" + DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} + "2.0" + "${TEST_HARNESS_TEMP_DIRECTORY}/Lua.SimpleGaussian.nrrd" ) + +sitk_add_lua_test( Example.DicomSeriesReader + "${CMAKE_CURRENT_SOURCE_DIR}/DicomSeriesReader.lua" + --compare-MD5 + "${TEST_HARNESS_TEMP_DIRECTORY}/DicomSeriesReader.nrrd" + "8e65f711d450b6b466c6d76a667ecb72" + DATA{${SimpleITK_DATA_ROOT}/Input/DicomSeries/,REGEX:Image[0-9]+.dcm} + "${TEST_HARNESS_TEMP_DIRECTORY}/DicomSeriesReader.nrrd" + ) + +sitk_add_lua_test( Example.ImageRegistrationMethod1 + "${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethod1.lua" + ${TEST_HARNESS_DATA_DIRECTORY}/Input/BrainProtonDensitySliceBorder20.png + ${TEST_HARNESS_DATA_DIRECTORY}/Input/BrainProtonDensitySliceShifted13x17y.png + ${TEST_HARNESS_TEMP_DIRECTORY}/LuaImageRegistrationMethod1Test.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/LuaImageRegistrationMethod1Test.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/displacement_13x17y.mha} + 0.02 + ) + diff --git a/Examples/DicomSeriesReader.lua b/Examples/Lua/DicomSeriesReader.lua similarity index 100% rename from Examples/DicomSeriesReader.lua rename to Examples/Lua/DicomSeriesReader.lua diff --git a/Examples/ImageRegistrationMethod1.lua b/Examples/Lua/ImageRegistrationMethod1.lua similarity index 100% rename from Examples/ImageRegistrationMethod1.lua rename to Examples/Lua/ImageRegistrationMethod1.lua diff --git a/Examples/SimpleDerivative.lua b/Examples/Lua/SimpleDerivative.lua similarity index 100% rename from Examples/SimpleDerivative.lua rename to Examples/Lua/SimpleDerivative.lua diff --git a/Examples/SimpleGaussian.lua b/Examples/Lua/SimpleGaussian.lua similarity index 100% rename from Examples/SimpleGaussian.lua rename to Examples/Lua/SimpleGaussian.lua diff --git a/Examples/BoarderSegmentation.py b/Examples/Python/BoarderSegmentation.py similarity index 100% rename from Examples/BoarderSegmentation.py rename to Examples/Python/BoarderSegmentation.py diff --git a/Examples/Python/CMakeLists.txt b/Examples/Python/CMakeLists.txt new file mode 100644 index 000000000..4d47e905a --- /dev/null +++ b/Examples/Python/CMakeLists.txt @@ -0,0 +1,273 @@ +sitk_add_python_test( Example.SimpleGaussian + "${CMAKE_CURRENT_SOURCE_DIR}/SimpleGaussian.py" + --compare + "${TEST_HARNESS_TEMP_DIRECTORY}/Python.SimpleGaussian.nrrd" + DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} + "2.0" + "${TEST_HARNESS_TEMP_DIRECTORY}/Python.SimpleGaussian.nrrd" ) + +sitk_add_python_test( Example.SimpleGaussianProcedural + "${CMAKE_CURRENT_SOURCE_DIR}/SimpleGaussianProcedural.py" + --compare + "${TEST_HARNESS_TEMP_DIRECTORY}/Python.SimpleGaussianProcedural.nrrd" + DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} + "2.0" + "${TEST_HARNESS_TEMP_DIRECTORY}/Python.SimpleGaussianProcedural.nrrd" ) + +sitk_add_python_test( Example.ImageCreateAndSet + "${CMAKE_CURRENT_SOURCE_DIR}/ImageCreateAndSet.py" ) + +sitk_add_python_test( Example.CannyEdge + "${CMAKE_CURRENT_SOURCE_DIR}/CannyEdge.py" + DATA{${SimpleITK_DATA_ROOT}/Input/OAS1_0001_MR1_mpr-1_anon.nrrd} ) + +sitk_add_python_test( Example.ExtractSlice + "${CMAKE_CURRENT_SOURCE_DIR}/ExtractSlice.py" + DATA{${SimpleITK_DATA_ROOT}/Input/OAS1_0001_MR1_mpr-1_anon.nrrd} + "30" + "${TEST_HARNESS_TEMP_DIRECTORY}/Python.ExtractSlice.nrrd") + +sitk_add_python_test( Example.BoarderSegmentation + "${CMAKE_CURRENT_SOURCE_DIR}/BoarderSegmentation.py" + DATA{${SimpleITK_DATA_ROOT}/Input/OAS1_0001_MR1_mpr-1_anon.nrrd} + "${TEST_HARNESS_TEMP_DIRECTORY}/Python.BoarderSegmentation.nrrd" + "5000" + "150" ) + + sitk_add_python_test( Example.N4BiasFieldCorrection + "${CMAKE_CURRENT_SOURCE_DIR}/N4BiasFieldCorrection.py" + DATA{${SimpleITK_DATA_ROOT}/Input/OAS1_0001_MR1_mpr-1_anon.nrrd} + "${TEST_HARNESS_TEMP_DIRECTORY}/Python.Example.N4BiasFieldCorrection.nrrd" + "1" ) + +sitk_add_python_test( Example.ReadAndShow + "${CMAKE_CURRENT_SOURCE_DIR}/ReadAndShow.py" + DATA{${SimpleITK_DATA_ROOT}/Input/VM1111Shrink-RGB.png} ) + +sitk_add_python_test( Example.GeodesicActiceContourSegmentation + "${CMAKE_CURRENT_SOURCE_DIR}/GeodesicActiceContourSegmentation.py" + DATA{${SimpleITK_DATA_ROOT}/Input/cthead1.png} + "${TEST_HARNESS_TEMP_DIRECTORY}/Python.Example.GeodesicActiceContourSegmentation.nrrd" + .3 10 .9 50 55 + ) + +sitk_add_python_test( Example.FFTConvolution + "${CMAKE_CURRENT_SOURCE_DIR}/FFTConvolution.py" + DATA{${SimpleITK_DATA_ROOT}/Input/cthead1-Float.mha} + DATA{${SimpleITK_DATA_ROOT}/Input/Gaussian_1.5.nrrd} + "${TEST_HARNESS_TEMP_DIRECTORY}/Python.Examples.FFTConvolution.nrrd" + ) + +sitk_add_python_test( Example.FilterProgressReporting + "${CMAKE_CURRENT_SOURCE_DIR}/FilterProgressReporting.py" + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} + "2.0" + "${TEST_HARNESS_TEMP_DIRECTORY}/PythonFilterProgressReporting.nrrd" + ) + +set_tests_properties( Python.Example.FilterProgressReporting + PROPERTIES PASS_REGULAR_EXPRESSION "DiscreteGaussianImageFilter Progress" ) + +sitk_add_python_test( Example.DicomSeriesReader + "${CMAKE_CURRENT_SOURCE_DIR}/DicomSeriesReader.py" + --compare-MD5 + "${TEST_HARNESS_TEMP_DIRECTORY}/DicomSeriesReader.nrrd" + "8e65f711d450b6b466c6d76a667ecb72" + DATA{${SimpleITK_DATA_ROOT}/Input/DicomSeries/,REGEX:Image[0-9]+.dcm} + "${TEST_HARNESS_TEMP_DIRECTORY}/DicomSeriesReader.nrrd" + ) + +sitk_add_python_test( Example.DicomSeriesReader2 + "${CMAKE_CURRENT_SOURCE_DIR}/DicomSeriesReader2.py" + --compare-MD5 + "${TEST_HARNESS_TEMP_DIRECTORY}/DicomSeriesReader2.nrrd" + "8e65f711d450b6b466c6d76a667ecb72" + DATA{${SimpleITK_DATA_ROOT}/Input/DicomSeries/,REGEX:Image[0-9]+.dcm} + "${TEST_HARNESS_TEMP_DIRECTORY}/DicomSeriesReader2.nrrd" + ) + +sitk_add_python_test( Example.ConnectedThresholdImageFilter1 + "${CMAKE_CURRENT_SOURCE_DIR}/ConnectedThresholdImageFilter.py" + --compare-MD5 + "${TEST_HARNESS_TEMP_DIRECTORY}/PythonSegmentationConnectedThreshold1.png" + "d4ff9c512f9c18a84729677de800db0d" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySlice.png} + "${TEST_HARNESS_TEMP_DIRECTORY}/PythonSegmentationConnectedThreshold1.png" + 150 180 + 60 116 + ) + +sitk_add_python_test( Example.ConnectedThresholdImageFilter2 + "${CMAKE_CURRENT_SOURCE_DIR}/ConnectedThresholdImageFilter.py" + --compare-MD5 + "${TEST_HARNESS_TEMP_DIRECTORY}/PythonSegmentationConnectedThreshold2.png" + "a9695df04cde5b9c5481d8c253a5b3aa" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySlice.png} + "${TEST_HARNESS_TEMP_DIRECTORY}/PythonSegmentationConnectedThreshold2.png" + 210 250 + 81 112 + ) + +sitk_add_python_test( Example.NeighborhoodConnectedImageFilter1 + "${CMAKE_CURRENT_SOURCE_DIR}/NeighborhoodConnectedImageFilter.py" + --compare-MD5 + "${TEST_HARNESS_TEMP_DIRECTORY}/PythonSegmentationNeighborhoodConnected1.png" + "311d9d4b492e1ea625e3b0b295814dce" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySlice.png} + "${TEST_HARNESS_TEMP_DIRECTORY}/PythonSegmentationNeighborhoodConnected1.png" + 150 180 + 60 116 + ) + +sitk_add_python_test( Example.ImageRegistrationMethod1 + "${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethod1.py" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceShifted13x17y.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod11Test.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod11Test.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/displacement_13x17y.mha} + 0.02 + ) + +sitk_add_python_test( Example.ImageRegistrationMethod2 + "${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethod2.py" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceShifted13x17y.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod2Test.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod2Test.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/displacement_13x17y.mha} + 0.02 + ) + +sitk_add_python_test( Example.ImageRegistrationMethod3Test1 + "${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethod3.py" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceR10X13Y17.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod3Test1.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod3Test1.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethod3Test1.mha} + 0.02 + ) + +sitk_add_python_test( Example.ImageRegistrationMethod3Test2 + "${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethod3.py" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceR10X13Y17S12.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod3Test2.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod3Test2.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethod3Test2.mha} + 0.03 + ) + + +sitk_add_python_test( Example.ImageRegistrationMethod4Test1 + "${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethod4.py" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceShifted13x17y.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod4Test1.hdf5 + 24 1.0 + ) + +sitk_add_python_test( Example.ImageRegistrationMethod4Test2 + "${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethod4.py" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainT1SliceBorder20.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceShifted13x17y.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod4Test2.hdf5 + 24 0.1 + ) + +sitk_add_python_test( Example.ImageRegistrationMethod4Test3 + "${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethod4.py" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20Mask.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20Mask.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod4Test3.hdf5 + 5 0.4 + ) + + +sitk_add_python_test(Example.ImageRegistrationMethodBSpline1 + "${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethodBSpline1.py" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBSplined10.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodBSpline1.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodBSpline1.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethodBSpline1.mha} + 0.02 + ) + + +sitk_add_python_test(Example.ImageRegistrationMethodBSpline2 + "${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethodBSpline2.py" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainT1SliceBorder20.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBSplined10.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodBSpline2.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodBSpline2.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethodBSpline2.mha} + 0.02 + ) + +sitk_add_python_test(Example.ImageRegistrationMethodDisplacement1 + "${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethodDisplacement1.py" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBSplined10.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodDisplacement1.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodDisplacement1.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethodDisplacement1.mha} + 0.02 + ) + +sitk_add_python_test(Example.ImageRegistrationMethodDisplacement1Test2 + "${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethodDisplacement1.py" + DATA{${SimpleITK_DATA_ROOT}/Input/r16slice_rigid.nii.gz} + DATA{${SimpleITK_DATA_ROOT}/Input/r64slice.nii.gz} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodDisplacement1Test2.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodDisplacement1Test2.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethodDisplacement1Test2.mha} + 0.02 + ) + +sitk_add_python_test(Example.ImageRegistrationMethodExhaustiveTest1 + "${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethodExhaustive.py" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySlice.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceR10X13Y17.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodExhaustiveTest1.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodExhaustiveTest1.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethodExhaustiveTest1.mha} + 1e-10 + ) + + + +sitk_add_python_test(Example.DemonsRegistration1 + "${CMAKE_CURRENT_SOURCE_DIR}/DemonsRegistration1.py" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBSplined10.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonDemonsRegistration1Test.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonDemonsRegistration1Test.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/DemonsRegistration1Test_displacement.mha} + 0.005 + ) + +sitk_add_python_test(Example.DemonsRegistration2 + "${CMAKE_CURRENT_SOURCE_DIR}/DemonsRegistration2.py" + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceShifted13x17y.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBSplined10.png} + DATA{${SimpleITK_DATA_ROOT}/Input/xforms/translation_-13x-17y.txt} + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonDemonsRegistration2Test.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/PythonDemonsRegistration2Test.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/DemonsRegistration2Test_displacement.mha} + 0.01 + ) diff --git a/Examples/CannyEdge.py b/Examples/Python/CannyEdge.py similarity index 100% rename from Examples/CannyEdge.py rename to Examples/Python/CannyEdge.py diff --git a/Examples/Segmentation/ConnectedThresholdImageFilter.py b/Examples/Python/ConnectedThresholdImageFilter.py similarity index 100% rename from Examples/Segmentation/ConnectedThresholdImageFilter.py rename to Examples/Python/ConnectedThresholdImageFilter.py diff --git a/Examples/DemonsRegistration1.py b/Examples/Python/DemonsRegistration1.py similarity index 100% rename from Examples/DemonsRegistration1.py rename to Examples/Python/DemonsRegistration1.py diff --git a/Examples/DemonsRegistration2.py b/Examples/Python/DemonsRegistration2.py similarity index 100% rename from Examples/DemonsRegistration2.py rename to Examples/Python/DemonsRegistration2.py diff --git a/Examples/DicomSeriesReader.py b/Examples/Python/DicomSeriesReader.py similarity index 100% rename from Examples/DicomSeriesReader.py rename to Examples/Python/DicomSeriesReader.py diff --git a/Examples/DicomSeriesReader2.py b/Examples/Python/DicomSeriesReader2.py similarity index 100% rename from Examples/DicomSeriesReader2.py rename to Examples/Python/DicomSeriesReader2.py diff --git a/Examples/ExtractSlice.py b/Examples/Python/ExtractSlice.py similarity index 100% rename from Examples/ExtractSlice.py rename to Examples/Python/ExtractSlice.py diff --git a/Examples/FFTConvolution.py b/Examples/Python/FFTConvolution.py similarity index 100% rename from Examples/FFTConvolution.py rename to Examples/Python/FFTConvolution.py diff --git a/Examples/FilterProgressReporting.py b/Examples/Python/FilterProgressReporting.py similarity index 100% rename from Examples/FilterProgressReporting.py rename to Examples/Python/FilterProgressReporting.py diff --git a/Examples/GeodesicActiceContourSegmentation.py b/Examples/Python/GeodesicActiceContourSegmentation.py similarity index 100% rename from Examples/GeodesicActiceContourSegmentation.py rename to Examples/Python/GeodesicActiceContourSegmentation.py diff --git a/Examples/ImageCreateAndSet.py b/Examples/Python/ImageCreateAndSet.py similarity index 100% rename from Examples/ImageCreateAndSet.py rename to Examples/Python/ImageCreateAndSet.py diff --git a/Examples/ImageRegistrationMethod1.py b/Examples/Python/ImageRegistrationMethod1.py similarity index 100% rename from Examples/ImageRegistrationMethod1.py rename to Examples/Python/ImageRegistrationMethod1.py diff --git a/Examples/ImageRegistrationMethod2.py b/Examples/Python/ImageRegistrationMethod2.py similarity index 100% rename from Examples/ImageRegistrationMethod2.py rename to Examples/Python/ImageRegistrationMethod2.py diff --git a/Examples/ImageRegistrationMethod3.py b/Examples/Python/ImageRegistrationMethod3.py similarity index 100% rename from Examples/ImageRegistrationMethod3.py rename to Examples/Python/ImageRegistrationMethod3.py diff --git a/Examples/ImageRegistrationMethod4.py b/Examples/Python/ImageRegistrationMethod4.py similarity index 100% rename from Examples/ImageRegistrationMethod4.py rename to Examples/Python/ImageRegistrationMethod4.py diff --git a/Examples/ImageRegistrationMethodBSpline1.py b/Examples/Python/ImageRegistrationMethodBSpline1.py similarity index 100% rename from Examples/ImageRegistrationMethodBSpline1.py rename to Examples/Python/ImageRegistrationMethodBSpline1.py diff --git a/Examples/ImageRegistrationMethodBSpline2.py b/Examples/Python/ImageRegistrationMethodBSpline2.py similarity index 100% rename from Examples/ImageRegistrationMethodBSpline2.py rename to Examples/Python/ImageRegistrationMethodBSpline2.py diff --git a/Examples/ImageRegistrationMethodDisplacement1.py b/Examples/Python/ImageRegistrationMethodDisplacement1.py similarity index 100% rename from Examples/ImageRegistrationMethodDisplacement1.py rename to Examples/Python/ImageRegistrationMethodDisplacement1.py diff --git a/Examples/ImageRegistrationMethodExhaustive.py b/Examples/Python/ImageRegistrationMethodExhaustive.py similarity index 100% rename from Examples/ImageRegistrationMethodExhaustive.py rename to Examples/Python/ImageRegistrationMethodExhaustive.py diff --git a/Examples/N4BiasFieldCorrection.py b/Examples/Python/N4BiasFieldCorrection.py similarity index 100% rename from Examples/N4BiasFieldCorrection.py rename to Examples/Python/N4BiasFieldCorrection.py diff --git a/Examples/Segmentation/NeighborhoodConnectedImageFilter.py b/Examples/Python/NeighborhoodConnectedImageFilter.py similarity index 100% rename from Examples/Segmentation/NeighborhoodConnectedImageFilter.py rename to Examples/Python/NeighborhoodConnectedImageFilter.py diff --git a/Examples/ReadAndShow.py b/Examples/Python/ReadAndShow.py similarity index 100% rename from Examples/ReadAndShow.py rename to Examples/Python/ReadAndShow.py diff --git a/Examples/SimpleGaussian.py b/Examples/Python/SimpleGaussian.py similarity index 100% rename from Examples/SimpleGaussian.py rename to Examples/Python/SimpleGaussian.py diff --git a/Examples/SimpleGaussianProcedural.py b/Examples/Python/SimpleGaussianProcedural.py similarity index 100% rename from Examples/SimpleGaussianProcedural.py rename to Examples/Python/SimpleGaussianProcedural.py diff --git a/Examples/R/CMakeLists.txt b/Examples/R/CMakeLists.txt new file mode 100644 index 000000000..865033ef0 --- /dev/null +++ b/Examples/R/CMakeLists.txt @@ -0,0 +1,31 @@ + +sitk_add_r_test( Example.SimpleGaussian + "--file=${CMAKE_CURRENT_SOURCE_DIR}/SimpleGaussian.R" + --compare + "${TEST_HARNESS_TEMP_DIRECTORY}/R.SimpleGaussian.nrrd" + DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} + --args + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} + "2.0" + "${TEST_HARNESS_TEMP_DIRECTORY}/R.SimpleGaussian.nrrd" + ) + +sitk_add_r_test( Example.FilterProgressReporting + "--file=${CMAKE_CURRENT_SOURCE_DIR}/FilterProgressReporting.R" + --args + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} + 2.0 + "${TEST_HARNESS_TEMP_DIRECTORY}/R.FilterProgressReporting.nrrd" + ) + +sitk_add_r_test( Example.ImageRegistrationMethod1 + "--file=${CMAKE_CURRENT_SOURCE_DIR}/ImageRegistrationMethod1.R" + --args + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} + DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceShifted13x17y.png} + ${TEST_HARNESS_TEMP_DIRECTORY}/RImageRegistrationMethod11Test.hdf5 + TRANSFORM_COMPARE + ${TEST_HARNESS_TEMP_DIRECTORY}/RImageRegistrationMethod11Test.hdf5 + DATA{${SimpleITK_DATA_ROOT}/Baseline/displacement_13x17y.mha} + 0.02 + ) diff --git a/Examples/FilterProgressReporting.R b/Examples/R/FilterProgressReporting.R similarity index 100% rename from Examples/FilterProgressReporting.R rename to Examples/R/FilterProgressReporting.R diff --git a/Examples/ImageRegistrationMethod1.R b/Examples/R/ImageRegistrationMethod1.R similarity index 100% rename from Examples/ImageRegistrationMethod1.R rename to Examples/R/ImageRegistrationMethod1.R diff --git a/Examples/SimpleGaussian.R b/Examples/R/SimpleGaussian.R similarity index 100% rename from Examples/SimpleGaussian.R rename to Examples/R/SimpleGaussian.R diff --git a/Examples/Ruby/CMakeLists.txt b/Examples/Ruby/CMakeLists.txt new file mode 100644 index 000000000..8f636b95c --- /dev/null +++ b/Examples/Ruby/CMakeLists.txt @@ -0,0 +1,8 @@ +sitk_add_ruby_test( Example.SimpleGaussian + "${CMAKE_CURRENT_SOURCE_DIR}/SimpleGaussian.rb" + --compare + "${TEST_HARNESS_TEMP_DIRECTORY}/Ruby.SimpleGaussian.nrrd" + DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} + "2.0" + "${TEST_HARNESS_TEMP_DIRECTORY}/Ruby.SimpleGaussian.nrrd" ) diff --git a/Examples/FilterProgressReporting.rb b/Examples/Ruby/FilterProgressReporting.rb similarity index 100% rename from Examples/FilterProgressReporting.rb rename to Examples/Ruby/FilterProgressReporting.rb diff --git a/Examples/SimpleGaussian.rb b/Examples/Ruby/SimpleGaussian.rb similarity index 100% rename from Examples/SimpleGaussian.rb rename to Examples/Ruby/SimpleGaussian.rb diff --git a/Examples/Tcl/CMakeLists.txt b/Examples/Tcl/CMakeLists.txt new file mode 100644 index 000000000..1779618b1 --- /dev/null +++ b/Examples/Tcl/CMakeLists.txt @@ -0,0 +1,10 @@ + +sitk_add_tcl_test( Example.SimpleGaussian + "${CMAKE_CURRENT_SOURCE_DIR}/SimpleGaussian.tcl" + --compare + "${TEST_HARNESS_TEMP_DIRECTORY}/Tcl.SimpleGaussian.nrrd" + DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} + DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} + "2.0" + "${TEST_HARNESS_TEMP_DIRECTORY}/Tcl.SimpleGaussian.nrrd" ) + diff --git a/Examples/SimpleGaussian.tcl b/Examples/Tcl/SimpleGaussian.tcl similarity index 100% rename from Examples/SimpleGaussian.tcl rename to Examples/Tcl/SimpleGaussian.tcl diff --git a/Examples/test/CMakeLists.txt b/Examples/test/CMakeLists.txt index 785cefced..5216679b4 100644 --- a/Examples/test/CMakeLists.txt +++ b/Examples/test/CMakeLists.txt @@ -1,8 +1,3 @@ -set(ITK_TEST_DRIVER "itkTestDriver") - -# Test data directory -set(TEST_HARNESS_TEMP_DIRECTORY ${SimpleITK_BINARY_DIR}/Testing/Temporary) -set(TEST_HARNESS_DATA_DIRECTORY ${SimpleITK_BINARY_DIR}/ExternalData/Testing/Data) # # CXX Examples @@ -174,367 +169,8 @@ sitk_add_test(NAME CXX.Example.DemonsRegistration2 -# -# Python Examples -# -sitk_add_python_test( Example.SimpleGaussian - "${SimpleITKExamples_SOURCE_DIR}/SimpleGaussian.py" - --compare - "${TEST_HARNESS_TEMP_DIRECTORY}/Python.SimpleGaussian.nrrd" - DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} - DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} - "2.0" - "${TEST_HARNESS_TEMP_DIRECTORY}/Python.SimpleGaussian.nrrd" ) - -sitk_add_python_test( Example.SimpleGaussianProcedural - "${SimpleITKExamples_SOURCE_DIR}/SimpleGaussianProcedural.py" - --compare - "${TEST_HARNESS_TEMP_DIRECTORY}/Python.SimpleGaussianProcedural.nrrd" - DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} - DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} - "2.0" - "${TEST_HARNESS_TEMP_DIRECTORY}/Python.SimpleGaussianProcedural.nrrd" ) - -sitk_add_python_test( Example.ImageCreateAndSet - "${SimpleITKExamples_SOURCE_DIR}/ImageCreateAndSet.py" ) - -sitk_add_python_test( Example.CannyEdge - "${SimpleITKExamples_SOURCE_DIR}/CannyEdge.py" - DATA{${SimpleITK_DATA_ROOT}/Input/OAS1_0001_MR1_mpr-1_anon.nrrd} ) - -sitk_add_python_test( Example.ExtractSlice - "${SimpleITKExamples_SOURCE_DIR}/ExtractSlice.py" - DATA{${SimpleITK_DATA_ROOT}/Input/OAS1_0001_MR1_mpr-1_anon.nrrd} - "30" - "${TEST_HARNESS_TEMP_DIRECTORY}/Python.ExtractSlice.nrrd") - -sitk_add_python_test( Example.BoarderSegmentation - "${SimpleITKExamples_SOURCE_DIR}/BoarderSegmentation.py" - DATA{${SimpleITK_DATA_ROOT}/Input/OAS1_0001_MR1_mpr-1_anon.nrrd} - "${TEST_HARNESS_TEMP_DIRECTORY}/Python.BoarderSegmentation.nrrd" - "5000" - "150" ) - - sitk_add_python_test( Example.N4BiasFieldCorrection - "${SimpleITKExamples_SOURCE_DIR}/N4BiasFieldCorrection.py" - DATA{${SimpleITK_DATA_ROOT}/Input/OAS1_0001_MR1_mpr-1_anon.nrrd} - "${TEST_HARNESS_TEMP_DIRECTORY}/Python.Example.N4BiasFieldCorrection.nrrd" - "1" ) - -sitk_add_python_test( Example.ReadAndShow - "${SimpleITKExamples_SOURCE_DIR}/ReadAndShow.py" - DATA{${SimpleITK_DATA_ROOT}/Input/VM1111Shrink-RGB.png} ) - -sitk_add_python_test( Example.GeodesicActiceContourSegmentation - "${SimpleITKExamples_SOURCE_DIR}/GeodesicActiceContourSegmentation.py" - DATA{${SimpleITK_DATA_ROOT}/Input/cthead1.png} - "${TEST_HARNESS_TEMP_DIRECTORY}/Python.Example.GeodesicActiceContourSegmentation.nrrd" - .3 10 .9 50 55 - ) - -sitk_add_python_test( Example.FFTConvolution - "${SimpleITKExamples_SOURCE_DIR}/FFTConvolution.py" - DATA{${SimpleITK_DATA_ROOT}/Input/cthead1-Float.mha} - DATA{${SimpleITK_DATA_ROOT}/Input/Gaussian_1.5.nrrd} - "${TEST_HARNESS_TEMP_DIRECTORY}/Python.Examples.FFTConvolution.nrrd" - ) - -if ( WRAP_PYTHON ) - sitk_add_python_test( Example.FilterProgressReporting - "${SimpleITKExamples_SOURCE_DIR}/FilterProgressReporting.py" - DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} - "2.0" - "${TEST_HARNESS_TEMP_DIRECTORY}/PythonFilterProgressReporting.nrrd" - ) - - set_tests_properties( Python.Example.FilterProgressReporting - PROPERTIES PASS_REGULAR_EXPRESSION "DiscreteGaussianImageFilter Progress" ) -endif() -sitk_add_python_test( Example.DicomSeriesReader - "${SimpleITKExamples_SOURCE_DIR}/DicomSeriesReader.py" - --compare-MD5 - "${TEST_HARNESS_TEMP_DIRECTORY}/DicomSeriesReader.nrrd" - "8e65f711d450b6b466c6d76a667ecb72" - DATA{${SimpleITK_DATA_ROOT}/Input/DicomSeries/,REGEX:Image[0-9]+.dcm} - "${TEST_HARNESS_TEMP_DIRECTORY}/DicomSeriesReader.nrrd" - ) -sitk_add_python_test( Example.DicomSeriesReader2 - "${SimpleITKExamples_SOURCE_DIR}/DicomSeriesReader2.py" - --compare-MD5 - "${TEST_HARNESS_TEMP_DIRECTORY}/DicomSeriesReader2.nrrd" - "8e65f711d450b6b466c6d76a667ecb72" - DATA{${SimpleITK_DATA_ROOT}/Input/DicomSeries/,REGEX:Image[0-9]+.dcm} - "${TEST_HARNESS_TEMP_DIRECTORY}/DicomSeriesReader2.nrrd" - ) - -sitk_add_python_test( Example.Segmentation.ConnectedThresholdImageFilter1 - "${SimpleITKExamples_SOURCE_DIR}/Segmentation/ConnectedThresholdImageFilter.py" - --compare-MD5 - "${TEST_HARNESS_TEMP_DIRECTORY}/PythonSegmentationConnectedThreshold1.png" - "d4ff9c512f9c18a84729677de800db0d" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySlice.png} - "${TEST_HARNESS_TEMP_DIRECTORY}/PythonSegmentationConnectedThreshold1.png" - 150 180 - 60 116 - ) - -sitk_add_python_test( Example.Segmentation.ConnectedThresholdImageFilter2 - "${SimpleITKExamples_SOURCE_DIR}/Segmentation/ConnectedThresholdImageFilter.py" - --compare-MD5 - "${TEST_HARNESS_TEMP_DIRECTORY}/PythonSegmentationConnectedThreshold2.png" - "a9695df04cde5b9c5481d8c253a5b3aa" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySlice.png} - "${TEST_HARNESS_TEMP_DIRECTORY}/PythonSegmentationConnectedThreshold2.png" - 210 250 - 81 112 - ) - -sitk_add_python_test( Example.Segmentation.NeighborhoodConnectedImageFilter1 - "${SimpleITKExamples_SOURCE_DIR}/Segmentation/NeighborhoodConnectedImageFilter.py" - --compare-MD5 - "${TEST_HARNESS_TEMP_DIRECTORY}/PythonSegmentationNeighborhoodConnected1.png" - "311d9d4b492e1ea625e3b0b295814dce" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySlice.png} - "${TEST_HARNESS_TEMP_DIRECTORY}/PythonSegmentationNeighborhoodConnected1.png" - 150 180 - 60 116 - ) - -sitk_add_python_test( Example.ImageRegistrationMethod1 - "${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethod1.py" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceShifted13x17y.png} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod11Test.hdf5 - TRANSFORM_COMPARE - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod11Test.hdf5 - DATA{${SimpleITK_DATA_ROOT}/Baseline/displacement_13x17y.mha} - 0.02 - ) - -sitk_add_python_test( Example.ImageRegistrationMethod2 - "${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethod2.py" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceShifted13x17y.png} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod2Test.hdf5 - TRANSFORM_COMPARE - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod2Test.hdf5 - DATA{${SimpleITK_DATA_ROOT}/Baseline/displacement_13x17y.mha} - 0.02 - ) - -sitk_add_python_test( Example.ImageRegistrationMethod3Test1 - "${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethod3.py" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceR10X13Y17.png} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod3Test1.hdf5 - TRANSFORM_COMPARE - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod3Test1.hdf5 - DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethod3Test1.mha} - 0.02 - ) - -sitk_add_python_test( Example.ImageRegistrationMethod3Test2 - "${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethod3.py" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceR10X13Y17S12.png} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod3Test2.hdf5 - TRANSFORM_COMPARE - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod3Test2.hdf5 - DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethod3Test2.mha} - 0.03 - ) - - -sitk_add_python_test( Example.ImageRegistrationMethod4Test1 - "${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethod4.py" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceShifted13x17y.png} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod4Test1.hdf5 - 24 1.0 - ) - -sitk_add_python_test( Example.ImageRegistrationMethod4Test2 - "${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethod4.py" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainT1SliceBorder20.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceShifted13x17y.png} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod4Test2.hdf5 - 24 0.1 - ) - -sitk_add_python_test( Example.ImageRegistrationMethod4Test3 - "${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethod4.py" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20Mask.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20Mask.png} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethod4Test3.hdf5 - 5 0.4 - ) - - -sitk_add_python_test(Example.ImageRegistrationMethodBSpline1 - "${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethodBSpline1.py" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBSplined10.png} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodBSpline1.hdf5 - TRANSFORM_COMPARE - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodBSpline1.hdf5 - DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethodBSpline1.mha} - 0.02 - ) - - -sitk_add_python_test(Example.ImageRegistrationMethodBSpline2 - "${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethodBSpline2.py" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainT1SliceBorder20.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBSplined10.png} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodBSpline2.hdf5 - TRANSFORM_COMPARE - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodBSpline2.hdf5 - DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethodBSpline2.mha} - 0.02 - ) - -sitk_add_python_test(Example.ImageRegistrationMethodDisplacement1 - "${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethodDisplacement1.py" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBSplined10.png} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodDisplacement1.hdf5 - TRANSFORM_COMPARE - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodDisplacement1.hdf5 - DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethodDisplacement1.mha} - 0.02 - ) - -sitk_add_python_test(Example.ImageRegistrationMethodDisplacement1Test2 - "${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethodDisplacement1.py" - DATA{${SimpleITK_DATA_ROOT}/Input/r16slice_rigid.nii.gz} - DATA{${SimpleITK_DATA_ROOT}/Input/r64slice.nii.gz} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodDisplacement1Test2.hdf5 - TRANSFORM_COMPARE - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodDisplacement1Test2.hdf5 - DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethodDisplacement1Test2.mha} - 0.02 - ) - -sitk_add_python_test(Example.ImageRegistrationMethodExhaustiveTest1 - "${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethodExhaustive.py" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySlice.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceR10X13Y17.png} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodExhaustiveTest1.hdf5 - TRANSFORM_COMPARE - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonImageRegistrationMethodExhaustiveTest1.hdf5 - DATA{${SimpleITK_DATA_ROOT}/Baseline/ImageRegistrationMethodExhaustiveTest1.mha} - 1e-10 - ) - - - -sitk_add_python_test(Example.DemonsRegistration1 - "${SimpleITKExamples_SOURCE_DIR}/DemonsRegistration1.py" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBSplined10.png} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonDemonsRegistration1Test.hdf5 - TRANSFORM_COMPARE - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonDemonsRegistration1Test.hdf5 - DATA{${SimpleITK_DATA_ROOT}/Baseline/DemonsRegistration1Test_displacement.mha} - 0.005 - ) - -sitk_add_python_test(Example.DemonsRegistration2 - "${SimpleITKExamples_SOURCE_DIR}/DemonsRegistration2.py" - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceShifted13x17y.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBSplined10.png} - DATA{${SimpleITK_DATA_ROOT}/Input/xforms/translation_-13x-17y.txt} - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonDemonsRegistration2Test.hdf5 - TRANSFORM_COMPARE - ${TEST_HARNESS_TEMP_DIRECTORY}/PythonDemonsRegistration2Test.hdf5 - DATA{${SimpleITK_DATA_ROOT}/Baseline/DemonsRegistration2Test_displacement.mha} - 0.01 - ) - -# -# Lua Examples -# -sitk_add_lua_test( Example.SimpleGaussian - "${SimpleITKExamples_SOURCE_DIR}/SimpleGaussian.lua" - --compare - "${TEST_HARNESS_TEMP_DIRECTORY}/Lua.SimpleGaussian.nrrd" - DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} - DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} - "2.0" - "${TEST_HARNESS_TEMP_DIRECTORY}/Lua.SimpleGaussian.nrrd" ) - -sitk_add_lua_test( Example.DicomSeriesReader - "${SimpleITKExamples_SOURCE_DIR}/DicomSeriesReader.lua" - --compare-MD5 - "${TEST_HARNESS_TEMP_DIRECTORY}/DicomSeriesReader.nrrd" - "8e65f711d450b6b466c6d76a667ecb72" - DATA{${SimpleITK_DATA_ROOT}/Input/DicomSeries/,REGEX:Image[0-9]+.dcm} - "${TEST_HARNESS_TEMP_DIRECTORY}/DicomSeriesReader.nrrd" - ) - -sitk_add_lua_test( Example.ImageRegistrationMethod1 - "${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethod1.lua" - ${TEST_HARNESS_DATA_DIRECTORY}/Input/BrainProtonDensitySliceBorder20.png - ${TEST_HARNESS_DATA_DIRECTORY}/Input/BrainProtonDensitySliceShifted13x17y.png - ${TEST_HARNESS_TEMP_DIRECTORY}/LuaImageRegistrationMethod1Test.hdf5 - TRANSFORM_COMPARE - ${TEST_HARNESS_TEMP_DIRECTORY}/LuaImageRegistrationMethod1Test.hdf5 - DATA{${SimpleITK_DATA_ROOT}/Baseline/displacement_13x17y.mha} - 0.02 - ) - - -# -# Ruby Examples -# -sitk_add_ruby_test( Example.SimpleGaussian - "${SimpleITKExamples_SOURCE_DIR}/SimpleGaussian.rb" - --compare - "${TEST_HARNESS_TEMP_DIRECTORY}/Ruby.SimpleGaussian.nrrd" - DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} - DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} - "2.0" - "${TEST_HARNESS_TEMP_DIRECTORY}/Ruby.SimpleGaussian.nrrd" ) - - - -# -# TCL Examples -# -sitk_add_tcl_test( Example.SimpleGaussian - "${SimpleITKExamples_SOURCE_DIR}/SimpleGaussian.tcl" - --compare - "${TEST_HARNESS_TEMP_DIRECTORY}/Tcl.SimpleGaussian.nrrd" - DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} - DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} - "2.0" - "${TEST_HARNESS_TEMP_DIRECTORY}/Tcl.SimpleGaussian.nrrd" ) - - -# -# JAVA Examples -# -sitk_add_java_test( Example.SimpleGaussian - "${SimpleITKExamples_SOURCE_DIR}/SimpleGaussian.java" - --compare - "${TEST_HARNESS_TEMP_DIRECTORY}/Java.SimpleGaussian.nrrd" - DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} - DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} - "2.0" - "${TEST_HARNESS_TEMP_DIRECTORY}/Java.SimpleGaussian.nrrd" ) - -if ( WRAP_JAVA ) - sitk_add_java_test( Example.FilterProgressReporting - "${SimpleITKExamples_SOURCE_DIR}/FilterProgressReporting.java" - DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} - "2.0" - "${TEST_HARNESS_TEMP_DIRECTORY}/Java.FilterProgressReporting.nrrd" - ) - set_tests_properties( Java.Example.FilterProgressReporting - PROPERTIES PASS_REGULAR_EXPRESSION "DiscreteGaussianImageFilter Progress" ) -endif ( WRAP_JAVA ) # This test currently does not compile or work # @@ -543,66 +179,5 @@ endif ( WRAP_JAVA ) -# -# R Examples -# -sitk_add_r_test( Example.SimpleGaussian - "--file=${SimpleITKExamples_SOURCE_DIR}/SimpleGaussian.R" - --compare - "${TEST_HARNESS_TEMP_DIRECTORY}/R.SimpleGaussian.nrrd" - DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} - --args - DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} - "2.0" - "${TEST_HARNESS_TEMP_DIRECTORY}/R.SimpleGaussian.nrrd" - ) -sitk_add_r_test( Example.FilterProgressReporting - "--file=${SimpleITKExamples_SOURCE_DIR}/FilterProgressReporting.R" - --args - DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} - 2.0 - "${TEST_HARNESS_TEMP_DIRECTORY}/R.FilterProgressReporting.nrrd" - ) - -sitk_add_r_test( Example.ImageRegistrationMethod1 - "--file=${SimpleITKExamples_SOURCE_DIR}/ImageRegistrationMethod1.R" - --args - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceBorder20.png} - DATA{${SimpleITK_DATA_ROOT}/Input/BrainProtonDensitySliceShifted13x17y.png} - ${TEST_HARNESS_TEMP_DIRECTORY}/RImageRegistrationMethod11Test.hdf5 - TRANSFORM_COMPARE - ${TEST_HARNESS_TEMP_DIRECTORY}/RImageRegistrationMethod11Test.hdf5 - DATA{${SimpleITK_DATA_ROOT}/Baseline/displacement_13x17y.mha} - 0.02 - ) - - -# -# CSharp Examples -# -sitk_add_csharp_test( Example.SimpleGaussian - "${SimpleITKExamples_SOURCE_DIR}/SimpleGaussian.cs" - --compare - "${TEST_HARNESS_TEMP_DIRECTORY}/CSharp.SimpleGaussian.nrrd" - DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleGaussian_2.0.nrrd} - DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} - "2.0" - "${TEST_HARNESS_TEMP_DIRECTORY}/CSharp.SimpleGaussian.nrrd" ) -if ( WRAP_CSHARP ) - sitk_add_csharp_test( Example.ImageGetBuffer - "${SimpleITKExamples_SOURCE_DIR}/ImageGetBuffer.cs" - DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd}) - set_tests_properties( CSharp.Example.ImageGetBuffer - PROPERTIES PASS_REGULAR_EXPRESSION "total: 1009713" ) - - sitk_add_csharp_test( Example.FilterProgressReporting - "${SimpleITKExamples_SOURCE_DIR}/FilterProgressReporting.cs" - DATA{${SimpleITK_DATA_ROOT}/Input/RA-Short.nrrd} - "2.0" - "${TEST_HARNESS_TEMP_DIRECTORY}/CSharp.FilterProgressReporting.nrrd" - ) - set_tests_properties( CSharp.Example.FilterProgressReporting - PROPERTIES PASS_REGULAR_EXPRESSION "DiscreteGaussianImageFilter Progress" ) -endif ( WRAP_CSHARP ) From 111a22ce63ac03a563b6aa0cd55081898b12bb4d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 22 Apr 2016 14:41:14 -0400 Subject: [PATCH 217/412] Correct typeo ImageSeriesWriter's Doxygen reference to procedural method Change-Id: I366d32f3afdf2b7a0dda421b6f9eea4c49f1ca28 --- Code/IO/include/sitkImageSeriesWriter.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/IO/include/sitkImageSeriesWriter.h b/Code/IO/include/sitkImageSeriesWriter.h index eb0a51a6b..ab8b50329 100644 --- a/Code/IO/include/sitkImageSeriesWriter.h +++ b/Code/IO/include/sitkImageSeriesWriter.h @@ -31,7 +31,7 @@ namespace itk { * \brief Writer series of image from a SimpleITK image. * * - * \sa itk::simple::WriterImage for the procedural interface + * \sa itk::simple::WriteImage for the procedural interface **/ class SITKIO_EXPORT ImageSeriesWriter : public ProcessObject From faa3e4764a104e791c5eece645394b3132ea78d2 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 22 Apr 2016 15:53:13 -0400 Subject: [PATCH 218/412] Renaming file with sitk prefix Change-Id: I399101b0bd47377ffd85749a6ebc97ee75b87d17 --- ...lerFlagSettings.cmake => sitkCompilerWarningsSettings.cmake} | 0 CMakeLists.txt | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename CMake/{CompilerFlagSettings.cmake => sitkCompilerWarningsSettings.cmake} (100%) diff --git a/CMake/CompilerFlagSettings.cmake b/CMake/sitkCompilerWarningsSettings.cmake similarity index 100% rename from CMake/CompilerFlagSettings.cmake rename to CMake/sitkCompilerWarningsSettings.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index 10027dd12..67d4029a3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -50,7 +50,7 @@ message(STATUS "Building SimpleITK version \"${SimpleITK_VERSION}\"") # This must be done before any other try compiles based tests are # done. include(sitkCheckRequiredFlags) -include(CompilerFlagSettings) +include(sitkCompilerWarningsSettings) find_package(ITK REQUIRED ) From a0984d460b9d4daba7a7fc84ff92b9a61fdd1144 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 22 Apr 2016 15:56:21 -0400 Subject: [PATCH 219/412] Replace '=' in CMake variable name This prevents the try_compile for -Wformat=2 flag from rerunning for every build. Change-Id: I792ab28eaff05afa520f42c60c8e85fe2840d820 --- CMake/sitkCompilerWarningsSettings.cmake | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/CMake/sitkCompilerWarningsSettings.cmake b/CMake/sitkCompilerWarningsSettings.cmake index 41a829ca8..7635eb408 100644 --- a/CMake/sitkCompilerWarningsSettings.cmake +++ b/CMake/sitkCompilerWarningsSettings.cmake @@ -21,8 +21,9 @@ include(CheckCXXCompilerFlag) function(test_cc_flags c_flag_var flag_list) set(local_c_flags "") foreach(flag IN LISTS ${flag_list}) - check_c_compiler_flag(${flag} C_HAS${flag}) - if(${C_HAS${flag}}) + string(REPLACE "=" "_" flag_var ${flag} ) + check_c_compiler_flag(${flag} C_HAS${flag_var}) + if(${C_HAS${flag_var}}) set(local_c_flags "${local_c_flags} ${flag}") endif() endforeach(flag) @@ -35,8 +36,9 @@ endfunction(test_cc_flags) function(test_cxx_flags cxx_flag_var flag_list) set(local_cxx_flags "") foreach(flag IN LISTS ${flag_list}) - check_cxx_compiler_flag(${flag} CXX_HAS${flag}) - if(${CXX_HAS${flag}}) + string(REPLACE "=" "_" flag_var ${flag} ) + check_cxx_compiler_flag(${flag} CXX_HAS${flag_var}) + if(${CXX_HAS${flag_var}}) set(local_cxx_flags "${local_cxx_flags} ${flag}") endif() endforeach(flag) From 78689fc7436db510af01328ffa78403a7df19906 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 26 Apr 2016 14:14:29 -0400 Subject: [PATCH 220/412] Fix "dist/dist" path for output of whl and eggs Change-Id: If69682151db7e778953dfbef8eca7fbd35065b3f --- Wrapping/Python/dist/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Wrapping/Python/dist/CMakeLists.txt b/Wrapping/Python/dist/CMakeLists.txt index b37d874dc..d5a6d4bd5 100644 --- a/Wrapping/Python/dist/CMakeLists.txt +++ b/Wrapping/Python/dist/CMakeLists.txt @@ -20,7 +20,7 @@ Using unknown versions of pip, setuptools and/or wheel packages/" ) add_custom_target( dist.Python ${VIRTUAL_PYTHON_EXECUTABLE} ${bdist_setup} ${bdist_commands} - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + WORKING_DIRECTORY ${SimpleITK_Python_BINARY_DIR} DEPENDS ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} COMMENT "Creating Python binary distribution" ) From 456fed879625fb72f1229d33f3ce15c553ab92b9 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 2 May 2016 10:06:21 -0400 Subject: [PATCH 221/412] Only add Example tests when testing is enabled Change-Id: Ifc78e2c1a8116195dc443d7efc721bfd87bb9c08 --- Examples/CMakeLists.txt | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index 91d40a5dd..25838ba40 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -64,14 +64,14 @@ macro(add_language_subdirectory lang) endif() endmacro() -add_language_subdirectory( CSharp ) -add_language_subdirectory( Java ) -add_language_subdirectory( Python ) -add_language_subdirectory( R ) -add_language_subdirectory( Ruby ) -add_language_subdirectory( Tcl ) - - if ( BUILD_TESTING ) add_subdirectory( test ) + + add_language_subdirectory( CSharp ) + add_language_subdirectory( Java ) + add_language_subdirectory( Python ) + add_language_subdirectory( R ) + add_language_subdirectory( Ruby ) + add_language_subdirectory( Tcl ) + endif() From 3f33c35d4c1e8d7cc844ac4c1c3326f17125af3f Mon Sep 17 00:00:00 2001 From: Paolo Zaffino Date: Tue, 1 Dec 2015 22:42:28 +0100 Subject: [PATCH 222/412] ENH: add SITK_GIT_PROTOCOL to enable user selection of the protocol Default to using the secure https protocol for downloading source code. Change-Id: Ie64e253e20c9c0934105ad569e7a2a20e16a027a --- SuperBuild/External_ITK.cmake | 3 ++- SuperBuild/External_Swig.cmake | 2 +- SuperBuild/SuperBuild.cmake | 16 ++++++++++++++-- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index b010edb75..42c59507e 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -32,7 +32,7 @@ VariableListToArgs( ITK_VARS ep_itk_args ) set(proj ITK) ## Use ITK convention of calling it ITK -set(ITK_REPOSITORY git://itk.org/ITK.git) +set(ITK_REPOSITORY "${git_protocol}://itk.org/ITK.git") # NOTE: it is very important to update the ITK_DIR path with the ITK version set(ITK_TAG_COMMAND GIT_TAG v4.9.1 ) @@ -67,6 +67,7 @@ ExternalProject_Add(${proj} -DITK_LEGACY_REMOVE:BOOL=ON -DITK_BUILD_DEFAULT_MODULES:BOOL=ON -DModule_ITKReview:BOOL=ON + -DITK_USE_GIT_PROTOCOL:BOOL=${ITK_USE_GIT_PROTOCOL} -DITK_WRAP_float:BOOL=ON -DITK_WRAP_unsigned_char:BOOL=ON -DITK_WRAP_signed_short:BOOL=ON diff --git a/SuperBuild/External_Swig.cmake b/SuperBuild/External_Swig.cmake index a60ce6620..f1e99e01a 100644 --- a/SuperBuild/External_Swig.cmake +++ b/SuperBuild/External_Swig.cmake @@ -19,7 +19,7 @@ if(NOT SWIG_DIR) endif() if( USE_SWIG_FROM_GIT ) - set(SWIG_GIT_REPOSITORY "git://github.com/swig/swig.git" CACHE STRING "URL of swig git repo") + set(SWIG_GIT_REPOSITORY "${git_protocol}://github.com/swig/swig.git" CACHE STRING "URL of swig git repo") set(SWIG_GIT_TAG "ec91de75b72ccb7ec20fffd5568dd38a966806e7" CACHE STRING "Tag in swig git repo") mark_as_advanced(SWIG_GIT_REPO) mark_as_advanced(SWIG_GIT_TAG) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 07dbe2d45..d1a45e3b8 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -1,5 +1,3 @@ -find_package(Git REQUIRED) - #----------------------------------------------------------------------------- # CTest Related Settings #----------------------------------------------------------------------------- @@ -70,6 +68,20 @@ else() set(gen "${CMAKE_GENERATOR}") endif() +#----------------------------------------------------------------------------- +# Use GIT protocol +#------------------------------------------------------------------------------ +find_package(Git) +set(SITK_GIT_PROTOCOL_default "https") +if (GIT_VERSION_STRING VERSION_LESS "1.7.10") + # minimum version for https support + set(SITK_GIT_PROTOCOL_default "git") +endif() +set(SITK_GIT_PROTOCOL ${SITK_GIT_PROTOCOL_default} CACHE STRING "If behind a firewall turn set this to 'https' or 'http'." ) +mark_as_advanced(SITK_GIT_PROTOCOL) +set_property(CACHE SITK_GIT_PROTOCOL PROPERTY STRINGS "https;http;git") +set(git_protocol ${SITK_GIT_PROTOCOL}) + #----------------------------------------------------------------------------- # SimpleITK options From 0210f1d469500836099bf8c02642a5f9f2bc4cc4 Mon Sep 17 00:00:00 2001 From: Matt McCormick Date: Tue, 3 May 2016 11:35:37 -0400 Subject: [PATCH 223/412] DOC: Update itk.org URL's for HTTPS support. SIMPLEITK-677 Change-Id: I9004498778d85388beaff9deaa9bbe662633b46b --- CMake/pre-commit | 2 +- CMake/sitkCheckCXX11.cmake | 2 +- CMake/sitkExternalData.cmake | 2 +- Documentation/Doxygen/Developer.dox | 2 +- Documentation/Doxygen/MainPage.dox | 2 +- Readme.md | 8 ++++---- Utilities/DevelopmentSetupScripts/SetupGerrit.sh | 2 +- Utilities/DevelopmentSetupScripts/SetupHooks.sh | 2 +- Utilities/Doxygen/Doxygen.cmake | 2 +- Utilities/Doxygen/ITKDoxygenTags.cmake | 2 +- Utilities/Maintenance/SourceTarball.bash | 2 +- Wrapping/Python/Packaging/setup.py.in | 2 +- Wrapping/R/Packaging/SimpleITK/DESCRIPTION.in | 2 +- .../R/Packaging/SimpleITK/vignettes/InsightArticle.cls | 4 ++-- .../Packaging/SimpleITK/vignettes/SimpleITK_tutorial.Rnw | 2 +- 15 files changed, 19 insertions(+), 19 deletions(-) diff --git a/CMake/pre-commit b/CMake/pre-commit index 9d41a6e40..139e6adb2 100755 --- a/CMake/pre-commit +++ b/CMake/pre-commit @@ -4,5 +4,5 @@ Paste the following commands into a shell: ./Utilities/SetupForDevelopment.sh -See http://www.itk.org/Wiki/ITK/Git/Develop for more details.' +See https://www.itk.org/Wiki/ITK/Git/Develop for more details.' exit 1 diff --git a/CMake/sitkCheckCXX11.cmake b/CMake/sitkCheckCXX11.cmake index dc28ce51f..7faf81c5b 100644 --- a/CMake/sitkCheckCXX11.cmake +++ b/CMake/sitkCheckCXX11.cmake @@ -83,5 +83,5 @@ if ( (NOT SITK_HAS_TR1_FUNCTIONAL AND NOT SITK_HAS_CXX11_FUNCTIONAL) "SimpleITK requires usage of C++11 or C++ Technical Report 1 (TR1).\n" "It may be available as an optional download for your compiler or difference CXX_FLAGS." "Please see the FAQs for details." - "http://www.itk.org/Wiki/SimpleITK/FAQ#Do_I_need_to_download_an_option_package_for_TR1_support.3F\n" ) + "https://www.itk.org/Wiki/SimpleITK/FAQ#Do_I_need_to_download_an_option_package_for_TR1_support.3F\n" ) endif ( ) diff --git a/CMake/sitkExternalData.cmake b/CMake/sitkExternalData.cmake index b50d89fad..67075bb82 100644 --- a/CMake/sitkExternalData.cmake +++ b/CMake/sitkExternalData.cmake @@ -40,7 +40,7 @@ if(NOT SITK_FORBID_DOWNLOADS) "https://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=%(hash)&algorithm=%(algo)" # Data published by developers using git-gerrit-push. - "http://www.itk.org/files/ExternalData/%(algo)/%(hash)" + "https://www.itk.org/files/ExternalData/%(algo)/%(hash)" ) endif() # Tell ExternalData commands not to transform raw files to content links. diff --git a/Documentation/Doxygen/Developer.dox b/Documentation/Doxygen/Developer.dox index 6d98259e3..2a7fed8b9 100644 --- a/Documentation/Doxygen/Developer.dox +++ b/Documentation/Doxygen/Developer.dox @@ -47,7 +47,7 @@ below. If you are not too familiar with these tools, this aspect of submitting patch to gerrit is the same as for ITK development. So the overview of ITK development process may be a better starting point: -http://www.itk.org/Wiki/ITK/Git/Develop +https://www.itk.org/Wiki/ITK/Git/Develop \subsection Add Binary Data to a Commit diff --git a/Documentation/Doxygen/MainPage.dox b/Documentation/Doxygen/MainPage.dox index 3969e895a..d229b3dd1 100644 --- a/Documentation/Doxygen/MainPage.dox +++ b/Documentation/Doxygen/MainPage.dox @@ -29,7 +29,7 @@ http://www.simpleitk.org The Home Page of the Insight toolkit can be found at : -http://www.itk.org +https://www.itk.org \section howto How to use this documentation diff --git a/Readme.md b/Readme.md index 42611f949..ed689493a 100644 --- a/Readme.md +++ b/Readme.md @@ -1,7 +1,7 @@ SimpleITK ========= -The goal of SimpleITK is to provide an abstraction layer to [ITK](http://www.itk.org) that enables developers and users to access the powerful features of the Insight Toolkit in a more simplified manner. SimpleITK's goal is to provide a simple layer to ITK's complicated C++ templeted API to be easily wrap-able in several languages including: +The goal of SimpleITK is to provide an abstraction layer to [ITK](https://www.itk.org) that enables developers and users to access the powerful features of the Insight Toolkit in a more simplified manner. SimpleITK's goal is to provide a simple layer to ITK's complicated C++ templeted API to be easily wrap-able in several languages including: * [Python](http://www.python.org) * [Java](http://www.java.com) @@ -10,11 +10,11 @@ The goal of SimpleITK is to provide an abstraction layer to [ITK](http://www.itk Wrapping is accomplished through [SWIG](http://www.swig.org), in principle, any language wrapped by SWIG should be applicable to SimpleITK. -SimpleITK is licensed under the [Apache License](http://www.opensource.org/licenses/apache2.0.php) in the [same way as ITK](http://www.itk.org/Wiki/ITK_Release_4/Licensing). +SimpleITK is licensed under the [Apache License](http://www.opensource.org/licenses/apache2.0.php) in the [same way as ITK](https://www.itk.org/Wiki/ITK_Release_4/Licensing). Development =========== -SimpleITK uses the [Git](http://git-scm.com/) distributed version control system. The main repository is hosted on [itk.org](http://itk.org/SimpleITK.git) and mirrored to [Github](https://blowekamp@github.com/SimpleITK/SimpleITK.git). There are two main branches, master and next. The "master" is a stable branch of the code, and suitable for most users, while "next" contains future features that are unlikely to be stable. +SimpleITK uses the [Git](http://git-scm.com/) distributed version control system. The main repository is hosted on [itk.org](https://itk.org/SimpleITK.git) and mirrored to [Github](https://blowekamp@github.com/SimpleITK/SimpleITK.git). There are two main branches, master and next. The "master" is a stable branch of the code, and suitable for most users, while "next" contains future features that are unlikely to be stable. -Documentation in maintained in [Doxygen](http://www.itk.org/SimpleITKDoxygen/html/annotated.html). [Development instructions](http://www.itk.org/SimpleITKDoxygen/html/pages.html) are also on this site. There is also the [Wiki](http://www.itk.org/Wiki/ITK_Release_4/SimpleITK) with additional information. SimpleITK requires a recent build of [ITK v4](http://itk.org/), but this can be automatically build along side SimpleITK with the SuperBuild cmake build. +Documentation in maintained in [Doxygen](https://www.itk.org/SimpleITKDoxygen/html/annotated.html). [Development instructions](https://www.itk.org/SimpleITKDoxygen/html/pages.html) are also on this site. There is also the [Wiki](https://www.itk.org/Wiki/ITK_Release_4/SimpleITK) with additional information. SimpleITK requires a recent build of [ITK v4](https://itk.org/), but this can be automatically build along side SimpleITK with the SuperBuild cmake build. diff --git a/Utilities/DevelopmentSetupScripts/SetupGerrit.sh b/Utilities/DevelopmentSetupScripts/SetupGerrit.sh index 194e9c53a..1c1857bac 100755 --- a/Utilities/DevelopmentSetupScripts/SetupGerrit.sh +++ b/Utilities/DevelopmentSetupScripts/SetupGerrit.sh @@ -48,7 +48,7 @@ gerrit_user() { For more information on Gerrit usage, see the ITK development process - http://www.itk.org/Wiki/ITK/Develop + https://www.itk.org/Wiki/ITK/Develop EOF } diff --git a/Utilities/DevelopmentSetupScripts/SetupHooks.sh b/Utilities/DevelopmentSetupScripts/SetupHooks.sh index 00f32229c..fecd2a6c4 100755 --- a/Utilities/DevelopmentSetupScripts/SetupHooks.sh +++ b/Utilities/DevelopmentSetupScripts/SetupHooks.sh @@ -20,7 +20,7 @@ # Run this script to set up the git hooks for committing changes to SimpleITK. # For more information, see: -# http://www.itk.org/Wiki/Git/Hooks +# https://www.itk.org/Wiki/Git/Hooks egrep-q() { egrep "$@" >/dev/null 2>/dev/null diff --git a/Utilities/Doxygen/Doxygen.cmake b/Utilities/Doxygen/Doxygen.cmake index 537501067..6c4b798fb 100644 --- a/Utilities/Doxygen/Doxygen.cmake +++ b/Utilities/Doxygen/Doxygen.cmake @@ -22,7 +22,7 @@ if (BUILD_DOXYGEN) -P "${PROJECT_SOURCE_DIR}/Utilities/Doxygen/ITKDoxygenTags.cmake" DEPENDS "${PROJECT_SOURCE_DIR}/Utilities/Doxygen/ITKDoxygenTags.cmake" ) - set(DOXYGEN_TAGFILES_PARAMETER "${PROJECT_BINARY_DIR}/Documentation/Doxygen/InsightDoxygen.tag=http://www.itk.org/Doxygen/html/") + set(DOXYGEN_TAGFILES_PARAMETER "${PROJECT_BINARY_DIR}/Documentation/Doxygen/InsightDoxygen.tag=https://www.itk.org/Doxygen/html/") endif() # diff --git a/Utilities/Doxygen/ITKDoxygenTags.cmake b/Utilities/Doxygen/ITKDoxygenTags.cmake index 45b11e8e9..3cdb7a165 100644 --- a/Utilities/Doxygen/ITKDoxygenTags.cmake +++ b/Utilities/Doxygen/ITKDoxygenTags.cmake @@ -32,7 +32,7 @@ if(EXISTS ${ITK_DOXYGEN_COMPRESSED_TAG_FILE}) if (${GZIP_OUT} ) MESSAGE(WARNING "gzip result message: " ${GZIP_OUT}) endif() - set(DOXYGEN_TAGFILES_PARAMETER "${ITK_DOXYGEN_TAG_FILE}=http://www.itk.org/Doxygen/html/") + set(DOXYGEN_TAGFILES_PARAMETER "${ITK_DOXYGEN_TAG_FILE}=https://www.itk.org/Doxygen/html/") endif() else() set(DOXYGEN_TAGFILES_PARAMETER "") diff --git a/Utilities/Maintenance/SourceTarball.bash b/Utilities/Maintenance/SourceTarball.bash index 4ba97ab57..43c57460e 100755 --- a/Utilities/Maintenance/SourceTarball.bash +++ b/Utilities/Maintenance/SourceTarball.bash @@ -56,7 +56,7 @@ validate_MD5() { download_object() { algo="$1" ; hash="$2" ; path="$3" mkdir -p $(dirname "$path") && - if wget "http://www.itk.org/files/ExternalData/$algo/$hash" -O "$path.tmp$$" 1>&2; then + if wget "https://www.itk.org/files/ExternalData/$algo/$hash" -O "$path.tmp$$" 1>&2; then mv "$path.tmp$$" "$path" elif wget "http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=$hash&algorithm=$algo" -O "$path.tmp$$" 1>&2; then mv "$path.tmp$$" "$path" diff --git a/Wrapping/Python/Packaging/setup.py.in b/Wrapping/Python/Packaging/setup.py.in index 2007345d2..45a80e950 100644 --- a/Wrapping/Python/Packaging/setup.py.in +++ b/Wrapping/Python/Packaging/setup.py.in @@ -64,7 +64,7 @@ setup( packages= ['SimpleITK'], package_dir = {'SimpleITK':r'@SIMPLEITK_PYTHON_PACKAGE_DIR@'}, package_data = {'SimpleITK':[r'@SIMPLEITK_RELATIVE_BINARY_MODULE@']}, - download_url = r'http://www.itk.org/SimpleITKDoxygen/html/PyDownloadPage.html', + download_url = r'https://www.itk.org/SimpleITKDoxygen/html/PyDownloadPage.html', platforms = [], description = r'Simplified interface to the Insight Toolkit for image registration and segmentation', long_description = 'Provide an abstraction layer to ITK that enables developers\ diff --git a/Wrapping/R/Packaging/SimpleITK/DESCRIPTION.in b/Wrapping/R/Packaging/SimpleITK/DESCRIPTION.in index d754ae169..859219fd1 100644 --- a/Wrapping/R/Packaging/SimpleITK/DESCRIPTION.in +++ b/Wrapping/R/Packaging/SimpleITK/DESCRIPTION.in @@ -12,6 +12,6 @@ Description: This package is an interface to SimpleITK, which is a simplified interface to the Insight Toolkit (ITKv@ITK_VERSION_MAJOR@.@ITK_VERSION_MINOR@.@ITK_VERSION_PATCH@) for medical image segmentation and registration. License: Apache 2.0 -URL: http://www.simpleitk.org, http://www.itk.org +URL: http://www.simpleitk.org, https://www.itk.org BugReports: http://issues.itk.org Maintainer: Richard Beare diff --git a/Wrapping/R/Packaging/SimpleITK/vignettes/InsightArticle.cls b/Wrapping/R/Packaging/SimpleITK/vignettes/InsightArticle.cls index e821da2cc..4f2caeb3d 100644 --- a/Wrapping/R/Packaging/SimpleITK/vignettes/InsightArticle.cls +++ b/Wrapping/R/Packaging/SimpleITK/vignettes/InsightArticle.cls @@ -76,11 +76,11 @@ % Define command to make reference to on-line Doxygen documentation \newcommand{\doxygen}[1]{ -\href{http://www.itk.org/Doxygen/html/classitk_1_1#1.html}{\code{itk::#1}}} +\href{https://www.itk.org/Doxygen/html/classitk_1_1#1.html}{\code{itk::#1}}} % Define command to make reference to on-line Doxygen documentation \newcommand{\subdoxygen}[2]{ -\href{http://www.itk.org/Doxygen/html/classitk_1_1#1_1_1#2.html}{\code{itk::#1::#2}}} +\href{https://www.itk.org/Doxygen/html/classitk_1_1#1_1_1#2.html}{\code{itk::#1::#2}}} % Define command for the standard comment introducing classes with similar functionalities \newcommand{\relatedClasses}{ diff --git a/Wrapping/R/Packaging/SimpleITK/vignettes/SimpleITK_tutorial.Rnw b/Wrapping/R/Packaging/SimpleITK/vignettes/SimpleITK_tutorial.Rnw index a605586ae..00b946db7 100644 --- a/Wrapping/R/Packaging/SimpleITK/vignettes/SimpleITK_tutorial.Rnw +++ b/Wrapping/R/Packaging/SimpleITK/vignettes/SimpleITK_tutorial.Rnw @@ -254,7 +254,7 @@ Testing. Beware of images from saved workspaces. External references, which is how images are represented, are not preserved when objects are saved to disk. Thus, attempting to use images from a saved workspace will result in ungraceful crashes. \section{Building and Installing} -Fetch SimpleITK from the git repository. Visit \url{http://www.itk.org/SimpleITKDoxygen/html/Wrapping.html} for the latest instructions on building and installing. +Fetch SimpleITK from the git repository. Visit \url{https://www.itk.org/SimpleITKDoxygen/html/Wrapping.html} for the latest instructions on building and installing. \section{Development} \end{document} From dab939787ce20e80a27096afefdeb3c68dcbfd6e Mon Sep 17 00:00:00 2001 From: Matt McCormick Date: Tue, 3 May 2016 13:13:25 -0400 Subject: [PATCH 224/412] DOC: Correct issue tracker URL to https://issues.itk.org Change-Id: Id1adcc24789a2c99dfafa595a78f46af60accef7 --- Wrapping/R/Packaging/SimpleITK/DESCRIPTION.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Wrapping/R/Packaging/SimpleITK/DESCRIPTION.in b/Wrapping/R/Packaging/SimpleITK/DESCRIPTION.in index 859219fd1..0770739f3 100644 --- a/Wrapping/R/Packaging/SimpleITK/DESCRIPTION.in +++ b/Wrapping/R/Packaging/SimpleITK/DESCRIPTION.in @@ -13,5 +13,5 @@ Description: This package is an interface to SimpleITK, which is a simplified and registration. License: Apache 2.0 URL: http://www.simpleitk.org, https://www.itk.org -BugReports: http://issues.itk.org +BugReports: https://issues.itk.org Maintainer: Richard Beare From d12c75e8ada3d49581ef0b6ff20e6de4cd0dfaee Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 4 May 2016 14:51:11 -0400 Subject: [PATCH 225/412] Restore missing dist target With out an explicit command, this was causing failure of the target on windows, and resulting in the packages missing. Change-Id: I2ffd73d6c34e7ee7025fdbcdbfdc138c008c2b31 --- Wrapping/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index 91dd86ac9..537350201 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -2,6 +2,7 @@ # A general packaging target, not built by default, to build packages for each # language. This should depend on all language specific targets. +add_custom_target( dist ${CMAKE_COMMAND} -E echo "Finished generating wrapped packages for distribution..." ) # # lua SWIG configuration From 77f269fcf1b5ddcbf2e5c4ae119d8700af857631 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 4 May 2016 15:17:48 -0400 Subject: [PATCH 226/412] Enable Python wheels over eggs by default Change-Id: Ib0ab83d9b935d372ebaff591f5410f44b6096097 --- Wrapping/Python/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index 24cde4230..d66496019 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -24,9 +24,9 @@ include_directories ( ${PYTHON_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ) # option ( SimpleITK_PYTHON_THREADS "Enable threaded python usage by unlocking the GIL." ON ) mark_as_advanced( SimpleITK_PYTHON_THREADS ) -option ( SimpleITK_PYTHON_EGG "Add building of python eggs to the dist target." ON ) +option ( SimpleITK_PYTHON_EGG "Add building of python eggs to the dist target." OFF ) mark_as_advanced( SimpleITK_PYTHON_EGG ) -option ( SimpleITK_PYTHON_WHEEL "Add building of python wheels to the dist target." OFF ) +option ( SimpleITK_PYTHON_WHEEL "Add building of python wheels to the dist target." ON ) mark_as_advanced( SimpleITK_PYTHON_WHEEL ) From 04175e781b15de8b0d359e8cd81fae43bdd92f09 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 5 May 2016 13:23:15 -0400 Subject: [PATCH 227/412] Adding Powell optimizer to registration Change-Id: Ic695352223f7e8c5bf6b3d131e80fe5acd2babe1 --- .../include/sitkImageRegistrationMethod.h | 17 ++++++++- .../src/sitkImageRegistrationMethod.cxx | 15 ++++++++ ...mageRegistrationMethod_CreateOptimizer.cxx | 19 ++++++++++ .../Unit/sitkImageRegistrationMethodTests.cxx | 35 +++++++++++++++++++ 4 files changed, 85 insertions(+), 1 deletion(-) diff --git a/Code/Registration/include/sitkImageRegistrationMethod.h b/Code/Registration/include/sitkImageRegistrationMethod.h index 8f3f11496..0a308e37b 100644 --- a/Code/Registration/include/sitkImageRegistrationMethod.h +++ b/Code/Registration/include/sitkImageRegistrationMethod.h @@ -332,6 +332,17 @@ namespace simple std::vector GetOptimizerWeights( ) const; /**@}*/ + /** \brief Powell optimization using Brent line search. + * + * \sa itk::PowellOptimizerv4 + */ + Self& SetOptimizerAsPowell(unsigned int numberOfIterations = 100, + unsigned int maximumLineIterations = 100, + double stepLength = 1, + double stepTolerance = 1e-6, + double valueTolerance = 1e-6 ); + + /** \brief Manually set per parameter weighting for the transform parameters. */ Self& SetOptimizerScales( const std::vector &scales ); @@ -594,7 +605,8 @@ namespace simple GradientDescentLineSearch, LBFGSB, Exhaustive, - Amoeba + Amoeba, + Powell }; OptimizerType m_OptimizerType; double m_OptimizerLearningRate; @@ -623,6 +635,9 @@ namespace simple double m_OptimizerParametersConvergenceTolerance; double m_OptimizerFunctionConvergenceTolerance; bool m_OptimizerWithRestarts; + unsigned int m_OptimizerMaximumLineIterations; + double m_OptimizerStepTolerance; + double m_OptimizerValueTolerance; std::vector m_OptimizerWeights; diff --git a/Code/Registration/src/sitkImageRegistrationMethod.cxx b/Code/Registration/src/sitkImageRegistrationMethod.cxx index 3eb583892..85bc0d36b 100644 --- a/Code/Registration/src/sitkImageRegistrationMethod.cxx +++ b/Code/Registration/src/sitkImageRegistrationMethod.cxx @@ -334,6 +334,21 @@ ImageRegistrationMethod::SetOptimizerAsAmoeba( double simplexDelta, return *this; } +ImageRegistrationMethod::Self& +ImageRegistrationMethod::SetOptimizerAsPowell(unsigned int numberOfIterations, + unsigned int maximumLineIterations, + double stepLength, + double stepTolerance, + double valueTolerance ) +{ + m_OptimizerType = Powell; + m_OptimizerNumberOfIterations = numberOfIterations; + m_OptimizerMaximumLineIterations = maximumLineIterations; + m_OptimizerStepLength = stepLength; + m_OptimizerStepTolerance = stepTolerance; + m_OptimizerValueTolerance = valueTolerance; +} + ImageRegistrationMethod::Self& ImageRegistrationMethod::SetOptimizerScales( const std::vector &scales) { diff --git a/Code/Registration/src/sitkImageRegistrationMethod_CreateOptimizer.cxx b/Code/Registration/src/sitkImageRegistrationMethod_CreateOptimizer.cxx index 32a6cf467..926b2e0a1 100644 --- a/Code/Registration/src/sitkImageRegistrationMethod_CreateOptimizer.cxx +++ b/Code/Registration/src/sitkImageRegistrationMethod_CreateOptimizer.cxx @@ -23,6 +23,7 @@ #include "itkLBFGSBOptimizerv4.h" #include "itkExhaustiveOptimizerv4.h" #include "itkAmoebaOptimizerv4.h" +#include namespace { @@ -258,6 +259,24 @@ namespace simple this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer); this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer); + optimizer->Register(); + return optimizer.GetPointer(); + } + else if ( m_OptimizerType == Powell ) + { + typedef itk::PowellOptimizerv4 _OptimizerType; + _OptimizerType::Pointer optimizer = _OptimizerType::New(); + + optimizer->SetMaximumIteration( this->m_OptimizerNumberOfIterations ); + optimizer->SetMaximumLineIteration( this->m_OptimizerMaximumLineIterations ); + optimizer->SetStepLength(this->m_OptimizerStepLength ); + optimizer->SetStepTolerance( this->m_OptimizerStepTolerance ); + optimizer->SetValueTolerance( this->m_OptimizerValueTolerance ); + + this->m_pfGetMetricValue = nsstd::bind(&_OptimizerType::GetValue,optimizer.GetPointer()); + this->m_pfGetOptimizerIteration = nsstd::bind(&_OptimizerType::GetCurrentIteration,optimizer.GetPointer()); + this->m_pfGetOptimizerPosition = nsstd::bind(&PositionOptimizerCustomCast::CustomCast,optimizer.GetPointer()); + optimizer->Register(); return optimizer.GetPointer(); } diff --git a/Testing/Unit/sitkImageRegistrationMethodTests.cxx b/Testing/Unit/sitkImageRegistrationMethodTests.cxx index aaf5564e9..de534cf4e 100644 --- a/Testing/Unit/sitkImageRegistrationMethodTests.cxx +++ b/Testing/Unit/sitkImageRegistrationMethodTests.cxx @@ -625,6 +625,41 @@ TEST_F(sitkRegistrationMethodTest, Optimizer_Amoeba) } + +TEST_F(sitkRegistrationMethodTest, Optimizer_Powell) +{ + sitk::Image image = MakeGaussianBlob( v2(64, 64), std::vector(2,256) ); + + + sitk::ImageRegistrationMethod R; + R.SetInterpolator(sitk::sitkLinear); + + sitk::TranslationTransform tx(image.GetDimension()); + tx.SetOffset(v2(-1,-2)); + R.SetInitialTransform(tx, false); + + R.SetMetricAsMeanSquares(); + + R.SetOptimizerAsPowell(10, 50, .2, .01, .0001 ); + + IterationUpdate cmd(R); + R.AddCommand(sitk::sitkIterationEvent, cmd); + + sitk::Transform outTx = R.Execute(image, image); + + + std::cout << "-------" << std::endl; + std::cout << outTx.ToString() << std::endl; + std::cout << "Optimizer stop condition: " << R.GetOptimizerStopConditionDescription() << std::endl; + std::cout << " Iteration: " << R.GetOptimizerIteration() << std::endl; + std::cout << " Metric value: " << R.GetMetricValue() << std::endl; + + EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,0.0), outTx.GetParameters(), 1e-3); + + +} + + TEST_F(sitkRegistrationMethodTest, Optimizer_ScalesEstimator) { sitk::Image fixedImage = MakeDualGaussianBlobs( v2(64, 64), v2(54, 74), std::vector(2,256) ); From 06465490fea33addfec23582011cf439ab2f3184 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 5 May 2016 14:54:24 -0400 Subject: [PATCH 228/412] BUG: Remove implicit deep copy in ImportImageFilter The purpose of the ImportImageFilter is to enable SimpleITK to share the buffer with an external application. The shallow copy or sharing of the buffer with SimpleITK is now restored. The implicit copy was occurring because the constructed ITK image was used by the sitk::Image. Then the sitk::Image was modified, causing the copy. This has been corrected by setting all attributes in the ITK image, and constructing the sitk::Image on the return. Change-Id: Iebf0df2c4a81fb6db6f09049e36fd58759f451d2 --- Code/IO/include/sitkImportImageFilter.h | 5 ++- Code/IO/src/sitkImportImageFilter.cxx | 55 ++++++++++++------------- Testing/Unit/sitkImportImageTest.cxx | 29 +++++++++++++ 3 files changed, 59 insertions(+), 30 deletions(-) diff --git a/Code/IO/include/sitkImportImageFilter.h b/Code/IO/include/sitkImportImageFilter.h index 42defe748..7379ca171 100644 --- a/Code/IO/include/sitkImportImageFilter.h +++ b/Code/IO/include/sitkImportImageFilter.h @@ -32,7 +32,10 @@ namespace itk { * * This filter is intended to interface SimpleITK to other image processing * libraries and applications that may have their own representation of an - * image class. + * image class. It creates a SimpleITK image which shares the bulk + * data buffer as what is set. SimpleITK will not responsible to + * delete the buffer afterwards, and it buffer must remain valid + * while in use. * * \sa itk::simple::ImportAsInt8, itk::simple::ImportAsUInt8, * itk::simple::ImportAsInt16, itk::simple::ImportAsUInt16, diff --git a/Code/IO/src/sitkImportImageFilter.cxx b/Code/IO/src/sitkImportImageFilter.cxx index a4f99b84b..25e15bf0e 100644 --- a/Code/IO/src/sitkImportImageFilter.cxx +++ b/Code/IO/src/sitkImportImageFilter.cxx @@ -472,6 +472,20 @@ Image ImportImageFilter::ExecuteInternal( ) typename ImageType::Pointer image = ImageType::New(); + + + // + // Origin + // + typename ImageType::PointType origin = sitkSTLVectorToITK< typename ImageType::PointType >( this->m_Origin ); + image->SetOrigin( origin ); + + // + // Spacing + // + typename ImageType::SpacingType spacing = sitkSTLVectorToITK< typename ImageType::SpacingType >( this->m_Spacing ); + image->SetSpacing( spacing ); + // // Size and Region // @@ -481,6 +495,15 @@ Image ImportImageFilter::ExecuteInternal( ) // set the size and region to the ITK image. image->SetRegions( region ); + // + // Direction, if m_Direction is not set, use ITK's default which is + // an identity. + // + if (this->m_Direction.size() != 0 ) + { + image->SetDirection( sitkSTLToITKDirection( this->m_Direction ) ); + } + size_t numberOfElements = m_NumberOfComponentsPerPixel; for(unsigned int si = 0; si < Dimension; si++ ) @@ -501,35 +524,9 @@ Image ImportImageFilter::ExecuteInternal( ) // this->SetNumberOfComponentsOnImage( image.GetPointer() ); - Image sitkimage( image ); - - this->m_Origin.resize( Dimension ); - this->m_Spacing.resize( Dimension ); - - sitkimage.SetOrigin( this->m_Origin ); - sitkimage.SetSpacing( this->m_Spacing ); - - if (this->m_Direction.size() != 0 ) - sitkimage.SetDirection( this->m_Direction ); - else if (Dimension == 2) - { - // make a 2x2 identity matrix - std::vector dir(4, 0.); - dir[0] = 1.; - dir[3] = 1.; - sitkimage.SetDirection( dir ); - } - else if (Dimension == 3) - { - // make a 3x3 identity matrix - std::vector dir(9, 0.); - dir[0] = 1.; - dir[4] = 1.; - dir[8] = 1.; - sitkimage.SetDirection( dir ); - } - - return sitkimage; + // This line must be the last line in the function to prevent a deep + // copy caused by a implicit sitk::MakeUnique + return Image( image ); } template diff --git a/Testing/Unit/sitkImportImageTest.cxx b/Testing/Unit/sitkImportImageTest.cxx index 5a45f69d8..499193b91 100644 --- a/Testing/Unit/sitkImportImageTest.cxx +++ b/Testing/Unit/sitkImportImageTest.cxx @@ -198,6 +198,35 @@ TEST_F(Import,Direction) { } +TEST_F(Import,Shallow) { + + // This test is designed to verify the buffer is shared + + uint8_buffer = std::vector< uint8_t >( 128*128*128, 17 ); + + sitk::ImportImageFilter importer; + importer.SetSize( std::vector< unsigned int >( 3, 128u ) ); + importer.SetBufferAsUInt8( &uint8_buffer[0] ); + + sitk::Image image = importer.Execute(); + + ASSERT_EQ( image.GetDimension(), 3u ) << "image dimension check"; + + + + EXPECT_EQ ( "a2178ce2d158a4a7c5a9ef3d03a33a6099b9c5be", sitk::Hash( image ) ) << " hash value for basic uin8_t"; + + std::vector idx(3, 0 ); + uint8_buffer[0] = 19; + EXPECT_EQ ( 19, uint8_buffer[0] ) << " direct setting of buffer"; + EXPECT_EQ ( 19, image.GetPixelAsUInt8(idx) ) << " buffer modifying image"; + + image.SetPixelAsUInt8(idx, 23); + EXPECT_EQ ( 23, image.GetPixelAsUInt8(idx) ) << " direct setting of image"; + EXPECT_EQ ( 23, uint8_buffer[0] ) << " image modifying buffer"; + +} + TEST_F(Import,ExhaustiveTypes) { sitk::ImportImageFilter importer; From 1ea35f095efee8a3ee277e299d81de88977da90e Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Wed, 6 Apr 2016 20:17:33 +1000 Subject: [PATCH 229/412] R documentation for procedural interface. Some very basic documentation for the procedural interface in R. It consists of c++ signatures, which at least gives the various signatures to help guessing argument order etc. Extended usage to indicate that R requires an output folder. Change-Id: Id62710a394501d9aa063c7df81443792190942e4 --- Utilities/GenerateDocs/doxy2swig.py | 129 +++++++++++++++++++++++++++- Utilities/GenerateDocs/doxyall.py | 12 ++- 2 files changed, 137 insertions(+), 4 deletions(-) diff --git a/Utilities/GenerateDocs/doxy2swig.py b/Utilities/GenerateDocs/doxy2swig.py index c492fb85c..84cc78ba0 100755 --- a/Utilities/GenerateDocs/doxy2swig.py +++ b/Utilities/GenerateDocs/doxy2swig.py @@ -408,6 +408,7 @@ def clean_pieces(self, pieces): ret.extend([_tmp, '\n\n']) return ret + class Doxy2R(Doxy2SWIG): def __init__(self, src, javaFlag=0): Doxy2SWIG.__init__(self, src, javaFlag) @@ -569,13 +570,139 @@ def do_doxygenindex(self, node): p.generate() self.pieces.extend(self.clean_pieces(p.pieces)) +## For the procedural interface +## This will produce multiple Rd files, and is therefore +## quite different to the others +## Text is now stored in piecesdict +## add_text uses a variable to track the name + +class Doxy2RProc(Doxy2SWIG): + def __init__(self, src, javaFlag=0): + Doxy2SWIG.__init__(self, src, javaFlag) + """ Turns on the title, brief description and detailed description markup. + Turn them off when inside member documentatation. + + """ + self.FilterTitle = True + self.EmptyText = False + self.piecesdict = dict() + self.currentFunc='' + + def parse_Text(self, node): + txt = node.data + txt = txt.replace('\\', r'\\\\') + txt = txt.replace('"', r'\"') + # ignore pure whitespace + m = self.space_re.match(txt) + if m and len(m.group()) == len(txt): + # Flag the text being empty + self.EmptyText = True + pass + else: + self.add_text(textwrap.fill(txt)) + + def add_text(self, value): + """Adds text corresponding to `value` into `self.pieces`.""" + if not self.currentname in self.piecesdict: + self.piecesdict[self.currentname]=[] + if type(value) in (list, tuple): + self.piecesdict[self.currentname].extend(value) + else: + self.piecesdict[self.currentname].append(value) + + + def do_includes(self, node): + self.add_text('%C++ includes: ') + self.generic_parse(node, pad=1) + + def do_detaileddescription(self, node): + if self.FilterTitle: + self.add_text('\\details{') + self.generic_parse(node, pad=1) + if self.FilterTitle: + # check that we actually got a detailed description. + # Not having a title is illegal in R + # use the class name otherwise + self.add_text('}\n') + def do_briefdescription(self, node): + # there are brief descriptions all over the place and + # we don't want them all to be titles + if self.FilterTitle: + self.add_text('\\description{') + self.generic_parse(node, pad=0) + if self.FilterTitle: + # if the title is empty, then we'll use the name + if self.EmptyText: + self.add_text(self.sitkClassName) + self.add_text('}\n') + self.EmptyText = False + + def do_memberdef(self, node): + prot = node.attributes['prot'].value + id = node.attributes['id'].value + kind = node.attributes['kind'].value + tmp = node.parentNode.parentNode.parentNode + compdef = tmp.getElementsByTagName('compounddef')[0] + cdef_kind = compdef.attributes['kind'].value + + self.FilterTitle = False; + + if prot == 'public': + first = self.get_specific_nodes(node, ('definition', 'name')) + name = first['name'].firstChild.data + if name[:8] == 'operator': # Don't handle operators yet. + return + # names are overloaded, of course, and need + # to be collected into the same R file + defn = first['definition'].firstChild.data + anc = node.parentNode.parentNode + # need to worry about documenting these for the procedural interface + # We want to document overloaded names in the same file, + # which means we'll need to store a map of individual + # file contents + if cdef_kind in ('namespace'): + # do we already have something by this name + self.currentname=name + others = self.get_specific_nodes(node, ('argsstring', 'briefdescription', + 'detaileddescription')) + argstring = others['argsstring'].firstChild.data + if not name in self.piecesdict: + # first time we've hit this name, so add the name, alias and title + self.add_text('\\title{%s}\n' %(name)) + self.add_text('\\name{%s}\n' %(name)) + self.add_text('\\alias{%s}\n' %(name)) + self.add_text('\\description{\n') + self.generic_parse(others['briefdescription']) + self.add_text('\n}\n\n') + self.add_text('\\details{\n') + self.generic_parse(others['detaileddescription']) + self.add_text('\n}\n\n') + + # now the potentially repeated bits (overloading) + usage=defn + argstring + self.add_text('\\usage{\n%s\n}\n' %(usage)) + + def do_sectiondef(self, node): + kind = node.attributes['kind'].value + if kind in ('public-func', 'func'): + self.generic_parse(node) + + + def write(self, fname, mode='w'): + ## fname is the destination folder + if os.path.isdir(fname): + for FuncName in self.piecesdict: + outname=os.path.join(fname, FuncName + ".Rd") + self.pieces = self.piecesdict[FuncName] + Doxy2SWIG.write(self,outname) + else: + assert False, "Destination path doesn't exist" def main(input, output): p = Doxy2SWIG(input) p.generate() p.write(output) - if __name__ == '__main__': if len(sys.argv) != 3: print (__doc__) diff --git a/Utilities/GenerateDocs/doxyall.py b/Utilities/GenerateDocs/doxyall.py index e88ebac1a..51ebba187 100755 --- a/Utilities/GenerateDocs/doxyall.py +++ b/Utilities/GenerateDocs/doxyall.py @@ -6,12 +6,11 @@ def usage(): - print( "\ndoxyall.py [options] doxygen_xml_dir output.i|outputdir" ) + print( "\ndoxyall.py [options] doxygen_xml_dir output.i|output_directory" ) print( "" ) print( " -h, --help This help message" ) print( " -j, --java Java style output" ) - print( " -r, --R R style output - destination must be a directory" ) - + print( " -r, --R R style output - note that output directory must be specified for R" ) print( "" ) @@ -123,6 +122,13 @@ def usage(): flog.close() +# the procedural interface +if rFlag: + nspacefile=os.path.join(indir, "namespaceitk_1_1simple.xml") + p = Doxy2RProc(nspacefile) + p.generate() + p.write(outdir) + os.close(tmpfd) os.close(logfd) From 8f7d387e39dc3b90ac4c1747c22b3ca71d75d052 Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Tue, 26 Apr 2016 17:05:32 +1000 Subject: [PATCH 230/412] Single functions for pixel access This patch creates a single SetPixel function and the corresponding GetPixel function. It isn't quite as nice as the python equivalent as the swig extend mechanism doesn't have an obvious way to directly add R code. Instead we create a dummy C function to force the appropriate entry in the method list and overwrite it with a hand generated R function in zA.R Test now covers both scalars and vectors for setting and getting. Label image types are also tested. The Get/Set methods for sitkLabelUInt8 are the same as for sitkUInt8. itk::simple::Unused included in dummy Set/Get methods. This patch is replacing the original, now based on upstream/master Change-Id: If3e613c67ee31b3b5b7af566739643103cfe0bfb --- Testing/Unit/RPixelAccess.R | 68 ++++++++++++++++++++++++++- Wrapping/R/Packaging/SimpleITK/R/zA.R | 52 +++++++++++++++++++- Wrapping/R/R.i | 21 +++++++++ 3 files changed, 137 insertions(+), 4 deletions(-) diff --git a/Testing/Unit/RPixelAccess.R b/Testing/Unit/RPixelAccess.R index 36950c560..90b5e9a4e 100644 --- a/Testing/Unit/RPixelAccess.R +++ b/Testing/Unit/RPixelAccess.R @@ -16,9 +16,9 @@ targs <- c("sitkVectorUInt8", "sitkVectorInt8", "sitkVectorUInt16", "sitkVectorUInt64", "sitkVectorInt64", "sitkVectorFloat32", "sitkVectorFloat64") names(targs) <- targs + + castims <- lapply(targs, function(m)Cast(fr, m)) -res<-list() -pixvals <- list() vectorextract <- sapply(castims, function(K)K[3,4]) channelextract <- sapply(castims, function(K)K[[1]][3,4]) @@ -37,3 +37,67 @@ if (any(channelextract != 2) ) cat("Pixel type: ", targs[channelextract != 2], "\n") quit(save="no", status=1) } + +## Test the methods introduced via the "extend" mechanism + +vectorextractGet <-sapply(castims, function(K)K$GetPixel(c(3,4)-1)) +channelextractGet <- sapply(castims, function(K)K[[1]]$GetPixel(c(3,4)-1)) + +if (any(vectorextractGet[1,] != 2) | any(vectorextractGet[2,] != 3)) +{ + cat("Failure in vector extraction using GetPixel\n") + cat("Pixel type :", targs[(vectorextractGet[1,] != 2) | + (vectorextractGet[2,] != 3)], "\n") + quit(save="no", status=1) +} + +## testing reading scalar +if (any(channelextractGet != 2) ) +{ + cat("Failure in channel extraction\n") + cat("Pixel type: ", targs[channelextractGet != 2], "\n") + quit(save="no", status=1) +} + +## Test the SetPixel method - this tests setting vector +## recreate castims so we can write to it +castims <- lapply(targs, function(m)Cast(fr, m)) + +sapply(castims, function(K)K$SetPixel(c(0,0), c(10,11))) +VecModified <- sapply(castims, function(K)K$GetPixel(c(0,0))) +if (any(VecModified[1,] != 10) | any(VecModified[2,] != 11) ) +{ + cat("Failure in SetPixel vector test\n") + cat("Pixel type: ", targs[(VecModified[1,] != 10) | (VecModified[2,] != 11)], "\n") + quit(save="no", status=1) +} + +## Test the SetPixel method - this tests setting scalar +## recreate castims so we can write to it +castims <- lapply(targs, function(m)Cast(fr, m)) + +FirstChannel <- lapply(castims, function(K)K[[1]]) +sapply(FirstChannel, function(K)K$SetPixel(c(0,0), 12)) +channelModified <- sapply(FirstChannel, function(K)K$GetPixel(c(0,0))) +if (any(channelModified != 12) ) +{ + cat("Failure in SetPixel scalar test\n") + cat("Pixel type: ", targs[channelModified != 12], "\n") + quit(save="no", status=1) +} + +## Test label pixels +labtargs <- c("sitkLabelUInt8", "sitkLabelUInt16", "sitkLabelUInt32", "sitkLabelUInt64") +names(labtargs) <- labtargs + +labims <- lapply(labtargs, function(tt)Image(c(5,5), tt)) + +l <- lapply(labims, function(K)K$SetPixel(c(1,2), 7)) +labvals <- sapply(labims, function(K)K$GetPixel(c(1,2))) + +if (any(labvals != 7)) +{ + cat("Failure in SetPixel/GetPixel label test\n") + print(labvals) + quit(save="no", status=1) +} diff --git a/Wrapping/R/Packaging/SimpleITK/R/zA.R b/Wrapping/R/Packaging/SimpleITK/R/zA.R index 180f6c5dd..0186ada88 100644 --- a/Wrapping/R/Packaging/SimpleITK/R/zA.R +++ b/Wrapping/R/Packaging/SimpleITK/R/zA.R @@ -31,11 +31,17 @@ createPixLookup <- function( where = topenv(parent.frame())) ff <- gsub("^sitk(.+)", "Image_GetPixelAs\\1", n) ff <- gsub("AsFloat32$", "AsFloat", ff) ff <- gsub("AsFloat64$", "AsDouble", ff) - + ff <- gsub("Label", "", ff) sitkPixelAccessMap <- mget(ff, envir=where, ifnotfound=rep(NA,length(ff))) + ff2 <- gsub("GetPixelAs", "SetPixelAs", ff) + sitkPixelSetMap <- mget(ff2, envir=where, + ifnotfound=rep(NA,length(ff))) + names(sitkPixelAccessMap) <- n + names(sitkPixelSetMap) <- n assign("sitkPixelAccessMap", sitkPixelAccessMap, envir=where) + assign("sitkPixelSetMap", sitkPixelSetMap, envir=where) } ImportPixVec <- function(VP) @@ -55,7 +61,49 @@ ImportPixVec <- function(VP) return(res) } - # experimental bracket operator for images +## SetPixel and GetPixel methods. We've provided dummy "extends" methods for these. +## We'll overwite the bindings here +Image_SetPixel = function(self, idx, v) +{ + idx = as.integer(idx); + ## check that the size of v matches the image pixel type + if (Image_GetNumberOfComponentsPerPixel(self) != length(v)) + { + ## It seems that passing incorrect size values doesn't + ## cause a c++ error, so check here. Swig must + ## cleverly pass just the first element. + stop("Error in SetPixel - value does not match image depth") + } + PixType <- Image_GetPixelID(self) + sF <- sitkPixelSetMap[[PixType]] + if (!is.null(sF)) { + invisible(sF(self, idx, v)) + } else { + stop("Error in SetPixel - no accessor function for this pixel type") + } +} + +attr(`Image_SetPixel`, 'returnType') = 'void' +attr(`Image_SetPixel`, "inputTypes") = c('_p_itk__simple__Image', 'integer', 'numeric') +class(`Image_SetPixel`) = c("SWIGFunction", class('Image_SetPixel')) + +Image_GetPixel = function(self, idx, .copy = FALSE) +{ + idx = as.integer(idx); + PixType <- Image_GetPixelID(self) + aF <- sitkPixelAccessMap[[PixType]] + if (!is.null(aF)) { + return(aF(self, idx)) + } else { + stop("Error in GetPixel - no accessor function for this pixel type") + } +} + +attr(`Image_GetPixel`, 'returnType') = 'numeric' +attr(`Image_GetPixel`, "inputTypes") = c('_p_itk__simple__Image', 'integer') +class(`Image_GetPixel`) = c("SWIGFunction", class('Image_GetPixel')) + +## experimental bracket operator for images setMethod('[', "_p_itk__simple__Image", function(x,i, j, k, drop=TRUE) { # check to see whether this is returning a single number or an image diff --git a/Wrapping/R/R.i b/Wrapping/R/R.i index 0831c0fd5..f59534ed9 100644 --- a/Wrapping/R/R.i +++ b/Wrapping/R/R.i @@ -58,6 +58,27 @@ std::vector, std::vector *, std::vector & return(invisible($result)) %} + +%extend itk::simple::Image { + // a dummy function that we'll replace + // strategy is to make swig generate a binding to something with the correct name, + // and place those names in the method list for $ operator + // The hand coded R version is provided in zA.R + void SetPixel(const std::vector< uint32_t > &idx, double v) + { + itk::simple::Unused(v); + itk::simple::Unused(idx); + } + + double GetPixel(const std::vector< uint32_t > &idx) + { + itk::simple::Unused(idx); + double e = 0; + return(e); + } + +} + %inline %{ #include "sitkConditional.h" From c7319b947e7503fc3265fef4bb678e7cab6ec785 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Thu, 12 May 2016 14:49:15 -0400 Subject: [PATCH 231/412] New image tests for Java Initial checkin of a new test for Java. The Java.ImageTests has two simple tests. The first one, BasicImageTest, creates a small image, sets a pixel and gets it back. The second test, LabelShapeStatisticsTest, creates a small image with a smaller square label in the middle. Then the LabelShapeStatisticsImageFilter is applied to it and the results are checked. It tests for the number of labels (1), the number of pixels for each label (16 for label 1) and gets the perimeter of that label. Change-Id: I583a6285319b8b4ca8ba822f8d4484bef2775b97 --- Testing/Unit/AdditionalTests.cmake | 2 + Testing/Unit/sitkImageTests.java | 181 +++++++++++++++++++++++++++++ 2 files changed, 183 insertions(+) create mode 100644 Testing/Unit/sitkImageTests.java diff --git a/Testing/Unit/AdditionalTests.cmake b/Testing/Unit/AdditionalTests.cmake index 92d8d7428..744da0982 100644 --- a/Testing/Unit/AdditionalTests.cmake +++ b/Testing/Unit/AdditionalTests.cmake @@ -47,6 +47,8 @@ sitk_add_python_test( Test.ProcessObject sitk_add_java_test( ProcessObjectTest "${SimpleITK_SOURCE_DIR}/Testing/Unit/sitkProcessObjectTest.java" ) +sitk_add_java_test( ImageTests + "${SimpleITK_SOURCE_DIR}/Testing/Unit/sitkImageTests.java" ) # # R Tests diff --git a/Testing/Unit/sitkImageTests.java b/Testing/Unit/sitkImageTests.java new file mode 100644 index 000000000..2e214f5c7 --- /dev/null +++ b/Testing/Unit/sitkImageTests.java @@ -0,0 +1,181 @@ +/*========================================================================= +* +* Copyright Insight Software Consortium +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0.txt +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*=========================================================================*/ + +import org.itk.simple.*; + +class sitkImageTests + { + + public static void main(String argv[]) + { + int ntests = 2; + int npass = 0; + int nfail = 0; + + System.out.println("[==========] Running Java.ImageTests"); + + + System.out.println("[----------]"); + System.out.println("[ RUN ] Java.BasicImageTest"); + if (BasicImageTest()) + { + System.out.println("[ OK ] Java.BasicImageTest"); + npass++; + } + else + { + System.out.println("[ FAIL ] Java.BasicImageTest"); + nfail++; + } + System.out.println("[----------]"); + + System.out.println("[----------]"); + System.out.println("[ RUN ] Java.LabelShapeStatisticsTest"); + if (LabelShapeStatisticsTest()) + { + System.out.println("[ OK ] Java.LabelShapeStatisticsTest"); + npass++; + } + else + { + System.out.println("[ FAIL ] Java.LabelShapeStatisticsTest"); + nfail++; + } + System.out.println("[----------]"); + System.out.println("[==========]"); + if (npass == ntests) + { + System.out.println("[ PASSED ]"); + } + else + { + System.out.println("[ FAILED ]"); + System.exit(1); + } + } + + public static boolean BasicImageTest() + { + int[] v = {1,1}; + VectorUInt32 idx = new VectorUInt32( v.length ); + + for (int i = 0; i < v.length; i++) + { + idx.set( i, v[i] ); + } + + int size = 10; + short val = 42; + + Image image = new Image(size, size, PixelIDValueEnum.sitkUInt8); + + image.setPixelAsUInt8(idx, val); + + try + { + if (size != image.getWidth()) + { + throw new Exception("Bad width"); + } + } + catch (Exception e) + { + return false; + } + + short newval; + + newval = image.getPixelAsUInt8(idx); + + try + { + if (newval != val) + { + throw new Exception("Bad pixel value"); + } + } + catch (Exception e) + { + return false; + } + return true; + } + + public static boolean LabelShapeStatisticsTest() + { + int size = 10; + int i,j; + short val = 1; + + + /* Make a 10x10 test image */ + Image image = new Image(size, size, PixelIDValueEnum.sitkUInt8); + VectorUInt32 idx = new VectorUInt32( 2 ); + + /* Fill in a 4x4 square in the middle of the image */ + for (j=4; j<8; j++) + { + idx.set(1, j); + for (i=4; i<8; i++) + { + idx.set(0, i); + image.setPixelAsUInt8(idx, val); + } + } + + try + { + /* Run statistics on the test image */ + LabelShapeStatisticsImageFilter filter = new LabelShapeStatisticsImageFilter(); + filter.execute(image); + + VectorInt64 labels = filter.getLabels(); + j = filter.getNumberOfLabels().intValue(); + if (j != 1) + { + throw new Exception("Wrong number of labels"); + } + int npix; + double perim; + + System.out.println("Label,\t#pix,\tperimeter"); + for (i=0; i Date: Fri, 13 May 2016 09:30:15 -0400 Subject: [PATCH 232/412] Documenting SetDisplacementField method "steals" the image --- .../include/sitkDisplacementFieldTransform.h | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Code/Common/include/sitkDisplacementFieldTransform.h b/Code/Common/include/sitkDisplacementFieldTransform.h index 253373c4a..93d2ec54b 100644 --- a/Code/Common/include/sitkDisplacementFieldTransform.h +++ b/Code/Common/include/sitkDisplacementFieldTransform.h @@ -63,8 +63,19 @@ class SITKCommon_EXPORT DisplacementFieldTransform std::string GetName() const { return std::string ("DisplacementFieldTransform"); } /** parameters */ - // set displacement methods take ownership for the image and remove it + + /** \brief Consume an image, and set the displacement field + * + * \warning The ownership of the input displacement image is + * transferred to the constructed transform object. The input image + * is modified to be a default constructed Image object. + * + * Image must be of sitkVectorFloat64 pixel type with the number of + * components equal to the image dimension. + * + */ Self &SetDisplacementField(Image &); + /** \todo The returned image should not directly modify the * internal displacement field. */ @@ -74,6 +85,7 @@ class SITKCommon_EXPORT DisplacementFieldTransform /* additional methods */ Self &SetInverseDisplacementField(Image &); + /** \todo The returned image is should not directly modify the * internal displacement field. */ From 9f3bac963200068c2a7ea7009b1403a538992765 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 13 May 2016 09:30:34 -0400 Subject: [PATCH 233/412] Fix typo in IntegerLabelPixelIDTypeList type --- Code/Common/include/sitkPixelIDTypeLists.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Common/include/sitkPixelIDTypeLists.h b/Code/Common/include/sitkPixelIDTypeLists.h index de2187bf6..2fdafd6d7 100644 --- a/Code/Common/include/sitkPixelIDTypeLists.h +++ b/Code/Common/include/sitkPixelIDTypeLists.h @@ -165,7 +165,7 @@ typedef typelist::MakeTypeList, #endif >::Type LabelPixelIDTypeList; -typedef UnsignedIntegerPixelIDTypeList IntergerLabelPixelIDTypeList; +typedef UnsignedIntegerPixelIDTypeList IntegerLabelPixelIDTypeList; /** List of all pixel ids available, but itk::LabelMap this include image of itk::Image, * itk::VectorImage From a4f976fee8b2cd3c81fa147f59ece797437dd26e Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 13 May 2016 09:35:44 -0400 Subject: [PATCH 234/412] Updating Swig git version This version include a number of improvements to R contributed by Richard Beare . --- SuperBuild/External_Swig.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_Swig.cmake b/SuperBuild/External_Swig.cmake index f1e99e01a..d31b3d6a6 100644 --- a/SuperBuild/External_Swig.cmake +++ b/SuperBuild/External_Swig.cmake @@ -20,7 +20,7 @@ if(NOT SWIG_DIR) if( USE_SWIG_FROM_GIT ) set(SWIG_GIT_REPOSITORY "${git_protocol}://github.com/swig/swig.git" CACHE STRING "URL of swig git repo") - set(SWIG_GIT_TAG "ec91de75b72ccb7ec20fffd5568dd38a966806e7" CACHE STRING "Tag in swig git repo") + set(SWIG_GIT_TAG "8890a675f7783436d0c7b61fdb318f30ffb92cde" CACHE STRING "Tag in swig git repo") mark_as_advanced(SWIG_GIT_REPO) mark_as_advanced(SWIG_GIT_TAG) endif() From c7e12e2c4d66a8d7962f4e6b9d51d73ecf0bfc0e Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 13 May 2016 12:01:16 -0400 Subject: [PATCH 235/412] BUG: Adding missing return value to SetOptimizerAsPowell Change-Id: Idec380bc377420abc6f5aa8a3ad8b65eb2cc9209 --- Code/Registration/src/sitkImageRegistrationMethod.cxx | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Registration/src/sitkImageRegistrationMethod.cxx b/Code/Registration/src/sitkImageRegistrationMethod.cxx index 85bc0d36b..2f2a77f10 100644 --- a/Code/Registration/src/sitkImageRegistrationMethod.cxx +++ b/Code/Registration/src/sitkImageRegistrationMethod.cxx @@ -347,6 +347,7 @@ ImageRegistrationMethod::SetOptimizerAsPowell(unsigned int numberOfIterations, m_OptimizerStepLength = stepLength; m_OptimizerStepTolerance = stepTolerance; m_OptimizerValueTolerance = valueTolerance; + return *this; } ImageRegistrationMethod::Self& From 886cd340bd9207f6bbb7f6c6dcc725f5fe7a1aa8 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 13 May 2016 14:10:21 -0400 Subject: [PATCH 236/412] Update Superbuild ITK version to 4.10rc1 Change-Id: I23ce833279697e31a2194097db78c0e121cb2d03 --- SuperBuild/External_ITK.cmake | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 42c59507e..7a4c8e9eb 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY "${git_protocol}://itk.org/ITK.git") # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG v4.9.1 ) +set(ITK_TAG_COMMAND GIT_TAG v4.10rc01 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) @@ -91,5 +91,5 @@ ExternalProject_Add(${proj} ExternalProject_Get_Property(ITK install_dir) -set(ITK_DIR "${install_dir}/lib/cmake/ITK-4.9" ) -set(WrapITK_DIR "${install_dir}/lib/cmake/ITK-4.9/WrapITK") +set(ITK_DIR "${install_dir}/lib/cmake/ITK-4.10" ) +set(WrapITK_DIR "${ITK_DIR}/WrapITK") From 69afe9c8432961423125c8730817758178e9d5e1 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 13 May 2016 14:13:10 -0400 Subject: [PATCH 237/412] Fix Euler3D test top support 4 fixed parameters Change-Id: I45c79807f484c900d6735c1d60d657c71e9cf2fe --- Testing/Unit/sitkTransformTests.cxx | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/Testing/Unit/sitkTransformTests.cxx b/Testing/Unit/sitkTransformTests.cxx index 6de57b9cb..7f3ae6ae0 100644 --- a/Testing/Unit/sitkTransformTests.cxx +++ b/Testing/Unit/sitkTransformTests.cxx @@ -997,16 +997,22 @@ TEST(TransformTest,Euler3DTransform) const std::vector zeros(3,0.0); const std::vector trans(3, 2.2); +#if (ITK_VERSION_MAJOR*100+ITK_VERSION_MINOR) >= 410 + const unsigned int numberOfFixedParameters = 4u; +#else + const unsigned int numberOfFixedParameters = numberOfFixedParameters; +#endif + std::auto_ptr tx(new sitk::Euler3DTransform()); std::cout << tx->ToString() << std::endl; EXPECT_EQ( tx->GetParameters().size(), 6u ); - EXPECT_EQ( tx->GetFixedParameters().size(), 3u ); + EXPECT_EQ( tx->GetFixedParameters().size(), numberOfFixedParameters ); EXPECT_EQ( tx->GetMatrix(), v9(1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0) ); tx.reset( new sitk::Euler3DTransform(center)); EXPECT_EQ( tx->GetParameters().size(), 6u ); - EXPECT_EQ( tx->GetFixedParameters().size(), 3u ); + EXPECT_EQ( tx->GetFixedParameters().size(), numberOfFixedParameters ); EXPECT_EQ( tx->GetFixedParameters()[0], 1.1 ); EXPECT_EQ( tx->GetFixedParameters()[1], 1.1 ); EXPECT_EQ( tx->GetFixedParameters()[2], 1.1 ); @@ -1015,7 +1021,7 @@ TEST(TransformTest,Euler3DTransform) tx.reset( new sitk::Euler3DTransform(center, 1.0, 2.0, 3.0)); EXPECT_EQ( tx->GetParameters().size(), 6u ); - EXPECT_EQ( tx->GetFixedParameters().size(), 3u ); + EXPECT_EQ( tx->GetFixedParameters().size(), numberOfFixedParameters ); EXPECT_EQ( tx->GetFixedParameters()[0], 1.1 ); EXPECT_EQ( tx->GetFixedParameters()[1], 1.1 ); EXPECT_EQ( tx->GetFixedParameters()[2], 1.1 ); @@ -1041,7 +1047,11 @@ TEST(TransformTest,Euler3DTransform) EXPECT_EQ( tx1.GetCenter(), zeros ); // copy on write - tx1.SetFixedParameters(center); + std::vector fixed = center; +#if (ITK_VERSION_MAJOR*100+ITK_VERSION_MINOR) >= 410 + fixed.push_back(0.0); +#endif + tx1.SetFixedParameters(fixed);// EXPECT_EQ( tx1.GetFixedParameters()[0], 1.1 ); EXPECT_EQ( tx1.GetFixedParameters()[1], 1.1 ); EXPECT_EQ( tx1.GetFixedParameters()[2], 1.1 ); @@ -1076,7 +1086,7 @@ TEST(TransformTest,Euler3DTransform) tx.reset(); EXPECT_EQ( tx3.GetParameters().size(), 6u ); - EXPECT_EQ( tx3.GetFixedParameters().size(), 3u ); + EXPECT_EQ( tx3.GetFixedParameters().size(), numberOfFixedParameters ); EXPECT_EQ( tx3.GetFixedParameters()[0], 1.1 ); EXPECT_EQ( tx3.GetFixedParameters()[1], 1.1 ); EXPECT_EQ( tx3.GetFixedParameters()[2], 1.1 ); From 7373e671f9accf6f87fe19cd8bd0403452ae8314 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 13 May 2016 14:16:01 -0400 Subject: [PATCH 238/412] Use exception in sitkSTLToITKDirection macro Remove the local check and exception in the PimpleImage class in favor of the one in the macro. Change-Id: Id79041f7617c3ca8cf0d7f5c4d223e90df3593a3 --- Code/Common/src/sitkPimpleImageBase.hxx | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Code/Common/src/sitkPimpleImageBase.hxx b/Code/Common/src/sitkPimpleImageBase.hxx index 636f321cb..bb86abec7 100644 --- a/Code/Common/src/sitkPimpleImageBase.hxx +++ b/Code/Common/src/sitkPimpleImageBase.hxx @@ -179,11 +179,6 @@ namespace itk // Set Direction virtual void SetDirection( const std::vector< double > & in ) { - if (in.size() != ImageType::ImageDimension*ImageType::ImageDimension) - { - sitkExceptionMacro("direction size mismatch"); - } - this->m_Image->SetDirection( sitkSTLToITKDirection( in ) ); } From 97269f524883e9779175c7b6277301e0401a6853 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Fri, 13 May 2016 16:00:04 -0400 Subject: [PATCH 239/412] Added BigIntegerFix class The BigIntegerFix class is needed because on some systems for Java Swig converts uint64_t to long, and on others it converts to BigInteger. Change-Id: I379e6920d381e6eb957cbce431044db80eb04b4d --- Testing/Unit/sitkImageTests.java | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/Testing/Unit/sitkImageTests.java b/Testing/Unit/sitkImageTests.java index 2e214f5c7..7795ad753 100644 --- a/Testing/Unit/sitkImageTests.java +++ b/Testing/Unit/sitkImageTests.java @@ -16,8 +16,24 @@ * *=========================================================================*/ +import java.math.BigInteger; import org.itk.simple.*; +/* This class is needed because on some systems uint64_t gets converted to long + * while on others it becomes a BigInteger. */ +class BigIntegerFix + { + public static long Convert( long value ) + { + return value; + } + + public static long Convert( BigInteger value ) + { + return value.longValue(); + } + } + class sitkImageTests { @@ -119,7 +135,8 @@ public static boolean BasicImageTest() public static boolean LabelShapeStatisticsTest() { int size = 10; - int i,j; + int i; + long j; short val = 1; @@ -145,20 +162,20 @@ public static boolean LabelShapeStatisticsTest() filter.execute(image); VectorInt64 labels = filter.getLabels(); - j = filter.getNumberOfLabels().intValue(); + j = BigIntegerFix.Convert( filter.getNumberOfLabels() ); if (j != 1) { throw new Exception("Wrong number of labels"); } - int npix; + long npix; double perim; System.out.println("Label,\t#pix,\tperimeter"); for (i=0; i Date: Tue, 17 May 2016 10:41:09 -0400 Subject: [PATCH 240/412] BUG: Adjust itk.org ExternalData URL. The request to https://www.itk.org gives a 301 redirect to https://itk.org. Use the direct address, which helps some clients. Change-Id: Ibec8f8cf95415fc2467150bb115efde5e96994ca --- CMake/sitkExternalData.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMake/sitkExternalData.cmake b/CMake/sitkExternalData.cmake index 67075bb82..a438091ef 100644 --- a/CMake/sitkExternalData.cmake +++ b/CMake/sitkExternalData.cmake @@ -40,7 +40,7 @@ if(NOT SITK_FORBID_DOWNLOADS) "https://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=%(hash)&algorithm=%(algo)" # Data published by developers using git-gerrit-push. - "https://www.itk.org/files/ExternalData/%(algo)/%(hash)" + "https://itk.org/files/ExternalData/%(algo)/%(hash)" ) endif() # Tell ExternalData commands not to transform raw files to content links. From f230f33e2883fa2835a5b01c23e0815005efdd33 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 18 May 2016 14:38:01 -0400 Subject: [PATCH 241/412] Fix number of expected Euler3D fixed parameters Change-Id: I92e5d1bbc2c58d0a41609caede4019a94b3a62f2 --- Testing/Unit/sitkTransformTests.cxx | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Testing/Unit/sitkTransformTests.cxx b/Testing/Unit/sitkTransformTests.cxx index 7f3ae6ae0..72ea45a54 100644 --- a/Testing/Unit/sitkTransformTests.cxx +++ b/Testing/Unit/sitkTransformTests.cxx @@ -146,6 +146,13 @@ TEST(TransformTest, Copy) { } TEST(TransformTest, SetGetParameters) { +#if (ITK_VERSION_MAJOR*100+ITK_VERSION_MINOR) >= 410 + const unsigned int euler3DNumberOfFixedParameters = 4u; +#else + const unsigned int euler3DNumberOfFixedParameters = 3u; +#endif + + sitk::Transform tx; EXPECT_TRUE( tx.GetParameters().empty() ); @@ -173,7 +180,7 @@ TEST(TransformTest, SetGetParameters) { tx = sitk::Transform( 3, sitk::sitkEuler ); EXPECT_EQ( tx.GetParameters().size(), 6u ); - EXPECT_EQ( tx.GetFixedParameters().size(), 3u ); + EXPECT_EQ( tx.GetFixedParameters().size(), euler3DNumberOfFixedParameters ); EXPECT_TRUE(tx.IsLinear()); tx = sitk::Transform( 2, sitk::sitkSimilarity ); From 7fe0fdc39b98cbc1f7aa441ce5675bd1febe04e2 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 18 May 2016 14:46:25 -0400 Subject: [PATCH 242/412] Update ITK Superbuild version toward ITK v4.10 Change-Id: Id2f4dbffa01eeb1c8f8162d1a61ffe13a2f06558 --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 7a4c8e9eb..b93fa5413 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY "${git_protocol}://itk.org/ITK.git") # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG v4.10rc01 ) +set(ITK_TAG_COMMAND GIT_TAG 417d6a36d01aa3b835855349cc481a9b3dca8506 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From fc25cb830b6eae5193bb44a56e7c1c4260bbef1a Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 18 May 2016 14:49:27 -0400 Subject: [PATCH 243/412] Fix CMake CMP0042 in TargetLinkLibrariesWithDynamicLookup Change-Id: Ic5e7f98b9bfe546553cfbcfe6e923a50eb192a91 --- CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake | 1 + 1 file changed, 1 insertion(+) diff --git a/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake b/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake index 10e0a5675..4d085e265 100644 --- a/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake +++ b/CMake/sitkTargetLinkLibrariesWithDynamicLookup.cmake @@ -60,6 +60,7 @@ int foo(void) {return bar()+1;} undefined CMAKE_FLAGS "-DCMAKE_SHARED_LINKER_FLAGS='${CMAKE_SHARED_LINKER_FLAGS}'" + "-DCMAKE_MACOSX_RPATH=OFF" OUTPUT_VARIABLE output) set(${cache_var} ${${VARIABLE}} CACHE INTERNAL "hashed flags with try_compile results") From 4b1f8904022973942ad0b15524153e091862d6cf Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 18 May 2016 15:46:23 -0400 Subject: [PATCH 244/412] Suppress libraries as being required for wrapped languages The python library is not needed on systems where dynamic linking can occur. Don't require it any more. Change-Id: I40426536d91e3a2c1ef307641abbbc025aba098c --- CMake/sitkLanguageOptions.cmake | 56 ++++++++++++++++----------------- SuperBuild/SuperBuild.cmake | 4 ++- 2 files changed, 31 insertions(+), 29 deletions(-) diff --git a/CMake/sitkLanguageOptions.cmake b/CMake/sitkLanguageOptions.cmake index 3df87e77f..d26db8811 100644 --- a/CMake/sitkLanguageOptions.cmake +++ b/CMake/sitkLanguageOptions.cmake @@ -8,15 +8,29 @@ # Additionally it give the option to wrap LUA. # +include(sitkTargetLinkLibrariesWithDynamicLookup) + +# +# Macro to set "_QUIET" and "_QUIET_LIBRARY" based on the first +# argument being defined and true, to either REQUIRED or QUIET. +# +macro(set_QUIET var) + if ( DEFINED ${var} AND ${var} ) + set( _QUIET "REQUIRED" ) + else() + set( _QUIET "QUIET" ) + endif() + if ( SITK_UNDEFINED_SYMBOLS_ALLOWED ) + set( _QUIET_LIBRARY "QUIET" ) + else() + set( _QUIET_LIBRARY ${_QUIET} ) + endif() +endmacro() # # Setup the option for each language # -if (DEFINED WRAP_LUA AND WRAP_LUA) - set(_QUIET "REQUIRED") -else() - set(_QUIET "QUIET") -endif() +set_QUIET( WRAP_LUA ) if (CMAKE_VERSION VERSION_LESS "3") find_package ( Lua51 ${_QUIET} ) if ( NOT LUA_FOUND ) @@ -48,15 +62,10 @@ endif() # If you're not using python or it's the first time, be quiet -if (DEFINED WRAP_PYTHON AND WRAP_PYTHON) - set(_QUIET "REQUIRED") -else() - set(_QUIET "QUIET") -endif() +set_QUIET( WRAP_PYTHON ) find_package ( PythonInterp ${_QUIET}) - -find_package ( PythonLibs ${PYTHON_VERSION_STRING} EXACT ${_QUIET} ) +find_package ( PythonLibs ${PYTHON_VERSION_STRING} EXACT ${_QUIET_LIBRARY} ) if (PYTHON_VERSION_STRING VERSION_LESS 2.6) message( WARNING "Python version less that 2.6: \"${PYTHON_VERSION_STRING}\"." ) @@ -89,12 +98,8 @@ if ( WRAP_PYTHON ) endif () -if (DEFINED WRAP_JAVA AND WRAP_JAVA) - set(_QUIET "REQUIRED") -else() - set(_QUIET "QUIET") -endif() +set_QUIET( WRAP_JAVA ) find_package ( Java COMPONENTS Development Runtime ${_QUIET} ) find_package ( JNI ${_QUIET} ) if ( ${JAVA_FOUND} AND ${JNI_FOUND} ) @@ -131,13 +136,10 @@ if ( WRAP_JAVA ) endif() -if (DEFINED WRAP_TCL AND WRAP_TCL) - set(_QUIET "REQUIRED") -else() - set(_QUIET "QUIET") -endif() +set_QUIET(WRAP_TCL) find_package ( TCL ${_QUIET} ) + if ( ${TCL_FOUND} ) set ( WRAP_TCL_DEFAULT ON ) else ( ${TCL_FOUND} ) @@ -158,7 +160,9 @@ if ( WRAP_TCL ) endif() -find_package ( Ruby QUIET ) +set_QUIET( WRAP_RUBY ) + +find_package ( Ruby ${_QUIET} ) if ( ${RUBY_FOUND} ) set ( WRAP_RUBY_DEFAULT ON ) else ( ${RUBY_FOUND} ) @@ -203,11 +207,7 @@ if ( WRAP_CSHARP ) endif() -if (DEFINED WRAP_R AND WRAP_R) - set(_QUIET "REQUIRED") -else() - set(_QUIET "QUIET") -endif() +set_QUIET( WRAP_R ) find_package(R ${_QUIET}) if ( ${R_FOUND} AND NOT WIN32 ) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index d1a45e3b8..02be02d43 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -346,7 +346,9 @@ foreach (_varName ${_varNames}) AND NOT _varName MATCHES "^SimpleITK_VARS" AND - NOT _varName MATCHES "^SimpleITK_REQUIRED_") + NOT _varName MATCHES "^SimpleITK_REQUIRED_" + AND + NOT _varName MATCHES "^SITK_UNDEFINED_SYMBOLS_ALLOWED") message( STATUS "Passing variable \"${_varName}=${${_varName}}\" to SimpleITK external project.") list(APPEND SimpleITK_VARS ${_varName}) endif() From 72ac2ee9a11143b2a5be345018d4aed5059f75ba Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 18 May 2016 15:47:27 -0400 Subject: [PATCH 245/412] CMake recently add LUA_MATH_LIBRARY as an additional variable Change-Id: I7c71ad65dec900ad314525dca1b8a259bce97590 --- CMake/sitkLanguageOptions.cmake | 1 + 1 file changed, 1 insertion(+) diff --git a/CMake/sitkLanguageOptions.cmake b/CMake/sitkLanguageOptions.cmake index d26db8811..95c075430 100644 --- a/CMake/sitkLanguageOptions.cmake +++ b/CMake/sitkLanguageOptions.cmake @@ -55,6 +55,7 @@ if ( WRAP_LUA ) LUA_LIBRARIES LUA_INCLUDE_DIR LUA_VERSION_STRING + LUA_MATH_LIBRARY LUA_ADDITIONAL_LIBRARIES ) endif() From 66f568dd4818c82f6040fc5013bb34452955b43d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 19 May 2016 15:20:44 -0400 Subject: [PATCH 246/412] Require python 2.6 for running JSON validation script Change-Id: Id2dadb36d79a77f369923decd467a4b384cfac47 --- CMake/sitkGenerateFilterSource.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMake/sitkGenerateFilterSource.cmake b/CMake/sitkGenerateFilterSource.cmake index 47ebbbf61..c7883ed20 100644 --- a/CMake/sitkGenerateFilterSource.cmake +++ b/CMake/sitkGenerateFilterSource.cmake @@ -112,7 +112,7 @@ macro( expand_template FILENAME input_dir output_dir library_name ) set ( IMAGE_FILTER_LIST ${IMAGE_FILTER_LIST} ${FILENAME} CACHE INTERNAL "" ) # validate json files if python is available - if ( PYTHON_EXECUTABLE ) + if ( PYTHON_EXECUTABLE AND NOT PYTHON_VERSION_STRING VERSION_LESS 2.6 ) set ( JSON_VALIDATE_COMMAND COMMAND "${PYTHON_EXECUTABLE}" "${SimpleITK_SOURCE_DIR}/Utilities/JSONValidate.py" "${input_json_file}" ) endif () From 69ef3f1e036f0c9cba24179b210dd45118773681 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 19 May 2016 15:34:25 -0400 Subject: [PATCH 247/412] Updating Superbuild ITK version to 4.10 rc 2 Change-Id: I60e1e76bbaa3b46391c8e5ed84007705a36c5fbc --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index b93fa5413..44a367058 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY "${git_protocol}://itk.org/ITK.git") # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG 417d6a36d01aa3b835855349cc481a9b3dca8506 ) +set(ITK_TAG_COMMAND GIT_TAG v4.10rc02 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 9838465f11504ae48d6dee97d25fd659ce0a5cfe Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 20 May 2016 10:55:01 -0400 Subject: [PATCH 248/412] Do not require Python libs if weak linking is going to be used Change-Id: Ieb92d1c28ca6826ec3fd1273ee51b8eb6d1f60f9 --- Wrapping/Python/CMakeLists.txt | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index d66496019..a9fced428 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -14,8 +14,12 @@ endif() include(../../CMake/sitkProjectLanguageCommon.cmake) - -find_package ( PythonLibs REQUIRED ) +if ( SITK_UNDEFINED_SYMBOLS_ALLOWED ) + set( _QUIET_LIBRARY "QUIET" ) +else() + set( _QUIET_LIBRARY "REQUIRED" ) +endif() +find_package ( PythonLibs ${_QUIET_LIBRARY} ) find_package ( PythonInterp REQUIRED ) include_directories ( ${PYTHON_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ) From 98cf0fb28a656d9c8a8eb7d63906ed15c7ad5b9b Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 20 May 2016 10:57:00 -0400 Subject: [PATCH 249/412] Use current binary directory for Python packaging working directory This addresses issues when building the Wrapped directory as a separate project. Change-Id: I0f116cce817c7cd121d21e72f74604d39c3885f4 --- Wrapping/Python/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index d66496019..4b5dc27b0 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -52,7 +52,7 @@ sitk_strip_target( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ) # Installation -set( SIMPLEITK_PYTHON_PACKAGE_DIR "${SimpleITK_BINARY_DIR}/Wrapping/Python" ) +set( SIMPLEITK_PYTHON_PACKAGE_DIR "${CMAKE_CURRENT_BINARY_DIR}" ) file( TO_NATIVE_PATH "${SIMPLEITK_PYTHON_PACKAGE_DIR}" SIMPLEITK_PYTHON_PACKAGE_DIR ) get_target_property( SWIG_MODULE_SimpleITKPython_TARGET_LOCATION ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} OUTPUT_NAME ) add_custom_command( From 6f3482537bc4c397e6d970874fea98c81c379d56 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Fri, 20 May 2016 13:26:08 -0400 Subject: [PATCH 250/412] Fix for CMake's semicolon issue on Windows The sitk_add_java_test function needs to pass a CLASSPATH for Java down to sitk_add_tests. CLASSPATH contains two directories that are separated by a semicolon on Windows. However CMake uses semicolons to separated elements in a string into a list. And in CMake function arguements are passed as a single string, separated by semicolons. So to get a CLASSPATH string such as "path1;path2" to not get separated into list elements by CMake, we need to use backslashes to escape the semicolon. And in this case, we need our CLASSPATH to make it down through 4 levels of function calls. So we have to use SEVEN backslashes: "path1\\\\\\\;path2". Change-Id: Idb1c8f94db04791986eba1eea94ecfc924edaa37 --- CMake/sitkAddTest.cmake | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index 57fb02e67..b82e61c1a 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -165,8 +165,9 @@ function(sitk_add_java_test name java_file) if(WIN32) set( _JAVA_LIBRARY_PATH "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/$" ) # Note: on windows this is a semi-colon separated list - set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE};${CMAKE_CURRENT_BINARY_DIR}" ) - else(WIN32) + # Note 2: there are 7 backslashes before the semi-colon so that it + # gets properly passed through 4 levels of function calls. + set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}\\\\\\\;${CMAKE_CURRENT_BINARY_DIR}" ) set( _JAVA_LIBRARY_PATH "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}" ) set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}:${CMAKE_CURRENT_BINARY_DIR}" ) endif(WIN32) From 09cbfbd498e820c5366793dce35c8aefb7e2e860 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Fri, 20 May 2016 15:05:08 -0400 Subject: [PATCH 251/412] Reverting deleted line I accidentally deleted an ELSE line from an IF-ELSE-THEN statement. This patch restores the ELSE line. Change-Id: Ic2b9a66fcfd191545f1f0a71ae8fc7e716ef8c60 --- CMake/sitkAddTest.cmake | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index b82e61c1a..0f3d9d562 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -168,6 +168,8 @@ function(sitk_add_java_test name java_file) # Note 2: there are 7 backslashes before the semi-colon so that it # gets properly passed through 4 levels of function calls. set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}\\\\\\\;${CMAKE_CURRENT_BINARY_DIR}" ) + + else(WIN32) set( _JAVA_LIBRARY_PATH "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}" ) set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}:${CMAKE_CURRENT_BINARY_DIR}" ) endif(WIN32) From 4e0332c9df9232e8f0e638e1b41739a915b55bc5 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 23 May 2016 14:41:11 -0400 Subject: [PATCH 252/412] Update ITK Superbuild version along RC This update contains several warnings fixes for compilers. Change-Id: I2162450c3ba8eb405b6f3f4b17c141412fcd84a6 --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 44a367058..770dfe785 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY "${git_protocol}://itk.org/ITK.git") # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG v4.10rc02 ) +set(ITK_TAG_COMMAND GIT_TAG c29756e1dbb0afbb991ad2f399658d754035d225 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 5e19ecdbcd42e20e039f0dab416964ac70aabb39 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 24 May 2016 14:49:40 -0400 Subject: [PATCH 253/412] Adding SimpleITK version components to Config file Change-Id: I57120d14598621f8f52abd1ea9a3556a4be1f4b6 --- SimpleITKConfig.cmake.in | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/SimpleITKConfig.cmake.in b/SimpleITKConfig.cmake.in index f10c2a0ab..5f2811d25 100644 --- a/SimpleITKConfig.cmake.in +++ b/SimpleITKConfig.cmake.in @@ -16,6 +16,31 @@ set(SimpleITK_REQUIRED_C_FLAGS "@SimpleITK_REQUIRED_C_FLAGS@") set(SimpleITK_REQUIRED_CXX_FLAGS "@SimpleITK_REQUIRED_CXX_FLAGS@") set(SimpleITK_REQUIRED_LINK_FLAGS "@SimpleITK_REQUIRED_LINK_FLAGS@") +# The SimpleITK version number +set(SimpleITK_VERSION_MAJOR "@SimpleITK_VERSION_MAJOR@") +set(SimpleITK_VERSION_MINOR "@SimpleITK_VERSION_MINOR@") +if(NOT "@SimpleITK_VERSION_PATCH@" STREQUAL "") + set(SimpleITK_VERSION_PATCH "@SimpleITK_VERSION_PATCH@") +endif() +if(NOT "@SimpleITK_VERSION_TWEAK@" STREQUAL "") + set(SimpleITK_VERSION_TWEAK "@SimpleITK_VERSION_TWEAK@") +endif() +if(NOT "@SimpleITK_VERSION_RC@" STREQUAL "") + set(SimpleITK_VERSION_RC "@SimpleITK_VERSION_RC@") +endif() +if(NOT "@SimpleITK_VERSION_POST@" STREQUAL "") + set(SimpleITK_VERSION_POST "@SimpleITK_VERSION_POST@") +endif() +if(NOT "@SimpleITK_VERSION_DEV@" STREQUAL "") + set(SimpleITK_VERSION_DEV "@SimpleITK_VERSION_DEV@") +endif() +if(NOT "SimpleITK_VERSION_HASH@" STREQUAL "") + set(SimpleITK_VERSION_HASH "@SimpleITK_VERSION_HASH@") +endif() + + + + # The SimpleITK include file directories. set(SimpleITK_INCLUDE_DIRS "@SimpleITKConfig_INCLUDE_DIRS@") From 995523572b959f409fe10518c1e884928c416e4a Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 24 May 2016 14:50:06 -0400 Subject: [PATCH 254/412] Adding correct version variables to CPack Change-Id: I52a55997a4012696e407289227121eb5e612880a --- CMakeLists.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 67d4029a3..22da6db52 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -498,9 +498,9 @@ install(FILES ${SimpleITK_DOC_FILES} DESTINATION "${SimpleITK_INSTALL_DOC_DIR}" # CPack set(CPACK_SOURCE_IGNORE_FILES "${ITK_MODULES_DISABLED_CPACK};/\\\\.git") -set(CPACK_PACKAGE_VERSION_MAJOR "${SimpleITK_Major}") -set(CPACK_PACKAGE_VERSION_MINOR "${SimpleITK_Minor}") -set(CPACK_PACKAGE_VERSION_PATCH "${SimpleITK_Patch}") +set(CPACK_PACKAGE_VERSION_MAJOR "${SimpleITK_VERSION_MAJOR}") +set(CPACK_PACKAGE_VERSION_MINOR "${SimpleITK_VERSION_MINOR}") +set(CPACK_PACKAGE_VERSION_PATCH "${SimpleITK_VERSION_PATCH}") include( CPack ) From bb69d306b310ecd4cdf82adf21db08c4b0f9b060 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 24 May 2016 14:50:49 -0400 Subject: [PATCH 255/412] Fix setup.py using hash with empty string Change-Id: I2138ad9d03fd2d6f512f8f7e2c5952eaf03f3e7b --- Wrapping/Python/Packaging/setup.py.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Wrapping/Python/Packaging/setup.py.in b/Wrapping/Python/Packaging/setup.py.in index 45a80e950..2fc983854 100644 --- a/Wrapping/Python/Packaging/setup.py.in +++ b/Wrapping/Python/Packaging/setup.py.in @@ -37,7 +37,7 @@ def get_pep386version(): elif sitkDEV: version += ".dev"+sitkDEV - if sitkHASH and not "@SimpleITK_BUILD_DISTRIBUTE@": + if sitkHASH and not "@SimpleITK_BUILD_DISTRIBUTE@" in ['1', 'ON']: version += "-g"+sitkHASH return version From 087f6f50126d972145a4f9f74f4433f22f7ca592 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 25 May 2016 16:14:54 -0400 Subject: [PATCH 256/412] Updating ITK Superbuild version to 4.10 Change-Id: I9733fe674df169274579d9c3c5bb32a8ab029b9f --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 770dfe785..c3d9a71e4 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -35,7 +35,7 @@ set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY "${git_protocol}://itk.org/ITK.git") # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG c29756e1dbb0afbb991ad2f399658d754035d225 ) +set(ITK_TAG_COMMAND GIT_TAG v4.10.0 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 77fa5246f70be7ffb2a2d353ab7323df083dfb28 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Thu, 26 May 2016 15:32:22 -0400 Subject: [PATCH 257/412] Check for cmake version To get the semicolon to pass through the layers of function calls, we use slashes. The number of slashes require depends on the cmake version. For cmake 3.5, 7 slashes are needed. For old version, 11 seem to be the number required. Change-Id: I2a17e9421e105340825f203dd63ed76dfe11cc74 --- CMake/sitkAddTest.cmake | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index 0f3d9d562..0464c624c 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -165,9 +165,14 @@ function(sitk_add_java_test name java_file) if(WIN32) set( _JAVA_LIBRARY_PATH "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/$" ) # Note: on windows this is a semi-colon separated list - # Note 2: there are 7 backslashes before the semi-colon so that it - # gets properly passed through 4 levels of function calls. - set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}\\\\\\\;${CMAKE_CURRENT_BINARY_DIR}" ) + # Note 2: there are 7 or 11 backslashes (depending on the cmake version) + # before the semi-colon so that it gets properly passed through + # 4 levels of function calls. + if (${CMAKE_VERSION} VERSION_LESS "3.5") + set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}\\\\\\\\\\\;${CMAKE_CURRENT_BINARY_DIR}" ) + else() + set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}\\\\\\\;${CMAKE_CURRENT_BINARY_DIR}" ) + endif() else(WIN32) set( _JAVA_LIBRARY_PATH "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}" ) From 9c6c83f65077e10cd5a674ba71f478b28bdafc12 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 27 May 2016 15:11:55 -0400 Subject: [PATCH 258/412] Reuse ImageIO from reading initial information Change access level of GetImageIOBase method to protected. Overloaded methods to get info from filename to get it directly from the imageio. Refactored the series reader and the file reader to re-use the initial ImageIO created. This may improve performance. Change-Id: Idb3be08fa43acb3d219edfcf36231177159d0676 --- Code/IO/include/sitkImageFileReader.h | 4 ++-- Code/IO/include/sitkImageReaderBase.h | 7 +++++- Code/IO/include/sitkImageSeriesReader.h | 4 ++-- Code/IO/src/sitkImageFileReader.cxx | 13 ++++++----- Code/IO/src/sitkImageReaderBase.cxx | 29 ++++++++++++++++++++----- Code/IO/src/sitkImageSeriesReader.cxx | 14 +++++++----- 6 files changed, 50 insertions(+), 21 deletions(-) diff --git a/Code/IO/include/sitkImageFileReader.h b/Code/IO/include/sitkImageFileReader.h index 0b56b0498..07a1ad9d9 100644 --- a/Code/IO/include/sitkImageFileReader.h +++ b/Code/IO/include/sitkImageFileReader.h @@ -56,12 +56,12 @@ namespace itk { protected: - template Image ExecuteInternal ( void ); + template Image ExecuteInternal ( itk::ImageIOBase * ); private: // function pointer type - typedef Image (Self::*MemberFunctionType)( void ); + typedef Image (Self::*MemberFunctionType)( itk::ImageIOBase * ); // friend to get access to executeInternal member friend struct detail::MemberFunctionAddressor; diff --git a/Code/IO/include/sitkImageReaderBase.h b/Code/IO/include/sitkImageReaderBase.h index a58971082..8420ec452 100644 --- a/Code/IO/include/sitkImageReaderBase.h +++ b/Code/IO/include/sitkImageReaderBase.h @@ -63,12 +63,18 @@ class SmartPointer; protected: + itk::SmartPointer GetImageIOBase(const std::string &fileName); + void GetPixelIDFromImageIO( const std::string &fileName, PixelIDValueType &outPixelType, unsigned int & outDimensions); + void GetPixelIDFromImageIO( itk::ImageIOBase* iobase, + PixelIDValueType &outPixelType, + unsigned int & outDimensions); unsigned int GetDimensionFromImageIO( const std::string &fileName, unsigned int i); + unsigned int GetDimensionFromImageIO( itk::ImageIOBase* iobase, unsigned int i); private: @@ -78,7 +84,6 @@ class SmartPointer; PixelIDValueType ExecuteInternalReadComplex( int componentType ); - itk::SmartPointer GetImageIOBase(const std::string &fileName); PixelIDValueEnum m_OutputPixelType; diff --git a/Code/IO/include/sitkImageSeriesReader.h b/Code/IO/include/sitkImageSeriesReader.h index 077d8945a..b98d28ecd 100644 --- a/Code/IO/include/sitkImageSeriesReader.h +++ b/Code/IO/include/sitkImageSeriesReader.h @@ -109,12 +109,12 @@ namespace itk { protected: - template Image ExecuteInternal ( void ); + template Image ExecuteInternal ( itk::ImageIOBase * ); private: // function pointer type - typedef Image (Self::*MemberFunctionType)( void ); + typedef Image (Self::*MemberFunctionType)( itk::ImageIOBase * ); // friend to get access to executeInternal member friend struct detail::MemberFunctionAddressor; diff --git a/Code/IO/src/sitkImageFileReader.cxx b/Code/IO/src/sitkImageFileReader.cxx index c276ede0d..a6994c9c8 100644 --- a/Code/IO/src/sitkImageFileReader.cxx +++ b/Code/IO/src/sitkImageFileReader.cxx @@ -71,14 +71,16 @@ namespace itk { PixelIDValueType type = this->GetOutputPixelType(); unsigned int dimension = 0; + + itk::ImageIOBase::Pointer imageio = this->GetImageIOBase( this->m_FileName ); if (type == sitkUnknown) { - this->GetPixelIDFromImageIO( this->m_FileName, type, dimension ); + this->GetPixelIDFromImageIO( imageio, type, dimension ); } else { PixelIDValueType unused; - this->GetPixelIDFromImageIO( this->m_FileName, unused, dimension ); + this->GetPixelIDFromImageIO( imageio, unused, dimension ); } #ifdef SITK_4D_IMAGES @@ -98,12 +100,12 @@ namespace itk { << "Refusing to load! " << std::endl ); } - return this->m_MemberFactory->GetMemberFunction( type, dimension )(); + return this->m_MemberFactory->GetMemberFunction( type, dimension )(imageio.GetPointer()); } template Image - ImageFileReader::ExecuteInternal( void ) + ImageFileReader::ExecuteInternal( itk::ImageIOBase *imageio ) { typedef TImageType ImageType; @@ -112,8 +114,9 @@ namespace itk { // if the InstantiatedToken is correctly implemented this should // not occour assert( ImageTypeToPixelIDValue::Result != (int)sitkUnknown ); - + assert( imageio != SITK_NULLPTR ); typename Reader::Pointer reader = Reader::New(); + reader->SetImageIO( imageio ); reader->SetFileName( this->m_FileName.c_str() ); this->PreUpdate( reader.GetPointer() ); diff --git a/Code/IO/src/sitkImageReaderBase.cxx b/Code/IO/src/sitkImageReaderBase.cxx index 92f687e75..3a10c524c 100644 --- a/Code/IO/src/sitkImageReaderBase.cxx +++ b/Code/IO/src/sitkImageReaderBase.cxx @@ -64,7 +64,7 @@ ::GetImageIOBase(const std::string &fileName) itk::ImageIOFactory::CreateImageIO( fileName.c_str(), itk::ImageIOFactory::ReadMode); - if ( iobase.IsNull() ) + if ( iobase.IsNull() ) { if ( !itksys::SystemTools::FileExists( fileName.c_str() ) ) { @@ -107,10 +107,19 @@ ::GetPixelIDFromImageIO( const std::string &fileName, PixelIDValueType &outPixelType, unsigned int & outDimensions ) { - itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(fileName); + this->GetPixelIDFromImageIO(iobase, outPixelType, outDimensions); +} + +void +ImageReaderBase +::GetPixelIDFromImageIO( ImageIOBase *iobase, + PixelIDValueType &outPixelType, + unsigned int & outDimensions ) +{ + // get output information about input image unsigned int dimension = iobase->GetNumberOfDimensions(); itk::ImageIOBase::IOComponentType componentType = iobase->GetComponentType(); @@ -148,19 +157,27 @@ ::GetPixelIDFromImageIO( const std::string &fileName, sitkExceptionMacro( "Unknown PixelType: " << (int) componentType ); } - sitkExceptionMacro( "Unable to load image \"" << fileName << "\"" ); + sitkExceptionMacro( "Unable to load image." ); } unsigned int ImageReaderBase -::GetDimensionFromImageIO( const std::string &fileName, unsigned int i) +::GetDimensionFromImageIO( itk::ImageIOBase* iobase, unsigned int i) { - itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(fileName); - return iobase->GetDimensions(i); } +unsigned int +ImageReaderBase +::GetDimensionFromImageIO(const std::string &filename, unsigned int i) +{ + itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(filename); + + return this->GetDimensionFromImageIO(iobase.GetPointer(), i); +} + + PixelIDValueType ImageReaderBase ::ExecuteInternalReadScalar( int componentType ) diff --git a/Code/IO/src/sitkImageSeriesReader.cxx b/Code/IO/src/sitkImageSeriesReader.cxx index 64977a930..74950df0e 100644 --- a/Code/IO/src/sitkImageSeriesReader.cxx +++ b/Code/IO/src/sitkImageSeriesReader.cxx @@ -116,14 +116,16 @@ namespace itk { PixelIDValueType type = this->GetOutputPixelType(); unsigned int dimension = 0; + + itk::ImageIOBase::Pointer imageio = this->GetImageIOBase( this->m_FileNames.front() ); if (type == sitkUnknown) { - this->GetPixelIDFromImageIO( this->m_FileNames.front(), type, dimension ); + this->GetPixelIDFromImageIO( imageio, type, dimension ); } else { PixelIDValueType unused; - this->GetPixelIDFromImageIO( this->m_FileNames.front(), unused, dimension ); + this->GetPixelIDFromImageIO( imageio, unused, dimension ); } // increment for series @@ -131,7 +133,7 @@ namespace itk { if (dimension == 4) { - unsigned int size = this->GetDimensionFromImageIO( this->m_FileNames.front(), 2); + unsigned int size = this->GetDimensionFromImageIO( imageio, 2); if (size == 1) { --dimension; @@ -151,11 +153,11 @@ namespace itk { << "Refusing to load! " << std::endl ); } - return this->m_MemberFactory->GetMemberFunction( type, dimension )(); + return this->m_MemberFactory->GetMemberFunction( type, dimension )(imageio); } template Image - ImageSeriesReader::ExecuteInternal( void ) + ImageSeriesReader::ExecuteInternal( itk::ImageIOBase* imageio ) { typedef TImageType ImageType; @@ -164,7 +166,9 @@ namespace itk { // if the IsInstantiated is correctly implemented this should // not occour assert( ImageTypeToPixelIDValue::Result != (int)sitkUnknown ); + assert( imageio != SITK_NULLPTR ); typename Reader::Pointer reader = Reader::New(); + reader->SetImageIO( imageio ); reader->SetFileNames( this->m_FileNames ); this->PreUpdate( reader.GetPointer() ); From c82ff883adcb5b14d205876a19a1cc7ec9592d9d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 24 May 2016 09:26:42 -0400 Subject: [PATCH 259/412] Adding option to read DICOM private tags Change-Id: If91fd6d0209374496e023d5c15b1d0f75b54caf0 --- Code/IO/include/sitkImageReaderBase.h | 7 ++++ Code/IO/src/sitkImageReaderBase.cxx | 48 +++++++++++++++++++++++++-- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/Code/IO/include/sitkImageReaderBase.h b/Code/IO/include/sitkImageReaderBase.h index 8420ec452..3a67988d6 100644 --- a/Code/IO/include/sitkImageReaderBase.h +++ b/Code/IO/include/sitkImageReaderBase.h @@ -61,6 +61,12 @@ class SmartPointer; virtual std::string ToString() const; + + virtual Self& SetLoadPrivateTags(bool loadPrivateTags); + virtual bool GetLoadPrivateTags() const; + virtual void LoadPrivateTagsOn(); + virtual void LoadPrivateTagsOff(); + protected: itk::SmartPointer GetImageIOBase(const std::string &fileName); @@ -86,6 +92,7 @@ class SmartPointer; PixelIDValueEnum m_OutputPixelType; + bool m_LoadPrivateTags; }; } diff --git a/Code/IO/src/sitkImageReaderBase.cxx b/Code/IO/src/sitkImageReaderBase.cxx index 3a10c524c..71ffc8a5a 100644 --- a/Code/IO/src/sitkImageReaderBase.cxx +++ b/Code/IO/src/sitkImageReaderBase.cxx @@ -34,13 +34,17 @@ #include #include #include +#include + + namespace itk { namespace simple { ImageReaderBase ::ImageReaderBase() - : m_OutputPixelType(sitkUnknown) + : m_OutputPixelType(sitkUnknown), + m_LoadPrivateTags(false) { } @@ -51,7 +55,8 @@ ::ToString() const std::ostringstream out; out << " OutputPixelType: "; this->ToStringHelper(out, this->m_OutputPixelType) << std::endl; - + out << " LoadPrivateTags: "; + this->ToStringHelper(out, this->m_LoadPrivateTags) << std::endl; out << ProcessObject::ToString(); return out.str(); } @@ -79,10 +84,18 @@ ::GetImageIOBase(const std::string &fileName) sitkExceptionMacro( "Unable to determine ImageIO reader for \"" << fileName << "\"" ); } + // Try additional parameters + GDCMImageIO *ioGDCMImage = dynamic_cast(iobase.GetPointer()); + if (ioGDCMImage) + { + ioGDCMImage->SetLoadPrivateTags(this->m_LoadPrivateTags); + } + // Read the image information iobase->SetFileName( fileName ); iobase->ReadImageInformation(); + return iobase; } @@ -101,6 +114,37 @@ ::GetOutputPixelType( void ) const return this->m_OutputPixelType; } + +ImageReaderBase::Self& +ImageReaderBase +::SetLoadPrivateTags(bool loadPrivateTags) +{ + this->m_LoadPrivateTags = loadPrivateTags; + return *this; +} + +bool +ImageReaderBase +::GetLoadPrivateTags() const +{ + return this->m_LoadPrivateTags; +} + +void +ImageReaderBase +::LoadPrivateTagsOn() +{ + this->SetLoadPrivateTags(true); +} + +void +ImageReaderBase +::LoadPrivateTagsOff() +{ + this->SetLoadPrivateTags(false); +} + + void ImageReaderBase ::GetPixelIDFromImageIO( const std::string &fileName, From ed4c01e9af9d1a335b20a363ae6af705d10e773d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 27 May 2016 15:25:13 -0400 Subject: [PATCH 260/412] Adding Set/Get testing for LoadPrivateTags Change-Id: I86530d3e49d0c8a48d53cf6d8541609366606414 --- Code/IO/include/sitkImageReaderBase.h | 7 ++++++- Testing/Unit/sitkImageIOTests.cxx | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Code/IO/include/sitkImageReaderBase.h b/Code/IO/include/sitkImageReaderBase.h index 3a67988d6..9f887c790 100644 --- a/Code/IO/include/sitkImageReaderBase.h +++ b/Code/IO/include/sitkImageReaderBase.h @@ -61,11 +61,16 @@ class SmartPointer; virtual std::string ToString() const; - + /** \brief Set/Get loading private DICOM tags into Image's MetaData + * + * Unknown private tags may be encoded with Base64 encoding. + * @{ + */ virtual Self& SetLoadPrivateTags(bool loadPrivateTags); virtual bool GetLoadPrivateTags() const; virtual void LoadPrivateTagsOn(); virtual void LoadPrivateTagsOff(); + /* @} */ protected: diff --git a/Testing/Unit/sitkImageIOTests.cxx b/Testing/Unit/sitkImageIOTests.cxx index 6c0598292..f5fe5c41d 100644 --- a/Testing/Unit/sitkImageIOTests.cxx +++ b/Testing/Unit/sitkImageIOTests.cxx @@ -32,6 +32,19 @@ TEST(IO,ImageFileReader) { EXPECT_EQ( reader.GetOutputPixelType(), sitk::sitkUnknown ); + EXPECT_EQ( reader.GetLoadPrivateTags(), false ); + reader.LoadPrivateTagsOn(); + EXPECT_EQ( reader.GetLoadPrivateTags(), true ); + reader.LoadPrivateTagsOff(); + EXPECT_EQ( reader.GetLoadPrivateTags(), false ); + + reader.SetLoadPrivateTags(true); + EXPECT_EQ( reader.GetLoadPrivateTags(), true ); + + reader.SetLoadPrivateTags(false); + EXPECT_EQ( reader.GetLoadPrivateTags(), false ); + + typedef std::map MapType; MapType mapping; From ebda41e5ee7eed81e5338a9bc28f9dc554d622dc Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 27 May 2016 15:40:41 -0400 Subject: [PATCH 261/412] Adding example to print DICOM tags after reading file Change-Id: I78f960c8d5a68801b6f4693e99cdf40f7dd8f929 --- Examples/Python/CMakeLists.txt | 11 ++++++++ Examples/Python/DicomImagePrintTags.py | 38 ++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100755 Examples/Python/DicomImagePrintTags.py diff --git a/Examples/Python/CMakeLists.txt b/Examples/Python/CMakeLists.txt index 4d47e905a..ea7e4975d 100644 --- a/Examples/Python/CMakeLists.txt +++ b/Examples/Python/CMakeLists.txt @@ -88,6 +88,17 @@ sitk_add_python_test( Example.DicomSeriesReader2 "${TEST_HARNESS_TEMP_DIRECTORY}/DicomSeriesReader2.nrrd" ) + +sitk_add_python_test( Example.DicomImagePrintTags + "${CMAKE_CURRENT_SOURCE_DIR}/DicomImagePrintTags.py" + DATA{${SimpleITK_DATA_ROOT}/Input/DicomSeries/Image0075.dcm} + ) + + +set_tests_properties( Python.Example.DicomImagePrintTags + PROPERTIES PASS_REGULAR_EXPRESSION "\\(0008|0060\\) = = \"MR\"") + + sitk_add_python_test( Example.ConnectedThresholdImageFilter1 "${CMAKE_CURRENT_SOURCE_DIR}/ConnectedThresholdImageFilter.py" --compare-MD5 diff --git a/Examples/Python/DicomImagePrintTags.py b/Examples/Python/DicomImagePrintTags.py new file mode 100755 index 000000000..357d56264 --- /dev/null +++ b/Examples/Python/DicomImagePrintTags.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python +#========================================================================= +# +# Copyright Insight Software Consortium +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0.txt +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#========================================================================= + +from __future__ import print_function + +import SimpleITK as sitk +import sys, os + +if len ( sys.argv ) < 2: + print( "Usage: DicomImagePrintTags " ) + sys.exit ( 1 ) + +reader = sitk.ImageFileReader() + +reader.SetFileName( sys.argv[1] ) +reader.LoadPrivateTagsOn(); + +inputImage = reader.Execute() + +for k in inputImage.GetMetaDataKeys(): + v = inputImage.GetMetaData(k) + print("({0}) = = \"{1}\"".format(k,v)) From 6c8dc9f2deffa4dfd15a18262c06981804becc60 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 31 May 2016 10:03:40 -0400 Subject: [PATCH 262/412] Updating to SWIG 3.0.9 release Change-Id: I829882b1331d24bfb01a8da26de287afac6a2492 --- SuperBuild/External_Swig.cmake | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/SuperBuild/External_Swig.cmake b/SuperBuild/External_Swig.cmake index d31b3d6a6..3de7a2e96 100644 --- a/SuperBuild/External_Swig.cmake +++ b/SuperBuild/External_Swig.cmake @@ -20,14 +20,14 @@ if(NOT SWIG_DIR) if( USE_SWIG_FROM_GIT ) set(SWIG_GIT_REPOSITORY "${git_protocol}://github.com/swig/swig.git" CACHE STRING "URL of swig git repo") - set(SWIG_GIT_TAG "8890a675f7783436d0c7b61fdb318f30ffb92cde" CACHE STRING "Tag in swig git repo") + set(SWIG_GIT_TAG "rel-3.0.9" CACHE STRING "Tag in swig git repo") mark_as_advanced(SWIG_GIT_REPO) mark_as_advanced(SWIG_GIT_TAG) endif() - set(SWIG_TARGET_VERSION 3.0.8) - set(SWIG_DOWNLOAD_SOURCE_HASH "c96a1d5ecb13d38604d7e92148c73c97") - set(SWIG_DOWNLOAD_WIN_HASH "07bc00f7511b7d57516c50f59d705efa") + set(SWIG_TARGET_VERSION "3.0.9" ) + set(SWIG_DOWNLOAD_SOURCE_HASH "4bc5f46a6cdedbd8f579b25fafc96fd6") + set(SWIG_DOWNLOAD_WIN_HASH "811adf794d26a0cf54da578c2b9a14a3") if(WIN32) # binary SWIG for windows From 74c88b6cf67c30497abb055ffdc042b5ed863bb8 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 13 May 2016 09:35:44 -0400 Subject: [PATCH 263/412] Add R tests for new features with SWIG Added a test that covers all the types of numeric vectors as method arguments. Change-Id: Ibcc8c5af60fff56c133c4db5dd69baea5d51110b --- Testing/Unit/AdditionalTests.cmake | 3 ++ Testing/Unit/RSwigVectorConversionTests.R | 45 +++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 Testing/Unit/RSwigVectorConversionTests.R diff --git a/Testing/Unit/AdditionalTests.cmake b/Testing/Unit/AdditionalTests.cmake index 744da0982..901a6b15c 100644 --- a/Testing/Unit/AdditionalTests.cmake +++ b/Testing/Unit/AdditionalTests.cmake @@ -62,6 +62,9 @@ sitk_add_r_test( PixelIndexing sitk_add_r_test( ImageListArguments "--file=${SimpleITK_SOURCE_DIR}/Testing/Unit/RImageListArguments.R" ) +sitk_add_r_test( SwigVectorConversion + "--file=${SimpleITK_SOURCE_DIR}/Testing/Unit/RSwigVectorConversionTests.R" + ) # diff --git a/Testing/Unit/RSwigVectorConversionTests.R b/Testing/Unit/RSwigVectorConversionTests.R new file mode 100644 index 000000000..f4fac40ed --- /dev/null +++ b/Testing/Unit/RSwigVectorConversionTests.R @@ -0,0 +1,45 @@ +## Test automatic conversion of C++ std::vector types +## Note that RPixelAccess tests all the options for numeric vectors +## being converted to R vectors, but it doesn't test conversion +## from R to C++ +## Dicom example deals with std::vector cases +## Some problems have occurred in the past due to references not being +## included specifically in the swig definitions. +library(SimpleITK) +options(warn=2) +img = Image(64, 64, "sitkFloat32") +img$SetOrigin(c(0.3,0.6)) +img$SetSpacing(c(0.4,1.0)) +p1<-c(0.1,0.1) + +## This is a problem with swig and unsupported vector types +## Will need to address it. +## R to const std::vector< double > &point +## and std::vector< int64_t > to R +p1Indexes <-img$TransformPhysicalPointToIndex(p1) +sprintf("Point coordinates: %.1f %.1f Point indexes: %d %d",p1[1],p1[2],p1Indexes[1], p1Indexes[2]) + + + +# R to const std::vector< int64_t > &index) +# std::vector to R +p2Location <- img$TransformIndexToPhysicalPoint(c(1,1)) +print(p2Location) + +# R to const std::vector &r +bd <- BinaryDilateImageFilter() +bd <- bd$SetKernelRadius(c(3,4)) +# std::vector to R +bd$GetKernelRadius() + +# R to const std::vector & Radius +bm <- BinaryMedianImageFilter() +bm <- bm$SetRadius(c(7,7)) +# std::vector to R +bm$GetRadius() + +# R to std::vector +st <- MultiLabelSTAPLEImageFilter() +st <- st$SetPriorProbabilities(c(0.25, 0.25, 0.1)) +# std::vector to R +st$GetPriorProbabilities() From 210149e802792466ee1f1dda145021a1ffccb8e7 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 1 Jun 2016 10:12:26 -0400 Subject: [PATCH 264/412] Fix setting using git vs https protocol for ITK superbuild The variable was unset before. Change-Id: I5b236b60f70bc3536a8aaee05361d2c6dd131ead --- SuperBuild/External_ITK.cmake | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index c3d9a71e4..53eb66216 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -34,6 +34,11 @@ VariableListToArgs( ITK_VARS ep_itk_args ) set(proj ITK) ## Use ITK convention of calling it ITK set(ITK_REPOSITORY "${git_protocol}://itk.org/ITK.git") +set(ITK_USE_GIT_PROTOCOL 0) +if("${git_protocol}" STREQUAL "git") + set(ITK_USE_GIT_PROTOCOL 1) +endif() + # NOTE: it is very important to update the ITK_DIR path with the ITK version set(ITK_TAG_COMMAND GIT_TAG v4.10.0 ) From 2b301088336c98be498b11e818bd740ce22eb48f Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 1 Jun 2016 13:45:35 -0400 Subject: [PATCH 265/412] Fix PEP 440 compliance with "+" for local identifier Change-Id: Ifa8da3199f9317eacdc58189d7e1e6a17cd884c8 --- Wrapping/Python/Packaging/setup.py.in | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Wrapping/Python/Packaging/setup.py.in b/Wrapping/Python/Packaging/setup.py.in index 2fc983854..f432bc2a1 100644 --- a/Wrapping/Python/Packaging/setup.py.in +++ b/Wrapping/Python/Packaging/setup.py.in @@ -37,8 +37,9 @@ def get_pep386version(): elif sitkDEV: version += ".dev"+sitkDEV + # Local Version Identifier if sitkHASH and not "@SimpleITK_BUILD_DISTRIBUTE@" in ['1', 'ON']: - version += "-g"+sitkHASH + version += "+g"+sitkHASH return version From 60a9b28faed21ebbb08411c44cde8da43b29a671 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 1 Jun 2016 14:59:00 -0400 Subject: [PATCH 266/412] Address CMP0058 issue with configure time generated files Use the configure_file CMake command to copy from temporary file to the build tree for a dependency. Change-Id: I3a7953875efda06026ef1ca77ff1e85405c3e961 --- CMake/sitkGenerateFilterSource.cmake | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/CMake/sitkGenerateFilterSource.cmake b/CMake/sitkGenerateFilterSource.cmake index c7883ed20..edf2510ee 100644 --- a/CMake/sitkGenerateFilterSource.cmake +++ b/CMake/sitkGenerateFilterSource.cmake @@ -210,24 +210,25 @@ macro(generate_filter_source) # Create list of generated headers ###### - # clear the include files - file ( WRITE ${generated_code_output_path}/include/SimpleITK${directory_name}GeneratedHeaders.h "" ) - file ( WRITE ${generated_code_output_path}/include/SimpleITK${directory_name}GeneratedHeaders.i "" ) - set(generated_headers_h ${generated_code_output_path}/include/SimpleITK${directory_name}GeneratedHeaders.h) set(generated_headers_i ${generated_code_output_path}/include/SimpleITK${directory_name}GeneratedHeaders.i) + set(tmp_generated_headers_h ${CMAKE_CURRENT_BINARY_DIR}/CMakeTmp/SimpleITK${directory_name}GeneratedHeaders.h) + set(tmp_generated_headers_i ${CMAKE_CURRENT_BINARY_DIR}/CMakeTmp/include/SimpleITK${directory_name}GeneratedHeaders.i) + + file ( WRITE ${generated_headers_i} "") # Add ifndefs - file ( APPEND ${generated_headers_h} "#ifndef __SimpleITK${directory_name}GeneratedHeaders_h\n") - file ( APPEND ${generated_headers_h} "#define __SimpleITK${directory_name}GeneratedHeaders_h\n") + file ( WRITE "${tmp_generated_headers_h}" "#ifndef __SimpleITK${directory_name}GeneratedHeaders_h\n") + file ( APPEND "${tmp_generated_headers_h}" "#define __SimpleITK${directory_name}GeneratedHeaders_h\n") foreach ( filter ${GENERATED_FILTER_LIST} ) - file ( APPEND ${generated_headers_h} "#include \"sitk${filter}.h\"\n" ) - file ( APPEND ${generated_headers_i} "%include \"sitk${filter}.h\"\n" ) + file ( APPEND "${tmp_generated_headers_h}" "#include \"sitk${filter}.h\"\n" ) + file ( APPEND "${tmp_generated_headers_i}" "%include \"sitk${filter}.h\"\n" ) endforeach() - file ( APPEND ${generated_headers_h} "#endif\n") - + file ( APPEND "${tmp_generated_headers_h}" "#endif\n") + configure_file( "${tmp_generated_headers_h}" "${generated_headers_h}" COPYONLY ) + configure_file( "${tmp_generated_headers_i}" "${generated_headers_i}" COPYONLY ) endmacro() From 8aacbbe200ccd8db6ffd75fd7ddb4eedac6923bb Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 2 Jun 2016 11:41:04 -0400 Subject: [PATCH 267/412] Fix Output path for GTEST library with Ninja Corrected the output path to include the config directory only with Visual Studio. Change-Id: Icdc7650d1dc80bf63c7377054c5e802c440ef98f --- SuperBuild/External_GTest.cmake | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SuperBuild/External_GTest.cmake b/SuperBuild/External_GTest.cmake index 718356d05..d3f9be683 100644 --- a/SuperBuild/External_GTest.cmake +++ b/SuperBuild/External_GTest.cmake @@ -23,8 +23,8 @@ set(GTEST_PATCH_COMMAND ${CMAKE_COMMAND} -E copy_if_different ) set(${proj}_ARCHIVE_OUTPUT_DIRECTORY "/lib") -if (MSVC) - set(${proj}_ARCHIVE_OUTPUT_DIRECTORY "/lib/$") +if (CMAKE_GENERATOR MATCHES "Visual Studio") + set(${proj}_ARCHIVE_OUTPUT_DIRECTORY "/lib/$") endif() set(ep_extra_args) From aac1d14d462a81583585c69682835b34d38c446d Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Thu, 2 Jun 2016 15:12:00 -0400 Subject: [PATCH 268/412] Fixed the timeout value for Show on Windows The timeout value was set at 500. That is for 500 milliseconds on Linux and OS X. But on Windows the units are seconds, not milliseconds. So it's now set to 1 second. Change-Id: If7bd1dccf7aabad4a3bc86a476f5ed1f18f69ec6 --- Code/IO/src/sitkShow.cxx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Code/IO/src/sitkShow.cxx b/Code/IO/src/sitkShow.cxx index 0e5cde283..ecd82ea29 100644 --- a/Code/IO/src/sitkShow.cxx +++ b/Code/IO/src/sitkShow.cxx @@ -41,8 +41,13 @@ namespace itk static int ShowImageCount = 0; +#if defined(_WIN32) + // time to wait in seconds before we check if the process is OK + const unsigned int ProcessDelay = 1; +#else // time to wait in milli-seconds before we check if the process is OK const unsigned int ProcessDelay = 500; +#endif #define IMAGEJ_OPEN_MACRO "\'open(\"%f\"); rename(\"%t\"); \'" #define NIFTI_COLOR_MACRO "\'run(\"Make Composite\", \"display=Composite\");\'" From 60b03595d1d3c02d475ea270c147723b895cc0fc Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Fri, 3 Jun 2016 16:11:32 -0400 Subject: [PATCH 269/412] Refactored semi-colon hack Before there was a hack that used many backslashes to allow a semi-colon in a function parameter to get propogated down through multiple function calls. I've re-written it in a better fashion, using the generator expression. Change-Id: Ic524b0a680010c29198f716feca0e3026555cacd --- CMake/sitkAddTest.cmake | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index 0464c624c..192d49562 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -164,15 +164,7 @@ function(sitk_add_java_test name java_file) if(WIN32) set( _JAVA_LIBRARY_PATH "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/$" ) - # Note: on windows this is a semi-colon separated list - # Note 2: there are 7 or 11 backslashes (depending on the cmake version) - # before the semi-colon so that it gets properly passed through - # 4 levels of function calls. - if (${CMAKE_VERSION} VERSION_LESS "3.5") - set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}\\\\\\\\\\\;${CMAKE_CURRENT_BINARY_DIR}" ) - else() - set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}\\\\\\\;${CMAKE_CURRENT_BINARY_DIR}" ) - endif() + set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}$${CMAKE_CURRENT_BINARY_DIR}" ) else(WIN32) set( _JAVA_LIBRARY_PATH "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}" ) From ac0ac2754164eb55ab12c679e5957fa3af87daa5 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 6 Jun 2016 13:04:11 -0400 Subject: [PATCH 270/412] Address narrowing conversion warnings itkSliceImageFilterTest.cxx(98): warning C4838: conversion from 'double' to 'float' requires a narrowing conversion Change-Id: I651b5762acbab4d49656d051f90a7239bd499f4f --- Testing/Unit/itkSliceImageFilterTest.cxx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Testing/Unit/itkSliceImageFilterTest.cxx b/Testing/Unit/itkSliceImageFilterTest.cxx index 0565ee157..cb541884a 100644 --- a/Testing/Unit/itkSliceImageFilterTest.cxx +++ b/Testing/Unit/itkSliceImageFilterTest.cxx @@ -95,7 +95,7 @@ TEST(SliceImageFilterTests, PhysicalPoint1) SourceType::SizeValueType size[] = {128,127}; source->SetSize( size ); - float origin[] = {1.1, 2.22}; + float origin[] = {1.1f, 2.22f}; source->SetOrigin( origin ); @@ -134,7 +134,7 @@ TEST(SliceImageFilterTests, PhysicalPoint2) SourceType::SizeValueType size[] = {128,127}; source->SetSize( size ); - float origin[] = {3.33, 4.4444}; + float origin[] = {3.33f, 4.4444f}; source->SetOrigin( origin ); @@ -176,7 +176,7 @@ TEST(SliceImageFilterTests, PhysicalPoint3) SourceType::SizeValueType size[] = {16,17}; source->SetSize( size ); - float origin[] = {3.33, 4.4444}; + float origin[] = {3.33f, 4.4444f}; source->SetOrigin( origin ); int step[ImageDimension] = {-2,-2}; From fa9329edc2e799b4e71dbd595efcff6f08c6fae7 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 6 Jun 2016 13:07:15 -0400 Subject: [PATCH 271/412] Updating Superbuild version of virtualenv to 15.0.2 Change-Id: I909ca6b7f9f644ec93c7060d3ba9b2684dacfae0 --- SuperBuild/External_virtualenv.cmake | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SuperBuild/External_virtualenv.cmake b/SuperBuild/External_virtualenv.cmake index 645af579c..fb9c781dd 100644 --- a/SuperBuild/External_virtualenv.cmake +++ b/SuperBuild/External_virtualenv.cmake @@ -7,11 +7,11 @@ set(${CMAKE_CURRENT_LIST_FILENAME}_FILE_INCLUDED 1) set(proj virtualenv) -set(${proj}_TARGET_VERSION 15.0.1) -set(${proj}_DOWNLOAD_SOURCE_HASH "28d76a0d9cbd5dc42046dd14e76a6ecc") +set(${proj}_TARGET_VERSION 15.0.2) +set(${proj}_DOWNLOAD_SOURCE_HASH "0ed59863994daf1292827ffdbba80a63") # based on the standard EP_PREFIX locations, but since we don't build -# or install, then standars install directory is also the source +# or install, then standards install directory is also the source set(${proj}_binary_dir ${CMAKE_CURRENT_BINARY_DIR}/${proj}-prefix/src/${proj}-build) set(${proj}_source_dir ${CMAKE_CURRENT_BINARY_DIR}/${proj}) set(${proj}_install_dir ${CMAKE_CURRENT_BINARY_DIR}/${proj}) From e4d05a6774e561facf9524749f5afa932c06997d Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 7 Jun 2016 11:12:52 -0400 Subject: [PATCH 272/412] Removing unused typedef of Self causing SWIG warnings Change-Id: Iba2d06b0b1b61a71d7a538a34d393bf45d2c881f --- Code/Common/include/sitkCommand.h | 3 --- 1 file changed, 3 deletions(-) diff --git a/Code/Common/include/sitkCommand.h b/Code/Common/include/sitkCommand.h index 25420a15f..7be354a93 100644 --- a/Code/Common/include/sitkCommand.h +++ b/Code/Common/include/sitkCommand.h @@ -45,9 +45,6 @@ class SITKCommon_EXPORT Command: protected NonCopyable { public: -#ifndef SWIG - typedef Command Self; -#endif /** \brief Default Constructor */ Command(); From 9b367cd60344c5b5bf7417f4c7b987bcb04497a4 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 7 Jun 2016 11:15:38 -0400 Subject: [PATCH 273/412] Better suppress self warnings from SWIG Change-Id: Ic63eeaf91d1c0a0154877df25aa75dc447a26dd2 --- CMake/CTestCustom.cmake.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMake/CTestCustom.cmake.in b/CMake/CTestCustom.cmake.in index f1faa958c..198581106 100644 --- a/CMake/CTestCustom.cmake.in +++ b/CMake/CTestCustom.cmake.in @@ -65,7 +65,7 @@ SET(CTEST_CUSTOM_WARNING_EXCEPTION "warning: lowering visibility of .* to match its type" # Warning from SWIG with self member type - "sitkCommand.* Warning 314.*self.*is a python keyword" + "sitkCommand.* [wW]arning 314.*self.*is a python keyword" # Warning from RH5 gcc 4.1.2 "tr1/mu_iterate.h.* warning: unused parameter '__tuple'" From d9dfb1eab1404c4839ecdf13f523154ef12db12c Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 7 Jun 2016 11:27:26 -0400 Subject: [PATCH 274/412] Restore missing warnings flags to compilation Change-Id: Ic5ba210f1b0cc768604b903c3f0ddb48b3b6c425 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 22da6db52..5ad636731 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -79,7 +79,7 @@ endif() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SimpleITK_REQUIRED_C_FLAGS}") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SimpleITK_REQUIRED_CXX_FLAGS}") +set(CMAKE_CXX_FLAGS "${CXX_ADDITIONAL_WARNING_FLAGS} ${CMAKE_CXX_FLAGS} ${SimpleITK_REQUIRED_CXX_FLAGS}") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") From ece234a331e6c37cb07ceaf2a770997ad510668b Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 9 Jun 2016 15:54:50 -0400 Subject: [PATCH 275/412] Removing usage of return self from tests Change-Id: I12f510207b6f739d5560d8f11537bdc7cee1e338 --- Testing/Unit/CSharpImageFilterTestTemplate.cs.in | 7 ++++--- Testing/Unit/JavaImageFilterTestTemplate.java.in | 6 ++++-- Testing/Unit/PythonImageFilterTestTemplate.py.in | 11 ++++++----- Testing/Unit/RSwigVectorConversionTests.R | 6 +++--- Testing/Unit/RubyImageFilterTestTemplate.rb.in | 3 ++- Testing/Unit/TclImageFilterTestTemplate.tcl.in | 3 ++- Testing/Unit/sitkImageCompare.h | 2 +- 7 files changed, 22 insertions(+), 16 deletions(-) diff --git a/Testing/Unit/CSharpImageFilterTestTemplate.cs.in b/Testing/Unit/CSharpImageFilterTestTemplate.cs.in index 672d08f3d..297f7e091 100644 --- a/Testing/Unit/CSharpImageFilterTestTemplate.cs.in +++ b/Testing/Unit/CSharpImageFilterTestTemplate.cs.in @@ -63,8 +63,8 @@ $(foreach tests // Read image(s) for ( int i = 2; i < args.Length-1; i++ ) { - - inputs.Add( reader.SetFileName( args[i] ).Execute() ); + reader.SetFileName( args[i] ); + inputs.Add( reader.Execute() ); } $(if inputA_cast then @@ -181,7 +181,8 @@ OUT=[[ // Write output ImageFileWriter writer = new ImageFileWriter(); - writer.SetFileName( args[args.Length-1] ).Execute( output ); + writer.SetFileName( args[args.Length-1] ); + writer.Execute( output ); ]] end) diff --git a/Testing/Unit/JavaImageFilterTestTemplate.java.in b/Testing/Unit/JavaImageFilterTestTemplate.java.in index fac150ee5..ce576df53 100644 --- a/Testing/Unit/JavaImageFilterTestTemplate.java.in +++ b/Testing/Unit/JavaImageFilterTestTemplate.java.in @@ -82,7 +82,8 @@ $(foreach tests // Read image(s) $(for i=0,#inputs-1 do OUT=OUT..[[ - inputs[]]..i..[[] = reader.setFileName( argv[]]..i..[[+1] ).execute(); + reader.setFileName( argv[]]..i..[[+1] ); + inputs[]]..i..[[] = reader.execute(); ]] end) @@ -237,7 +238,8 @@ OUT=[[ } // Write output - writer.setFileName( argv[argv.length - 1] ).execute( output ); + writer.setFileName( argv[argv.length - 1] ); + writer.execute( output ); ]] end) } diff --git a/Testing/Unit/PythonImageFilterTestTemplate.py.in b/Testing/Unit/PythonImageFilterTestTemplate.py.in index 23663c582..c6bdb7c60 100644 --- a/Testing/Unit/PythonImageFilterTestTemplate.py.in +++ b/Testing/Unit/PythonImageFilterTestTemplate.py.in @@ -56,16 +56,16 @@ $(when settings $(foreach settings $(if parameter == "SeedList" and python_value then OUT=[[ filter.ClearSeeds() - filter$(for i=1,#python_value do OUT=OUT .. ".AddSeed( " .. python_value[i] .. " )" end)]] + $(for i=1,#python_value do OUT=OUT .. "\n filter.AddSeed( " .. python_value[i] .. " )\n" end)]] elseif parameter == "SeedList" then OUT=[[ filter.ClearSeeds() - filter$(for i=1,#value do OUT=OUT .. ".AddSeed( " .. value[i] .. " )" end)]] + $(for i=1,#value do OUT=OUT .. "\n filter.AddSeed( " .. value[i] .. " )\n" end)]] elseif parameter == "TrialPoints" and python_value then OUT=[[ filter.ClearTrialPoints() - filter$(for i=1,#python_value do OUT=OUT .. ".AddTrialPoint( " .. python_value[i] .. " )" end)]] + $(for i=1,#python_value do OUT=OUT .. "\n filter.AddTrialPoint( " .. python_value[i] .. " )\n" end)]] elseif parameter == "TrialPoints" then OUT=[[ filter.ClearTrialPoints() - filter$(for i=1,#value do OUT=OUT .. ".AddTrialPoint( " .. value[i] .. " )" end)]] + $(for i=1,#value do OUT=OUT .. "\n filter.AddTrialPoint( " .. value[i] .. " )" end)]] elseif python_value then OUT=[[ filter.Set${parameter}( ${python_value} )]] @@ -109,7 +109,8 @@ end) output = SimpleITK.LabelMapToLabel(output) $(if not no_return_image then OUT=[[ - writer.SetFileName ( sys.argv[-1] ).Execute ( output ) + writer.SetFileName ( sys.argv[-1] ) + writer.Execute ( output ) ]] end) ) diff --git a/Testing/Unit/RSwigVectorConversionTests.R b/Testing/Unit/RSwigVectorConversionTests.R index f4fac40ed..43f783c80 100644 --- a/Testing/Unit/RSwigVectorConversionTests.R +++ b/Testing/Unit/RSwigVectorConversionTests.R @@ -28,18 +28,18 @@ print(p2Location) # R to const std::vector &r bd <- BinaryDilateImageFilter() -bd <- bd$SetKernelRadius(c(3,4)) +bd$SetKernelRadius(c(3,4)) # std::vector to R bd$GetKernelRadius() # R to const std::vector & Radius bm <- BinaryMedianImageFilter() -bm <- bm$SetRadius(c(7,7)) +bm$SetRadius(c(7,7)) # std::vector to R bm$GetRadius() # R to std::vector st <- MultiLabelSTAPLEImageFilter() -st <- st$SetPriorProbabilities(c(0.25, 0.25, 0.1)) +st$SetPriorProbabilities(c(0.25, 0.25, 0.1)) # std::vector to R st$GetPriorProbabilities() diff --git a/Testing/Unit/RubyImageFilterTestTemplate.rb.in b/Testing/Unit/RubyImageFilterTestTemplate.rb.in index 8f19a8dbd..6f7702cde 100644 --- a/Testing/Unit/RubyImageFilterTestTemplate.rb.in +++ b/Testing/Unit/RubyImageFilterTestTemplate.rb.in @@ -141,7 +141,8 @@ OUT=[[ caster = Simpleitk::LabelMapToLabelImageFilter.new output = caster.execute( output ) end - writer.set_file_name( ARGV[ARGV.length-1] ).execute( output ) + writer.set_file_name( ARGV[ARGV.length-1] ) + writer.execute( output ) ]] end) end diff --git a/Testing/Unit/TclImageFilterTestTemplate.tcl.in b/Testing/Unit/TclImageFilterTestTemplate.tcl.in index 73ece5eac..46c6280b0 100644 --- a/Testing/Unit/TclImageFilterTestTemplate.tcl.in +++ b/Testing/Unit/TclImageFilterTestTemplate.tcl.in @@ -106,7 +106,8 @@ OUT=[[ set output [ LabelMapToLabel $$output ] } - [writer SetFileName [lindex $$argv end] ] Execute $$output + writer SetFileName [lindex $$argv end] + writer Execute $$output ]] end) exit diff --git a/Testing/Unit/sitkImageCompare.h b/Testing/Unit/sitkImageCompare.h index 2e703af09..f3a58abb1 100644 --- a/Testing/Unit/sitkImageCompare.h +++ b/Testing/Unit/sitkImageCompare.h @@ -37,7 +37,7 @@ class ImageCompare { // Return the message from the previous image comparison. std::string getMessage() { return mMessage; } - Self& setTolerance ( double t ) { mTolerance = t; return *this; } + SITK_RETURN_SELF_TYPE_HEADER setTolerance ( double t ) { mTolerance = t; return *this; } double getTolerance() { return mTolerance; } static void NormalizeAndSave ( const itk::simple::Image &image, const std::string &filename ); From f0065897c5d59dcbf60165539ba67bd12d6ad6bf Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 08:21:47 -0400 Subject: [PATCH 276/412] Remove usage or return self define from testing utility. Change-Id: I1eadd9ffb9a7b5b705b7ca1f02aab0b31ddc5b8c --- Testing/Unit/sitkImageCompare.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Testing/Unit/sitkImageCompare.h b/Testing/Unit/sitkImageCompare.h index f3a58abb1..3f6ca0ed0 100644 --- a/Testing/Unit/sitkImageCompare.h +++ b/Testing/Unit/sitkImageCompare.h @@ -37,7 +37,7 @@ class ImageCompare { // Return the message from the previous image comparison. std::string getMessage() { return mMessage; } - SITK_RETURN_SELF_TYPE_HEADER setTolerance ( double t ) { mTolerance = t; return *this; } + void setTolerance ( double t ) { mTolerance = t; } double getTolerance() { return mTolerance; } static void NormalizeAndSave ( const itk::simple::Image &image, const std::string &filename ); From 469e908bcf8707fcdeff94da71d793b78cb3365e Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 08:56:10 -0400 Subject: [PATCH 277/412] Remove Self typedef in PyCommand Mitigate Swig warning about self being a reserved word. Change-Id: Iee583123c5292b08705e0d3541355079f591b4a6 --- Wrapping/Python/sitkPyCommand.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/Wrapping/Python/sitkPyCommand.h b/Wrapping/Python/sitkPyCommand.h index 85383cc74..6158e246a 100644 --- a/Wrapping/Python/sitkPyCommand.h +++ b/Wrapping/Python/sitkPyCommand.h @@ -47,8 +47,6 @@ class PyCommand : public itk::simple::Command { public: - // Standard "Self" typedef. - typedef PyCommand Self; typedef Command Super; PyCommand(); From 75cfaa4440ba9dae9404a0d5998bd1fef0c43e47 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 10:32:22 -0400 Subject: [PATCH 278/412] Move hidden required MSVC flags to common required flags file. Change-Id: I0fddb366007e0706bba42e3a16d9069d209b5d12 --- CMake/sitkCheckRequiredFlags.cmake | 26 ++++++++++++++++++++++++++ CMakeLists.txt | 24 ------------------------ 2 files changed, 26 insertions(+), 24 deletions(-) diff --git a/CMake/sitkCheckRequiredFlags.cmake b/CMake/sitkCheckRequiredFlags.cmake index 53a625951..9ff82ba1c 100644 --- a/CMake/sitkCheckRequiredFlags.cmake +++ b/CMake/sitkCheckRequiredFlags.cmake @@ -19,6 +19,32 @@ if( NOT DEFINED SimpleITK_REQUIRED_LINK_FLAGS ) set(SimpleITK_REQUIRED_LINK_FLAGS "") endif() +if(MSVC) + # /bigobj is required for windows builds because of the size of + # some object files (CastImage for instance) + # Also supress the pesky warning about std::vector not being marked + # for export in the dll + set ( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj /wd4251" ) + set ( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /bigobj" ) + + # Avoid some warnings + add_definitions ( -D_SCL_SECURE_NO_WARNINGS ) + + + # force debug linking not to be incremental + foreach( _varName + CMAKE_EXE_LINKER_FLAGS_DEBUG + CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO + CMAKE_MODULE_LINKER_FLAGS_DEBUG + CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO + CMAKE_SHARED_LINKER_FLAGS_DEBUG + CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO ) + STRING(REGEX REPLACE "INCREMENTAL(:[a-zA-Z]+)?" "INCREMENTAL:NO" ${_varName} ${${_varName}}) + endforeach() + +endif() + + # # Search CMAKE_CXX_FLAGS for flags that should be considered required, # and propagated to other projects, via the diff --git a/CMakeLists.txt b/CMakeLists.txt index 22da6db52..3fae24d84 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -220,30 +220,6 @@ include(sitkStripOption) #------------------------------------------------------------------------------ # These are some system specific compiler options needed to build SimpleITK -if(MSVC) - # /bigobj is required for windows builds because of the size of - # some object files (CastImage for instance) - # Also supress the pesky warning about std::vector not being marked - # for export in the dll - set ( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj /wd4251" ) - set ( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /bigobj" ) - - # Avoid some warnings - add_definitions ( -D_SCL_SECURE_NO_WARNINGS ) - - - # force debug linking not to be incremental - foreach( _varName - CMAKE_EXE_LINKER_FLAGS_DEBUG - CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO - CMAKE_MODULE_LINKER_FLAGS_DEBUG - CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO - CMAKE_SHARED_LINKER_FLAGS_DEBUG - CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO ) - STRING(REGEX REPLACE "INCREMENTAL(:[a-zA-Z]+)?" "INCREMENTAL:NO" ${_varName} ${${_varName}}) - endforeach() - -endif() include(CheckCXXCompilerFlag) From 65ee13d0009d09432809c0d5360511aa6310dac9 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 10:33:38 -0400 Subject: [PATCH 279/412] Adding flags for mingw to create big object files Change-Id: Ib72e891da86453bed30872d8d7c6c6d38e1150cf --- CMake/sitkCheckRequiredFlags.cmake | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CMake/sitkCheckRequiredFlags.cmake b/CMake/sitkCheckRequiredFlags.cmake index 9ff82ba1c..947a8f678 100644 --- a/CMake/sitkCheckRequiredFlags.cmake +++ b/CMake/sitkCheckRequiredFlags.cmake @@ -44,6 +44,11 @@ if(MSVC) endif() +if(MINGW) + set ( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wa,-mbig-obj" ) + set ( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wa,-mbig-obj" ) +endif() + # # Search CMAKE_CXX_FLAGS for flags that should be considered required, From d65b73867c4ed825ebb38373a8f12b317f6c369c Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 11:35:52 -0400 Subject: [PATCH 280/412] Adding missing SWIG dependency on SimpleITK_Common.i Change-Id: I46db80542bc63791230bf407c9edf2f10b949f7f --- CMake/sitkProjectLanguageCommon.cmake | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CMake/sitkProjectLanguageCommon.cmake b/CMake/sitkProjectLanguageCommon.cmake index 9072fe1bd..362b2c5fa 100644 --- a/CMake/sitkProjectLanguageCommon.cmake +++ b/CMake/sitkProjectLanguageCommon.cmake @@ -44,6 +44,9 @@ find_package ( SWIG 2 REQUIRED ) include (sitkUseSWIG) +set(SIMPLEITK_WRAPPING_COMMON_DIR + ${SimpleITK_SOURCE_DIR}/Wrapping/Common) + file(GLOB SWIG_EXTRA_DEPS "${SimpleITK_SOURCE_DIR}/Code/Common/include/*.h" "${SimpleITK_SOURCE_DIR}/Code/Registration/include/*.h" @@ -52,6 +55,7 @@ file(GLOB SWIG_EXTRA_DEPS # make a manual list of dependencies for the Swig.i files list( APPEND SWIG_EXTRA_DEPS "${SimpleITK_BINARY_DIR}/Code/BasicFilters/include/SimpleITKBasicFiltersGeneratedHeaders.i" "${SimpleITK_BINARY_DIR}/Code/BasicFilters/include/SimpleITKBasicFiltersGeneratedHeaders.h" + "${SIMPLEITK_WRAPPING_COMMON_DIR}/SimpleITK_Common.i" ${SimpleITKBasicFiltersGeneratedHeader} ) @@ -65,9 +69,6 @@ if(${SITK_ULONG_SAME_AS_UINT64} ) set ( CMAKE_SWIG_GLOBAL_FLAGS "-DSWIGWORDSIZE64" ) endif() -set(SIMPLEITK_WRAPPING_COMMON_DIR - ${SimpleITK_SOURCE_DIR}/Wrapping/Common) - set ( CMAKE_SWIG_GLOBAL_FLAGS -I${SIMPLEITK_WRAPPING_COMMON_DIR} ${CMAKE_SWIG_GLOBAL_FLAGS} ) include(sitkTargetLinkLibrariesWithDynamicLookup) From 70f78d34dcee44a4aa1a41a533fe2b063db33313 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 11:43:31 -0400 Subject: [PATCH 281/412] Move language specific Swig into language files Change-Id: If24d7d49f835996aab9027cf72ebdc2e31250f62 --- Wrapping/CSharp/SimpleITK.i | 1 + Wrapping/Common/SimpleITK_Common.i | 14 -------------- Wrapping/Python/SimpleITK.i | 2 ++ Wrapping/R/SimpleITK.i | 2 ++ 4 files changed, 5 insertions(+), 14 deletions(-) diff --git a/Wrapping/CSharp/SimpleITK.i b/Wrapping/CSharp/SimpleITK.i index 74635c2ab..027d6016f 100644 --- a/Wrapping/CSharp/SimpleITK.i +++ b/Wrapping/CSharp/SimpleITK.i @@ -1 +1,2 @@ %include SimpleITK_Common.i +%include "sitkImportImageFilter.h" diff --git a/Wrapping/Common/SimpleITK_Common.i b/Wrapping/Common/SimpleITK_Common.i index 2d9a8a905..f363992c7 100644 --- a/Wrapping/Common/SimpleITK_Common.i +++ b/Wrapping/Common/SimpleITK_Common.i @@ -199,19 +199,5 @@ namespace std %include "sitkImageRegistrationMethod.h" -// Only C# can handle import filter -#if SWIGCSHARP -%include "sitkImportImageFilter.h" -#endif - - -#if SWIGPYTHON -%include "sitkPyCommand.h" -#endif - -#if SWIGR -%include "sitkRCommand.h" -#endif - // Auto-generated headers %include "SimpleITKBasicFiltersGeneratedHeaders.i" diff --git a/Wrapping/Python/SimpleITK.i b/Wrapping/Python/SimpleITK.i index 74635c2ab..4be0c1f91 100644 --- a/Wrapping/Python/SimpleITK.i +++ b/Wrapping/Python/SimpleITK.i @@ -1 +1,3 @@ %include SimpleITK_Common.i + +%include "sitkPyCommand.h" diff --git a/Wrapping/R/SimpleITK.i b/Wrapping/R/SimpleITK.i index 74635c2ab..b6688db3f 100644 --- a/Wrapping/R/SimpleITK.i +++ b/Wrapping/R/SimpleITK.i @@ -1 +1,3 @@ %include SimpleITK_Common.i + +%include "sitkRCommand.h" From 08da696113b118ff9086aa4d5ef3bc97acb5c078 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 13:24:43 -0400 Subject: [PATCH 282/412] Replacing Self return declarations with macro This enables this interface feature to be disabled when wrapping with SWIG. Change-Id: I49ab022024cf7145ad69e2ba2816092f8d65553a --- .../sitkBSplineTransformInitializerFilter.h | 4 +- .../include/sitkCastImageFilter.h | 4 +- .../sitkCenteredTransformInitializerFilter.h | 6 +- ...CenteredVersorTransformInitializerFilter.h | 6 +- .../include/sitkHashImageFilter.h | 2 +- ...kLandmarkBasedTransformInitializerFilter.h | 10 +-- .../sitkFastMarchingImageFilterTemplate.h.in | 6 +- .../sitkKernelImageFilterTemplate.h.in | 8 +- .../sitkRegionGrowingImageFilterTemplate.h.in | 8 +- Code/Common/include/sitkAffineTransform.h | 16 ++-- Code/Common/include/sitkBSplineTransform.h | 8 +- .../include/sitkDisplacementFieldTransform.h | 12 +-- Code/Common/include/sitkEuler2DTransform.h | 8 +- Code/Common/include/sitkEuler3DTransform.h | 14 ++-- Code/Common/include/sitkMacro.h | 4 + .../include/sitkScaleSkewVersor3DTransform.h | 14 ++-- Code/Common/include/sitkScaleTransform.h | 4 +- .../include/sitkScaleVersor3DTransform.h | 12 +-- .../include/sitkSimilarity2DTransform.h | 10 +-- .../include/sitkSimilarity3DTransform.h | 14 ++-- .../Common/include/sitkTranslationTransform.h | 2 +- .../include/sitkVersorRigid3DTransform.h | 12 +-- Code/Common/include/sitkVersorTransform.h | 8 +- Code/IO/include/sitkImageFileReader.h | 2 +- Code/IO/include/sitkImageFileWriter.h | 12 +-- Code/IO/include/sitkImageReaderBase.h | 2 +- Code/IO/include/sitkImageSeriesReader.h | 2 +- Code/IO/include/sitkImageSeriesWriter.h | 12 +-- Code/IO/include/sitkImportImageFilter.h | 28 +++---- .../include/sitkImageRegistrationMethod.h | 80 +++++++++---------- .../MemberGetSetDeclarations.h.in | 12 +-- 31 files changed, 173 insertions(+), 169 deletions(-) diff --git a/Code/BasicFilters/include/sitkBSplineTransformInitializerFilter.h b/Code/BasicFilters/include/sitkBSplineTransformInitializerFilter.h index 04d34898f..0fd70ca97 100644 --- a/Code/BasicFilters/include/sitkBSplineTransformInitializerFilter.h +++ b/Code/BasicFilters/include/sitkBSplineTransformInitializerFilter.h @@ -61,7 +61,7 @@ Nick Tustison /** * Allow the user to set the mesh size of the transform via the initializer even though the initializer does not do anything with that information. Defeault = 1^ImageDimension. */ - Self& SetTransformDomainMeshSize ( const std::vector & TransformDomainMeshSize ) { this->m_TransformDomainMeshSize = TransformDomainMeshSize; return *this; } + SITK_RETURN_SELF_TYPE_HEADER SetTransformDomainMeshSize ( const std::vector & TransformDomainMeshSize ) { this->m_TransformDomainMeshSize = TransformDomainMeshSize; return *this; } /** */ @@ -71,7 +71,7 @@ Nick Tustison * The order of the bspline in the output BSplineTransform. This * value effects the number of control points. */ - Self &SetOrder(unsigned int order) { this->m_Order = order; return *this; } + SITK_RETURN_SELF_TYPE_HEADER SetOrder(unsigned int order) { this->m_Order = order; return *this; } unsigned int GetOrder() const {return this->m_Order;} /** Name of this class */ diff --git a/Code/BasicFilters/include/sitkCastImageFilter.h b/Code/BasicFilters/include/sitkCastImageFilter.h index 2d3e0e225..c91d25991 100644 --- a/Code/BasicFilters/include/sitkCastImageFilter.h +++ b/Code/BasicFilters/include/sitkCastImageFilter.h @@ -45,8 +45,8 @@ class SITKBasicFilters_EXPORT CastImageFilter typedef CastImageFilter Self; /** Set/Get the output pixel type */ - Self& SetOutputPixelType( PixelIDValueEnum pixelID ); - Self& SetOutputPixelType( PixelIDValueType pixelID ); + SITK_RETURN_SELF_TYPE_HEADER SetOutputPixelType( PixelIDValueEnum pixelID ); + SITK_RETURN_SELF_TYPE_HEADER SetOutputPixelType( PixelIDValueType pixelID ); PixelIDValueEnum GetOutputPixelType( void ) const; /** diff --git a/Code/BasicFilters/include/sitkCenteredTransformInitializerFilter.h b/Code/BasicFilters/include/sitkCenteredTransformInitializerFilter.h index 7d8613a7c..dd071646d 100644 --- a/Code/BasicFilters/include/sitkCenteredTransformInitializerFilter.h +++ b/Code/BasicFilters/include/sitkCenteredTransformInitializerFilter.h @@ -71,7 +71,7 @@ In the second mode, the moments of gray level values are computed for both image /** */ - Self& SetOperationMode ( OperationModeType OperationMode ) { this->m_OperationMode = OperationMode; return *this; } + SITK_RETURN_SELF_TYPE_HEADER SetOperationMode ( OperationModeType OperationMode ) { this->m_OperationMode = OperationMode; return *this; } /** */ @@ -92,10 +92,10 @@ In the second mode, the moments of gray level values are computed for both image /** Select between using the geometrical center of the images or using the center of mass given by the image intensities. */ - Self& MomentsOn( ) { this->SetOperationMode( MOMENTS ); return *this; } + SITK_RETURN_SELF_TYPE_HEADER MomentsOn( ) { this->SetOperationMode( MOMENTS ); return *this; } /** Select between using the geometrical center of the images or using the center of mass given by the image intensities. */ - Self& GeometryOn( ) { this->SetOperationMode( GEOMETRY ); return *this; } + SITK_RETURN_SELF_TYPE_HEADER GeometryOn( ) { this->SetOperationMode( GEOMETRY ); return *this; } private: diff --git a/Code/BasicFilters/include/sitkCenteredVersorTransformInitializerFilter.h b/Code/BasicFilters/include/sitkCenteredVersorTransformInitializerFilter.h index ac93e8b64..03982338f 100644 --- a/Code/BasicFilters/include/sitkCenteredVersorTransformInitializerFilter.h +++ b/Code/BasicFilters/include/sitkCenteredVersorTransformInitializerFilter.h @@ -59,11 +59,11 @@ This class derived from the CenteredTransformInitializerand uses it in a more co /** * Enable the use of the principal axes of each image to compute an initial rotation that will align them. */ - Self& SetComputeRotation ( bool ComputeRotation ) { this->m_ComputeRotation = ComputeRotation; return *this; } + SITK_RETURN_SELF_TYPE_HEADER SetComputeRotation ( bool ComputeRotation ) { this->m_ComputeRotation = ComputeRotation; return *this; } /** Set the value of ComputeRotation to true or false respectfully. */ - Self& ComputeRotationOn() { return this->SetComputeRotation(true); } - Self& ComputeRotationOff() { return this->SetComputeRotation(false); } + SITK_RETURN_SELF_TYPE_HEADER ComputeRotationOn() { return this->SetComputeRotation(true); } + SITK_RETURN_SELF_TYPE_HEADER ComputeRotationOff() { return this->SetComputeRotation(false); } /** * Enable the use of the principal axes of each image to compute an initial rotation that will align them. diff --git a/Code/BasicFilters/include/sitkHashImageFilter.h b/Code/BasicFilters/include/sitkHashImageFilter.h index 3490aaaa3..71c4416c9 100644 --- a/Code/BasicFilters/include/sitkHashImageFilter.h +++ b/Code/BasicFilters/include/sitkHashImageFilter.h @@ -49,7 +49,7 @@ namespace itk { HashImageFilter(); enum HashFunction { SHA1, MD5 }; - Self& SetHashFunction ( HashFunction hashFunction ); + SITK_RETURN_SELF_TYPE_HEADER SetHashFunction ( HashFunction hashFunction ); HashFunction GetHashFunction () const; /** Name of this class */ diff --git a/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h b/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h index 62723214f..298d14a0d 100644 --- a/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h +++ b/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h @@ -76,7 +76,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co /** * Set the Fixed landmark point containers */ - Self& SetFixedLandmarks ( const std::vector & FixedLandmarks ) { this->m_FixedLandmarks = FixedLandmarks; return *this; } + SITK_RETURN_SELF_TYPE_HEADER SetFixedLandmarks ( const std::vector & FixedLandmarks ) { this->m_FixedLandmarks = FixedLandmarks; return *this; } /** * @@ -86,7 +86,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co /** * Set the Moving landmark point containers */ - Self& SetMovingLandmarks ( const std::vector & MovingLandmarks ) { this->m_MovingLandmarks = MovingLandmarks; return *this; } + SITK_RETURN_SELF_TYPE_HEADER SetMovingLandmarks ( const std::vector & MovingLandmarks ) { this->m_MovingLandmarks = MovingLandmarks; return *this; } /** * Get the shrink factors. @@ -96,7 +96,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co /** * Set the landmark weight point containers Weight includes diagonal elements of weight matrix */ - Self& SetLandmarkWeight ( const std::vector & LandmarkWeight ) { this->m_LandmarkWeight = LandmarkWeight; return *this; } + SITK_RETURN_SELF_TYPE_HEADER SetLandmarkWeight ( const std::vector & LandmarkWeight ) { this->m_LandmarkWeight = LandmarkWeight; return *this; } /** * @@ -106,7 +106,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co /** * Set the reference image to define the parametric domain for the BSpline transform */ - Self& SetReferenceImage ( const Image & ReferenceImage ) { this->m_ReferenceImage = ReferenceImage; return *this; } + SITK_RETURN_SELF_TYPE_HEADER SetReferenceImage ( const Image & ReferenceImage ) { this->m_ReferenceImage = ReferenceImage; return *this; } /** */ @@ -115,7 +115,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co /** * Set/Get the number of control points */ - Self& SetBSplineNumberOfControlPoints ( unsigned int BSplineNumberOfControlPoints ) { this->m_BSplineNumberOfControlPoints = BSplineNumberOfControlPoints; return *this; } + SITK_RETURN_SELF_TYPE_HEADER SetBSplineNumberOfControlPoints ( unsigned int BSplineNumberOfControlPoints ) { this->m_BSplineNumberOfControlPoints = BSplineNumberOfControlPoints; return *this; } /** * Set/Get the number of control points diff --git a/Code/BasicFilters/templates/sitkFastMarchingImageFilterTemplate.h.in b/Code/BasicFilters/templates/sitkFastMarchingImageFilterTemplate.h.in index bd49ac1a7..262a41198 100644 --- a/Code/BasicFilters/templates/sitkFastMarchingImageFilterTemplate.h.in +++ b/Code/BasicFilters/templates/sitkFastMarchingImageFilterTemplate.h.in @@ -32,19 +32,19 @@ $(include ClassDeclaration.h.in) $(include PublicDeclarations.h.in) $(include MemberGetSetDeclarations.h.in) /** Set trial points. The default trial value (i.e. 0.0) is used for each index. */ - Self& SetTrialPoints ( std::vector< std::vector > t ) + SITK_RETURN_SELF_TYPE_HEADER SetTrialPoints ( std::vector< std::vector > t ) { this->m_TrialPoints = t; return *this; } /** Add trial point */ - Self& AddTrialPoint( std::vector t ) + SITK_RETURN_SELF_TYPE_HEADER AddTrialPoint( std::vector t ) { this->m_TrialPoints.push_back( t ); return *this; } /** Clear trial points */ - Self& ClearTrialPoints( ) + SITK_RETURN_SELF_TYPE_HEADER ClearTrialPoints( ) { this->m_TrialPoints.clear(); return *this; } diff --git a/Code/BasicFilters/templates/sitkKernelImageFilterTemplate.h.in b/Code/BasicFilters/templates/sitkKernelImageFilterTemplate.h.in index 88f6747de..bb5d4f3c7 100644 --- a/Code/BasicFilters/templates/sitkKernelImageFilterTemplate.h.in +++ b/Code/BasicFilters/templates/sitkKernelImageFilterTemplate.h.in @@ -36,7 +36,7 @@ $(include ClassDeclaration.h.in) $(include PublicDeclarations.h.in) $(include MemberGetSetDeclarations.h.in) /** Kernel radius as a scale for isotropic structures */ - Self& SetKernelRadius(uint32_t r); + SITK_RETURN_SELF_TYPE_HEADER SetKernelRadius(uint32_t r); /** Set/Get the radius of the kernel structuring element as a * vector. @@ -45,14 +45,14 @@ $(include MemberGetSetDeclarations.h.in) * r, then the radius will be padded. If it is less the r will * be truncated. */ - Self& SetKernelRadius(const std::vector &r ); + SITK_RETURN_SELF_TYPE_HEADER SetKernelRadius(const std::vector &r ); std::vector GetKernelRadius() const; /** Set/Get the kernel or structuring elemenent used for the * morphology */ - Self& SetKernelType(KernelEnum t); + SITK_RETURN_SELF_TYPE_HEADER SetKernelType(KernelEnum t); #ifndef SWIG - Self& SetKernelType(KernelType t); + SITK_RETURN_SELF_TYPE_HEADER SetKernelType(KernelType t); #endif KernelEnum GetKernelType() const; diff --git a/Code/BasicFilters/templates/sitkRegionGrowingImageFilterTemplate.h.in b/Code/BasicFilters/templates/sitkRegionGrowingImageFilterTemplate.h.in index 926bcd539..d8a4db292 100644 --- a/Code/BasicFilters/templates/sitkRegionGrowingImageFilterTemplate.h.in +++ b/Code/BasicFilters/templates/sitkRegionGrowingImageFilterTemplate.h.in @@ -32,7 +32,7 @@ $(include ClassDeclaration.h.in) $(include PublicDeclarations.h.in) $(include MemberGetSetDeclarations.h.in) /** Set SeedList */ - Self& SetSeedList ( const std::vector< std::vector > &t ) + SITK_RETURN_SELF_TYPE_HEADER SetSeedList ( const std::vector< std::vector > &t ) { this->m_SeedList = t; return *this; } @@ -44,14 +44,14 @@ $(include MemberGetSetDeclarations.h.in) } /** ClearSeeds - Clear out all seeds in the list */ - Self& ClearSeeds( ) + SITK_RETURN_SELF_TYPE_HEADER ClearSeeds( ) { this->m_SeedList.clear(); return *this; } /** SetSeed - Set list to a single seed */ - Self& SetSeed( const std::vector &idx ) + SITK_RETURN_SELF_TYPE_HEADER SetSeed( const std::vector &idx ) { this->m_SeedList.clear(); this->m_SeedList.push_back(idx); @@ -59,7 +59,7 @@ $(include MemberGetSetDeclarations.h.in) } /** AddSeed - Add a seed to the end of the list */ - Self& AddSeed( const std::vector &idx ) + SITK_RETURN_SELF_TYPE_HEADER AddSeed( const std::vector &idx ) { this->m_SeedList.push_back(idx); return *this; diff --git a/Code/Common/include/sitkAffineTransform.h b/Code/Common/include/sitkAffineTransform.h index bc4ce9130..13b0c8d40 100644 --- a/Code/Common/include/sitkAffineTransform.h +++ b/Code/Common/include/sitkAffineTransform.h @@ -55,24 +55,24 @@ class SITKCommon_EXPORT AffineTransform /** parameters */ std::vector GetTranslation( ) const; - Self &SetTranslation( const std::vector& translation); + SITK_RETURN_SELF_TYPE_HEADER SetTranslation( const std::vector& translation); - Self &SetMatrix( const std::vector &matrix); + SITK_RETURN_SELF_TYPE_HEADER SetMatrix( const std::vector &matrix); std::vector GetMatrix() const; /** fixed parameter */ - Self &SetCenter(const std::vector ¶ms); + SITK_RETURN_SELF_TYPE_HEADER SetCenter(const std::vector ¶ms); std::vector GetCenter( ) const; /** additional methods */ - Self &Scale(const std::vector & factor, bool pre=false); - Self &Scale(double factor, bool pre=false); + SITK_RETURN_SELF_TYPE_HEADER Scale(const std::vector & factor, bool pre=false); + SITK_RETURN_SELF_TYPE_HEADER Scale(double factor, bool pre=false); - Self &Shear(int axis1, int axis2, double coef, bool pre=false); + SITK_RETURN_SELF_TYPE_HEADER Shear(int axis1, int axis2, double coef, bool pre=false); - Self &Translate(const std::vector &offset, bool pre=false); + SITK_RETURN_SELF_TYPE_HEADER Translate(const std::vector &offset, bool pre=false); - Self &Rotate(int axis1, int axis2, double angle, bool pre=false); + SITK_RETURN_SELF_TYPE_HEADER Rotate(int axis1, int axis2, double angle, bool pre=false); protected: diff --git a/Code/Common/include/sitkBSplineTransform.h b/Code/Common/include/sitkBSplineTransform.h index 0920f2c57..85b321493 100644 --- a/Code/Common/include/sitkBSplineTransform.h +++ b/Code/Common/include/sitkBSplineTransform.h @@ -52,13 +52,13 @@ class SITKCommon_EXPORT BSplineTransform /** parameters */ /** fixed parameter */ - Self &SetTransformDomainDirection(const std::vector &); + SITK_RETURN_SELF_TYPE_HEADER SetTransformDomainDirection(const std::vector &); std::vector GetTransformDomainDirection() const; - Self &SetTransformDomainMeshSize(const std::vector&); + SITK_RETURN_SELF_TYPE_HEADER SetTransformDomainMeshSize(const std::vector&); std::vector GetTransformDomainMeshSize() const; - Self &SetTransformDomainOrigin(const std::vector&); + SITK_RETURN_SELF_TYPE_HEADER SetTransformDomainOrigin(const std::vector&); std::vector GetTransformDomainOrigin() const; - Self &SetTransformDomainPhysicalDimensions(const std::vector &); + SITK_RETURN_SELF_TYPE_HEADER SetTransformDomainPhysicalDimensions(const std::vector &); std::vector GetTransformDomainPhysicalDimensions() const; /* additional methods */ diff --git a/Code/Common/include/sitkDisplacementFieldTransform.h b/Code/Common/include/sitkDisplacementFieldTransform.h index 93d2ec54b..5476e9164 100644 --- a/Code/Common/include/sitkDisplacementFieldTransform.h +++ b/Code/Common/include/sitkDisplacementFieldTransform.h @@ -74,7 +74,7 @@ class SITKCommon_EXPORT DisplacementFieldTransform * components equal to the image dimension. * */ - Self &SetDisplacementField(Image &); + SITK_RETURN_SELF_TYPE_HEADER SetDisplacementField(Image &); /** \todo The returned image should not directly modify the * internal displacement field. @@ -84,19 +84,19 @@ class SITKCommon_EXPORT DisplacementFieldTransform /** fixed parameter */ /* additional methods */ - Self &SetInverseDisplacementField(Image &); + SITK_RETURN_SELF_TYPE_HEADER SetInverseDisplacementField(Image &); /** \todo The returned image is should not directly modify the * internal displacement field. */ Image GetInverseDisplacementField() const; - Self &SetInterpolator(InterpolatorEnum interp); + SITK_RETURN_SELF_TYPE_HEADER SetInterpolator(InterpolatorEnum interp); // InterpolatorEnum GetInterpolator() const; How to do this? - Self &SetSmoothingOff(); - Self &SetSmoothingGaussianOnUpdate( double varianceForUpdateField=1.75, double varianceForTotalField=0.5 ); - Self &SetSmoothingBSplineOnUpdate( const std::vector &numberOfControlPointsForUpdateField = std::vector(3,4), + SITK_RETURN_SELF_TYPE_HEADER SetSmoothingOff(); + SITK_RETURN_SELF_TYPE_HEADER SetSmoothingGaussianOnUpdate( double varianceForUpdateField=1.75, double varianceForTotalField=0.5 ); + SITK_RETURN_SELF_TYPE_HEADER SetSmoothingBSplineOnUpdate( const std::vector &numberOfControlPointsForUpdateField = std::vector(3,4), const std::vector &numberOfControlPointsForTotalField = std::vector(3,4), bool enforceStationaryBoundary=true, unsigned int order=3 ); diff --git a/Code/Common/include/sitkEuler2DTransform.h b/Code/Common/include/sitkEuler2DTransform.h index 9b5636683..fe4ce90de 100644 --- a/Code/Common/include/sitkEuler2DTransform.h +++ b/Code/Common/include/sitkEuler2DTransform.h @@ -55,19 +55,19 @@ class SITKCommon_EXPORT Euler2DTransform std::string GetName() const { return std::string ("Euler2DTransform"); } /** fixed parameter */ - Self &SetCenter(const std::vector ¶ms); + SITK_RETURN_SELF_TYPE_HEADER SetCenter(const std::vector ¶ms); std::vector GetCenter( ) const; /** parameter */ - Self &SetAngle (double angle); + SITK_RETURN_SELF_TYPE_HEADER SetAngle (double angle); double GetAngle () const; std::vector GetTranslation( ) const; - Self &SetTranslation(const std::vector& translation); + SITK_RETURN_SELF_TYPE_HEADER SetTranslation(const std::vector& translation); /** additional methods */ std::vector GetMatrix() const; - Self &SetMatrix(const std::vector &matrix, double tolerance = 1e-10); + SITK_RETURN_SELF_TYPE_HEADER SetMatrix(const std::vector &matrix, double tolerance = 1e-10); protected: diff --git a/Code/Common/include/sitkEuler3DTransform.h b/Code/Common/include/sitkEuler3DTransform.h index 64030911c..ed8a7f295 100644 --- a/Code/Common/include/sitkEuler3DTransform.h +++ b/Code/Common/include/sitkEuler3DTransform.h @@ -57,7 +57,7 @@ Euler3DTransform &operator=( const Euler3DTransform & ); std::string GetName() const { return std::string ("Euler3DTransform"); } /** fixed parameter */ -Self &SetCenter(const std::vector ¶ms); +SITK_RETURN_SELF_TYPE_HEADER SetCenter(const std::vector ¶ms); std::vector GetCenter( ) const; double GetAngleX () const; @@ -65,20 +65,20 @@ double GetAngleY () const; double GetAngleZ () const; /** parameter */ -Self &SetRotation (double angleX, double angleY, double angleZ); +SITK_RETURN_SELF_TYPE_HEADER SetRotation (double angleX, double angleY, double angleZ); std::vector GetTranslation( ) const; -Self &SetTranslation( const std::vector& translation); +SITK_RETURN_SELF_TYPE_HEADER SetTranslation( const std::vector& translation); -Self &SetComputeZYX (bool _arg); +SITK_RETURN_SELF_TYPE_HEADER SetComputeZYX (bool _arg); bool GetComputeZYX () const; -Self &ComputeZYXOn () {return this->SetComputeZYX(true);} -Self &ComputeZYXOff () {return this->SetComputeZYX(false);} +SITK_RETURN_SELF_TYPE_HEADER ComputeZYXOn () {return this->SetComputeZYX(true);} +SITK_RETURN_SELF_TYPE_HEADER ComputeZYXOff () {return this->SetComputeZYX(false);} /** additional methods */ std::vector GetMatrix() const; - Self &SetMatrix(const std::vector &matrix, double tolerance = 1e-10); + SITK_RETURN_SELF_TYPE_HEADER SetMatrix(const std::vector &matrix, double tolerance = 1e-10); protected: diff --git a/Code/Common/include/sitkMacro.h b/Code/Common/include/sitkMacro.h index 7318bda36..500bba04b 100644 --- a/Code/Common/include/sitkMacro.h +++ b/Code/Common/include/sitkMacro.h @@ -69,6 +69,10 @@ #endif +#if !defined(SITK_RETURN_SELF_TYPE_HEADER) +#define SITK_RETURN_SELF_TYPE_HEADER Self & +#endif + namespace itk { namespace simple { diff --git a/Code/Common/include/sitkScaleSkewVersor3DTransform.h b/Code/Common/include/sitkScaleSkewVersor3DTransform.h index c60c3c098..96663d775 100644 --- a/Code/Common/include/sitkScaleSkewVersor3DTransform.h +++ b/Code/Common/include/sitkScaleSkewVersor3DTransform.h @@ -64,26 +64,26 @@ class SITKCommon_EXPORT ScaleSkewVersor3DTransform std::string GetName() const { return std::string ("ScaleSkewVersor3DTransform"); } /** fixed parameter */ - Self &SetCenter(const std::vector ¶ms); + SITK_RETURN_SELF_TYPE_HEADER SetCenter(const std::vector ¶ms); std::vector GetCenter( ) const; /** parameter */ - Self &SetRotation(const std::vector &versor); - Self &SetRotation(const std::vector &axis, double angle); + SITK_RETURN_SELF_TYPE_HEADER SetRotation(const std::vector &versor); + SITK_RETURN_SELF_TYPE_HEADER SetRotation(const std::vector &axis, double angle); std::vector GetVersor() const; std::vector GetTranslation( ) const; - Self &SetTranslation(const std::vector& translation); + SITK_RETURN_SELF_TYPE_HEADER SetTranslation(const std::vector& translation); std::vector GetScale( ) const; - Self &SetScale( const std::vector & scale ); + SITK_RETURN_SELF_TYPE_HEADER SetScale( const std::vector & scale ); std::vector GetSkew( ) const; - Self &SetSkew( const std::vector & skew ); + SITK_RETURN_SELF_TYPE_HEADER SetSkew( const std::vector & skew ); /** additional methods */ - Self &Translate(const std::vector &offset); + SITK_RETURN_SELF_TYPE_HEADER Translate(const std::vector &offset); std::vector GetMatrix() const; protected: diff --git a/Code/Common/include/sitkScaleTransform.h b/Code/Common/include/sitkScaleTransform.h index 8a2c554e3..e9bdbdf3f 100644 --- a/Code/Common/include/sitkScaleTransform.h +++ b/Code/Common/include/sitkScaleTransform.h @@ -51,11 +51,11 @@ class SITKCommon_EXPORT ScaleTransform ScaleTransform &operator=( const ScaleTransform & ); - Self &SetScale(const std::vector ¶ms); + SITK_RETURN_SELF_TYPE_HEADER SetScale(const std::vector ¶ms); std::vector GetScale( ) const; /** fixed parameter */ - Self &SetCenter(const std::vector ¶ms); + SITK_RETURN_SELF_TYPE_HEADER SetCenter(const std::vector ¶ms); std::vector GetCenter( ) const; /** additional methods */ diff --git a/Code/Common/include/sitkScaleVersor3DTransform.h b/Code/Common/include/sitkScaleVersor3DTransform.h index e8fa7cb9a..27b8ec02e 100644 --- a/Code/Common/include/sitkScaleVersor3DTransform.h +++ b/Code/Common/include/sitkScaleVersor3DTransform.h @@ -63,23 +63,23 @@ class SITKCommon_EXPORT ScaleVersor3DTransform std::string GetName() const { return std::string ("ScaleVersor3DTransform"); } /** fixed parameter */ - Self &SetCenter(const std::vector ¶ms); + SITK_RETURN_SELF_TYPE_HEADER SetCenter(const std::vector ¶ms); std::vector GetCenter( ) const; /** parameter */ - Self &SetRotation(const std::vector &versor); - Self &SetRotation(const std::vector &axis, double angle); + SITK_RETURN_SELF_TYPE_HEADER SetRotation(const std::vector &versor); + SITK_RETURN_SELF_TYPE_HEADER SetRotation(const std::vector &axis, double angle); std::vector GetVersor() const; std::vector GetTranslation( ) const; - Self &SetTranslation(const std::vector& translation); + SITK_RETURN_SELF_TYPE_HEADER SetTranslation(const std::vector& translation); std::vector GetScale( ) const; - Self &SetScale( const std::vector & scale ); + SITK_RETURN_SELF_TYPE_HEADER SetScale( const std::vector & scale ); /** additional methods */ - Self &Translate(const std::vector &offset); + SITK_RETURN_SELF_TYPE_HEADER Translate(const std::vector &offset); std::vector GetMatrix() const; protected: diff --git a/Code/Common/include/sitkSimilarity2DTransform.h b/Code/Common/include/sitkSimilarity2DTransform.h index 03b5229ab..0c398edfd 100644 --- a/Code/Common/include/sitkSimilarity2DTransform.h +++ b/Code/Common/include/sitkSimilarity2DTransform.h @@ -56,22 +56,22 @@ class SITKCommon_EXPORT Similarity2DTransform std::string GetName() const { return std::string ("Similarity2DTransform"); } /** fixed parameter */ - Self &SetCenter(const std::vector ¶ms); + SITK_RETURN_SELF_TYPE_HEADER SetCenter(const std::vector ¶ms); std::vector GetCenter( ) const; /** parameter */ - Self &SetAngle (double angle); + SITK_RETURN_SELF_TYPE_HEADER SetAngle (double angle); double GetAngle () const; std::vector GetTranslation( ) const; - Self &SetTranslation(const std::vector& translation); + SITK_RETURN_SELF_TYPE_HEADER SetTranslation(const std::vector& translation); - Self &SetScale(double scale); + SITK_RETURN_SELF_TYPE_HEADER SetScale(double scale); double GetScale() const; /** additional methods */ std::vector GetMatrix() const; - Self &SetMatrix(const std::vector &matrix, double tolerance = 1e-10); + SITK_RETURN_SELF_TYPE_HEADER SetMatrix(const std::vector &matrix, double tolerance = 1e-10); protected: diff --git a/Code/Common/include/sitkSimilarity3DTransform.h b/Code/Common/include/sitkSimilarity3DTransform.h index 90e765f31..dac13dba8 100644 --- a/Code/Common/include/sitkSimilarity3DTransform.h +++ b/Code/Common/include/sitkSimilarity3DTransform.h @@ -59,26 +59,26 @@ Similarity3DTransform &operator=( const Similarity3DTransform & ); std::string GetName() const { return std::string ("Similarity3DTransform"); } /** fixed parameter */ -Self &SetCenter(const std::vector ¶ms); +SITK_RETURN_SELF_TYPE_HEADER SetCenter(const std::vector ¶ms); std::vector GetCenter( ) const; /** parameter */ -Self &SetRotation(const std::vector &versor); -Self &SetRotation(const std::vector &axis, double angle); +SITK_RETURN_SELF_TYPE_HEADER SetRotation(const std::vector &versor); +SITK_RETURN_SELF_TYPE_HEADER SetRotation(const std::vector &axis, double angle); std::vector GetVersor() const; -Self &SetScale(double scale); +SITK_RETURN_SELF_TYPE_HEADER SetScale(double scale); double GetScale() const; std::vector GetTranslation( ) const; -Self &SetTranslation(const std::vector& translation); +SITK_RETURN_SELF_TYPE_HEADER SetTranslation(const std::vector& translation); /** additional methods */ -Self &Translate(const std::vector &offset); +SITK_RETURN_SELF_TYPE_HEADER Translate(const std::vector &offset); std::vector GetMatrix() const; -Self &SetMatrix(const std::vector &matrix, double tolerance = 1e-10); +SITK_RETURN_SELF_TYPE_HEADER SetMatrix(const std::vector &matrix, double tolerance = 1e-10); protected: diff --git a/Code/Common/include/sitkTranslationTransform.h b/Code/Common/include/sitkTranslationTransform.h index ad44267f1..9c117681a 100644 --- a/Code/Common/include/sitkTranslationTransform.h +++ b/Code/Common/include/sitkTranslationTransform.h @@ -47,7 +47,7 @@ TranslationTransform( const Transform & ); TranslationTransform &operator=( const TranslationTransform & ); -Self &SetOffset(const std::vector ¶ms); +SITK_RETURN_SELF_TYPE_HEADER SetOffset(const std::vector ¶ms); std::vector GetOffset( ) const; protected: diff --git a/Code/Common/include/sitkVersorRigid3DTransform.h b/Code/Common/include/sitkVersorRigid3DTransform.h index 07effd1ad..62637bf9f 100644 --- a/Code/Common/include/sitkVersorRigid3DTransform.h +++ b/Code/Common/include/sitkVersorRigid3DTransform.h @@ -57,22 +57,22 @@ class SITKCommon_EXPORT VersorRigid3DTransform VersorRigid3DTransform &operator=( const VersorRigid3DTransform & ); /** fixed parameter */ - Self &SetCenter(const std::vector ¶ms); + SITK_RETURN_SELF_TYPE_HEADER SetCenter(const std::vector ¶ms); std::vector GetCenter( ) const; /** parameter */ - Self &SetRotation(const std::vector &versor); - Self &SetRotation(const std::vector &axis, double angle); + SITK_RETURN_SELF_TYPE_HEADER SetRotation(const std::vector &versor); + SITK_RETURN_SELF_TYPE_HEADER SetRotation(const std::vector &axis, double angle); std::vector GetVersor() const; std::vector GetTranslation( ) const; - Self &SetTranslation(const std::vector& translation); + SITK_RETURN_SELF_TYPE_HEADER SetTranslation(const std::vector& translation); /** additional methods */ - Self &Translate(const std::vector &offset); + SITK_RETURN_SELF_TYPE_HEADER Translate(const std::vector &offset); std::vector GetMatrix() const; - Self &SetMatrix(const std::vector &matrix, double tolerance = 1e-10); + SITK_RETURN_SELF_TYPE_HEADER SetMatrix(const std::vector &matrix, double tolerance = 1e-10); protected: diff --git a/Code/Common/include/sitkVersorTransform.h b/Code/Common/include/sitkVersorTransform.h index 7482b7d2c..4ff07d8ea 100644 --- a/Code/Common/include/sitkVersorTransform.h +++ b/Code/Common/include/sitkVersorTransform.h @@ -57,18 +57,18 @@ class SITKCommon_EXPORT VersorTransform VersorTransform &operator=( const VersorTransform & ); /** fixed parameter */ - Self &SetCenter(const std::vector ¶ms); + SITK_RETURN_SELF_TYPE_HEADER SetCenter(const std::vector ¶ms); std::vector GetCenter( ) const; /** parameter */ - Self &SetRotation(const std::vector &versor); - Self &SetRotation(const std::vector &axis, double angle); + SITK_RETURN_SELF_TYPE_HEADER SetRotation(const std::vector &versor); + SITK_RETURN_SELF_TYPE_HEADER SetRotation(const std::vector &axis, double angle); std::vector GetVersor() const; /** additional methods */ std::vector GetMatrix() const; - Self &SetMatrix(const std::vector &matrix, double tolerance = 1e-10); + SITK_RETURN_SELF_TYPE_HEADER SetMatrix(const std::vector &matrix, double tolerance = 1e-10); protected: diff --git a/Code/IO/include/sitkImageFileReader.h b/Code/IO/include/sitkImageFileReader.h index 07a1ad9d9..5664542fb 100644 --- a/Code/IO/include/sitkImageFileReader.h +++ b/Code/IO/include/sitkImageFileReader.h @@ -47,7 +47,7 @@ namespace itk { /** return user readable name fo the filter */ virtual std::string GetName() const { return std::string("ImageFileReader"); } - Self& SetFileName ( std::string fn ); + SITK_RETURN_SELF_TYPE_HEADER SetFileName ( std::string fn ); std::string GetFileName() const; Image Execute(); diff --git a/Code/IO/include/sitkImageFileWriter.h b/Code/IO/include/sitkImageFileWriter.h index 0553cb63a..44a6379c4 100644 --- a/Code/IO/include/sitkImageFileWriter.h +++ b/Code/IO/include/sitkImageFileWriter.h @@ -61,18 +61,18 @@ namespace itk { * get's passed to image file's itk::ImageIO object. This is * only a request as not all file formatts support compression. * @{ */ - Self& SetUseCompression( bool UseCompression ); + SITK_RETURN_SELF_TYPE_HEADER SetUseCompression( bool UseCompression ); bool GetUseCompression( void ) const; - Self & UseCompressionOn( void ) { return this->SetUseCompression(true); } - Self & UseCompressionOff( void ) { return this->SetUseCompression(false); } + SITK_RETURN_SELF_TYPE_HEADER UseCompressionOn( void ) { return this->SetUseCompression(true); } + SITK_RETURN_SELF_TYPE_HEADER UseCompressionOff( void ) { return this->SetUseCompression(false); } /** @} */ - Self& SetFileName ( std::string fileName ); + SITK_RETURN_SELF_TYPE_HEADER SetFileName ( std::string fileName ); std::string GetFileName() const; - Self& Execute ( const Image& ); - Self& Execute ( const Image& , const std::string &inFileName, bool inUseCompression ); + SITK_RETURN_SELF_TYPE_HEADER Execute ( const Image& ); + SITK_RETURN_SELF_TYPE_HEADER Execute ( const Image& , const std::string &inFileName, bool inUseCompression ); private: diff --git a/Code/IO/include/sitkImageReaderBase.h b/Code/IO/include/sitkImageReaderBase.h index 9f887c790..7b6d41c90 100644 --- a/Code/IO/include/sitkImageReaderBase.h +++ b/Code/IO/include/sitkImageReaderBase.h @@ -53,7 +53,7 @@ class SmartPointer; * convert the pixels. * @{ */ - Self& SetOutputPixelType( PixelIDValueEnum pixelID ); + SITK_RETURN_SELF_TYPE_HEADER SetOutputPixelType( PixelIDValueEnum pixelID ); PixelIDValueEnum GetOutputPixelType( void ) const; /* @} */ diff --git a/Code/IO/include/sitkImageSeriesReader.h b/Code/IO/include/sitkImageSeriesReader.h index b98d28ecd..63a9f6f82 100644 --- a/Code/IO/include/sitkImageSeriesReader.h +++ b/Code/IO/include/sitkImageSeriesReader.h @@ -102,7 +102,7 @@ namespace itk { **/ static std::vector GetGDCMSeriesIDs( const std::string &directory ); - Self& SetFileNames ( const std::vector &fileNames ); + SITK_RETURN_SELF_TYPE_HEADER SetFileNames ( const std::vector &fileNames ); const std::vector &GetFileNames() const; Image Execute(); diff --git a/Code/IO/include/sitkImageSeriesWriter.h b/Code/IO/include/sitkImageSeriesWriter.h index ab8b50329..9dacd07d4 100644 --- a/Code/IO/include/sitkImageSeriesWriter.h +++ b/Code/IO/include/sitkImageSeriesWriter.h @@ -53,11 +53,11 @@ namespace itk { * get's passed to image file's itk::ImageIO object. This is * only a request as not all file formatts support compression. * @{ */ - Self& SetUseCompression( bool UseCompression ); + SITK_RETURN_SELF_TYPE_HEADER SetUseCompression( bool UseCompression ); bool GetUseCompression( void ) const; - Self & UseCompressionOn( void ) { return this->SetUseCompression(true); } - Self & UseCompressionOff( void ) { return this->SetUseCompression(false); } + SITK_RETURN_SELF_TYPE_HEADER UseCompressionOn( void ) { return this->SetUseCompression(true); } + SITK_RETURN_SELF_TYPE_HEADER UseCompressionOff( void ) { return this->SetUseCompression(false); } /** @} */ /** The filenames to where the image slices are written. @@ -65,13 +65,13 @@ namespace itk { * The number of filenames must match the number of slices in * the image. * @{ */ - Self & SetFileNames ( const std::vector &fileNames ); + SITK_RETURN_SELF_TYPE_HEADER SetFileNames ( const std::vector &fileNames ); const std::vector &GetFileNames() const; /** @} */ - Self & Execute( const Image& ); - Self & Execute( const Image &image, const std::vector &inFileNames, bool inUseCompression ); + SITK_RETURN_SELF_TYPE_HEADER Execute( const Image& ); + SITK_RETURN_SELF_TYPE_HEADER Execute( const Image &image, const std::vector &inFileNames, bool inUseCompression ); protected: diff --git a/Code/IO/include/sitkImportImageFilter.h b/Code/IO/include/sitkImportImageFilter.h index 7379ca171..53f57abf7 100644 --- a/Code/IO/include/sitkImportImageFilter.h +++ b/Code/IO/include/sitkImportImageFilter.h @@ -57,28 +57,28 @@ namespace itk { /** return user readable name fo the filter */ virtual std::string GetName() const { return std::string("ImportImageFilter"); } - Self& SetSize( const std::vector< unsigned int > &size ); + SITK_RETURN_SELF_TYPE_HEADER SetSize( const std::vector< unsigned int > &size ); const std::vector< unsigned int > &GetSize( ) const; - Self& SetSpacing( const std::vector< double > &spacing ); + SITK_RETURN_SELF_TYPE_HEADER SetSpacing( const std::vector< double > &spacing ); const std::vector< double > &GetSpacing( ) const; - Self& SetOrigin( const std::vector< double > &origin ); + SITK_RETURN_SELF_TYPE_HEADER SetOrigin( const std::vector< double > &origin ); const std::vector< double > &GetOrigin( ) const; - Self& SetDirection( const std::vector< double > &direction ); + SITK_RETURN_SELF_TYPE_HEADER SetDirection( const std::vector< double > &direction ); const std::vector< double > &GetDirection( ) const; - Self& SetBufferAsInt8( int8_t * buffer, unsigned int numberOfComponents = 1 ); - Self& SetBufferAsUInt8( uint8_t * buffer, unsigned int numberOfComponents = 1 ); - Self& SetBufferAsInt16( int16_t * buffer, unsigned int numberOfComponents = 1 ); - Self& SetBufferAsUInt16( uint16_t * buffer, unsigned int numberOfComponents = 1 ); - Self& SetBufferAsInt32( int32_t * buffer, unsigned int numberOfComponents = 1 ); - Self& SetBufferAsUInt32( uint32_t * buffer, unsigned int numberOfComponents = 1 ); - Self& SetBufferAsInt64( int64_t * buffer, unsigned int numberOfComponents = 1 ); - Self& SetBufferAsUInt64( uint64_t * buffer, unsigned int numberOfComponents = 1 ); - Self& SetBufferAsFloat( float * buffer, unsigned int numberOfComponents = 1 ); - Self& SetBufferAsDouble( double * buffer, unsigned int numberOfComponents = 1 ); + SITK_RETURN_SELF_TYPE_HEADER SetBufferAsInt8( int8_t * buffer, unsigned int numberOfComponents = 1 ); + SITK_RETURN_SELF_TYPE_HEADER SetBufferAsUInt8( uint8_t * buffer, unsigned int numberOfComponents = 1 ); + SITK_RETURN_SELF_TYPE_HEADER SetBufferAsInt16( int16_t * buffer, unsigned int numberOfComponents = 1 ); + SITK_RETURN_SELF_TYPE_HEADER SetBufferAsUInt16( uint16_t * buffer, unsigned int numberOfComponents = 1 ); + SITK_RETURN_SELF_TYPE_HEADER SetBufferAsInt32( int32_t * buffer, unsigned int numberOfComponents = 1 ); + SITK_RETURN_SELF_TYPE_HEADER SetBufferAsUInt32( uint32_t * buffer, unsigned int numberOfComponents = 1 ); + SITK_RETURN_SELF_TYPE_HEADER SetBufferAsInt64( int64_t * buffer, unsigned int numberOfComponents = 1 ); + SITK_RETURN_SELF_TYPE_HEADER SetBufferAsUInt64( uint64_t * buffer, unsigned int numberOfComponents = 1 ); + SITK_RETURN_SELF_TYPE_HEADER SetBufferAsFloat( float * buffer, unsigned int numberOfComponents = 1 ); + SITK_RETURN_SELF_TYPE_HEADER SetBufferAsDouble( double * buffer, unsigned int numberOfComponents = 1 ); Image Execute(); diff --git a/Code/Registration/include/sitkImageRegistrationMethod.h b/Code/Registration/include/sitkImageRegistrationMethod.h index 0a308e37b..19807883b 100644 --- a/Code/Registration/include/sitkImageRegistrationMethod.h +++ b/Code/Registration/include/sitkImageRegistrationMethod.h @@ -111,7 +111,7 @@ namespace simple */ InterpolatorEnum GetInterpolator() { return this->m_Interpolator; } - Self& SetInterpolator ( InterpolatorEnum Interpolator ) + SITK_RETURN_SELF_TYPE_HEADER SetInterpolator ( InterpolatorEnum Interpolator ) { this->m_Interpolator = Interpolator; return *this; } /** @} */ @@ -133,9 +133,9 @@ namespace simple */ #if !defined(SWIG) || defined(JAVASWIG) || defined(CSHARPSWIG) // Only wrap this method if the wrapping language is strongly typed - Self& SetInitialTransform ( const Transform &transform ); + SITK_RETURN_SELF_TYPE_HEADER SetInitialTransform ( const Transform &transform ); #endif - Self& SetInitialTransform ( Transform &transform, bool inPlace=true ); + SITK_RETURN_SELF_TYPE_HEADER SetInitialTransform ( Transform &transform, bool inPlace=true ); Transform GetInitialTransform() { return this->m_InitialTransform; } bool GetInitialTransformInPlace() const @@ -155,7 +155,7 @@ namespace simple * \sa itk::ImageRegistrationMethodv4::SetMovingInitialTransform * @{ */ - Self& SetMovingInitialTransform( const Transform &transform ) + SITK_RETURN_SELF_TYPE_HEADER SetMovingInitialTransform( const Transform &transform ) { this->m_MovingInitialTransform = transform; return *this; } Transform GetMovingInitialTransform( ) const { return this->m_MovingInitialTransform; } @@ -171,7 +171,7 @@ namespace simple * \sa itk::ImageRegistrationMethodv4::SetFixedInitialTransform * @{ */ - Self& SetFixedInitialTransform( const Transform &transform ) + SITK_RETURN_SELF_TYPE_HEADER SetFixedInitialTransform( const Transform &transform ) { this->m_FixedInitialTransform = transform; return *this; } Transform GetFixedInitialTransform( ) const { return this->m_FixedInitialTransform; } @@ -183,39 +183,39 @@ namespace simple * * \sa itk::ANTSNeighborhoodCorrelationImageToImageMetricv4 */ - Self& SetMetricAsANTSNeighborhoodCorrelation( unsigned int radius ); + SITK_RETURN_SELF_TYPE_HEADER SetMetricAsANTSNeighborhoodCorrelation( unsigned int radius ); /** \brief Use negative normalized cross correlation image metric. * * \sa itk::CorrelationImageToImageMetricv4 */ - Self& SetMetricAsCorrelation( ); + SITK_RETURN_SELF_TYPE_HEADER SetMetricAsCorrelation( ); /** \brief Use demons image metric. * * \sa itk::DemonsImageToImageMetricv4 */ - Self& SetMetricAsDemons( double intensityDifferenceThreshold = 0.001 ); + SITK_RETURN_SELF_TYPE_HEADER SetMetricAsDemons( double intensityDifferenceThreshold = 0.001 ); /** \brief Use mutual information between two images. * * \sa itk::JointHistogramMutualInformationImageToImageMetricv4 */ - Self& SetMetricAsJointHistogramMutualInformation( unsigned int numberOfHistogramBins = 20, + SITK_RETURN_SELF_TYPE_HEADER SetMetricAsJointHistogramMutualInformation( unsigned int numberOfHistogramBins = 20, double varianceForJointPDFSmoothing = 1.5); /** \brief Use negative means squares image metric. * * \sa itk::MeanSquaresImageToImageMetricv4 */ - Self& SetMetricAsMeanSquares( ); + SITK_RETURN_SELF_TYPE_HEADER SetMetricAsMeanSquares( ); /** \brief Use the mutual information between two images to be * registered using the method of Mattes et al. * * \sa itk::MattesMutualInformationImageToImageMetricv4 */ - Self& SetMetricAsMattesMutualInformation( unsigned int numberOfHistogramBins = 50 ); + SITK_RETURN_SELF_TYPE_HEADER SetMetricAsMattesMutualInformation( unsigned int numberOfHistogramBins = 50 ); enum EstimateLearningRateType { Never, Once, EachIteration }; @@ -224,7 +224,7 @@ namespace simple * * \sa itk::ConjugateGradientLineSearchOptimizerv4Template */ - Self& SetOptimizerAsConjugateGradientLineSearch( double learningRate, + SITK_RETURN_SELF_TYPE_HEADER SetOptimizerAsConjugateGradientLineSearch( double learningRate, unsigned int numberOfIterations, double convergenceMinimumValue = 1e-6, unsigned int convergenceWindowSize = 10, @@ -239,7 +239,7 @@ namespace simple * * \sa itk::RegularStepGradientDescentOptimizerv4 */ - Self& SetOptimizerAsRegularStepGradientDescent( double learningRate, + SITK_RETURN_SELF_TYPE_HEADER SetOptimizerAsRegularStepGradientDescent( double learningRate, double minStep, unsigned int numberOfIterations, double relaxationFactor=0.5, @@ -251,7 +251,7 @@ namespace simple * * \sa itk::GradientDescentOptimizerv4Template */ - Self& SetOptimizerAsGradientDescent( double learningRate, + SITK_RETURN_SELF_TYPE_HEADER SetOptimizerAsGradientDescent( double learningRate, unsigned int numberOfIterations, double convergenceMinimumValue = 1e-6, unsigned int convergenceWindowSize = 10, @@ -262,7 +262,7 @@ namespace simple * * \sa itk::GradientDescentLineSearchOptimizerv4Template */ - Self& SetOptimizerAsGradientDescentLineSearch( double learningRate, + SITK_RETURN_SELF_TYPE_HEADER SetOptimizerAsGradientDescentLineSearch( double learningRate, unsigned int numberOfIterations, double convergenceMinimumValue = 1e-6, unsigned int convergenceWindowSize = 10, @@ -279,7 +279,7 @@ namespace simple * * \sa itk::LBFGSBOptimizerv4 */ - Self& SetOptimizerAsLBFGSB(double gradientConvergenceTolerance = 1e-5, + SITK_RETURN_SELF_TYPE_HEADER SetOptimizerAsLBFGSB(double gradientConvergenceTolerance = 1e-5, unsigned int numberOfIterations = 500, unsigned int maximumNumberOfCorrections = 5, unsigned int maximumNumberOfFunctionEvaluations = 2000, @@ -304,14 +304,14 @@ namespace simple * * \sa itk::ExhaustiveOptimizerv4 */ - Self& SetOptimizerAsExhaustive( const std::vector &numberOfSteps, + SITK_RETURN_SELF_TYPE_HEADER SetOptimizerAsExhaustive( const std::vector &numberOfSteps, double stepLength = 1.0 ); /** \brief Set optimizer to Nelder-Mead downhill simplex algorithm. * * \sa itk::AmoebaOptimizerv4 */ - Self& SetOptimizerAsAmoeba(double simplexDelta, + SITK_RETURN_SELF_TYPE_HEADER SetOptimizerAsAmoeba(double simplexDelta, unsigned int numberOfIterations, double parametersConvergenceTolerance=1e-8, double functionConvergenceTolerance=1e-4, @@ -328,7 +328,7 @@ namespace simple * be used to apply another kind of prior knowledge. * @{ */ - Self& SetOptimizerWeights(const std::vector &weights); + SITK_RETURN_SELF_TYPE_HEADER SetOptimizerWeights(const std::vector &weights); std::vector GetOptimizerWeights( ) const; /**@}*/ @@ -336,7 +336,7 @@ namespace simple * * \sa itk::PowellOptimizerv4 */ - Self& SetOptimizerAsPowell(unsigned int numberOfIterations = 100, + SITK_RETURN_SELF_TYPE_HEADER SetOptimizerAsPowell(unsigned int numberOfIterations = 100, unsigned int maximumLineIterations = 100, double stepLength = 1, double stepTolerance = 1e-6, @@ -344,7 +344,7 @@ namespace simple /** \brief Manually set per parameter weighting for the transform parameters. */ - Self& SetOptimizerScales( const std::vector &scales ); + SITK_RETURN_SELF_TYPE_HEADER SetOptimizerScales( const std::vector &scales ); /** \brief Estimate scales from Jacobian norms. * @@ -352,14 +352,14 @@ namespace simple * * \sa itk::RegistrationParameterScalesFromJacobian */ - Self& SetOptimizerScalesFromJacobian( unsigned int centralRegionRadius = 5 ); + SITK_RETURN_SELF_TYPE_HEADER SetOptimizerScalesFromJacobian( unsigned int centralRegionRadius = 5 ); /** \brief Estimate scales from maximum voxel shift in index space * cause by parameter change. * * \sa itk::RegistrationParameterScalesFromIndexShift */ - Self& SetOptimizerScalesFromIndexShift( unsigned int centralRegionRadius = 5, + SITK_RETURN_SELF_TYPE_HEADER SetOptimizerScalesFromIndexShift( unsigned int centralRegionRadius = 5, double smallParameterVariation = 0.01 ); /** \brief Estimating scales of transform parameters a step sizes, @@ -368,7 +368,7 @@ namespace simple * * \sa itk::RegistrationParameterScalesFromPhysicalShift */ - Self& SetOptimizerScalesFromPhysicalShift( unsigned int centralRegionRadius = 5, + SITK_RETURN_SELF_TYPE_HEADER SetOptimizerScalesFromPhysicalShift( unsigned int centralRegionRadius = 5, double smallParameterVariation = 0.01 ); @@ -381,7 +381,7 @@ namespace simple * * \sa itk::ImageToImageMetricv4::SetFixedImageMask */ - Self& SetMetricFixedMask( const Image &binaryMask ); + SITK_RETURN_SELF_TYPE_HEADER SetMetricFixedMask( const Image &binaryMask ); /** \brief Set an image mask in order to restrict the sampled points * for the metric in the moving image space. @@ -392,15 +392,15 @@ namespace simple * * \sa itk::ImageToImageMetricv4::SetMovingImageMask */ - Self& SetMetricMovingMask( const Image &binaryMask ); + SITK_RETURN_SELF_TYPE_HEADER SetMetricMovingMask( const Image &binaryMask ); /** \brief Set percentage of pixels sampled for metric evaluation. * * \sa itk::ImageRegistrationMethodv4::SetMetricSamplingPercentage * @{ */ - Self &SetMetricSamplingPercentage(double percentage); - Self &SetMetricSamplingPercentagePerLevel(const std::vector &percentage); + SITK_RETURN_SELF_TYPE_HEADER SetMetricSamplingPercentage(double percentage); + SITK_RETURN_SELF_TYPE_HEADER SetMetricSamplingPercentagePerLevel(const std::vector &percentage); /** @} */ enum MetricSamplingStrategyType { @@ -413,7 +413,7 @@ namespace simple * * \sa itk::ImageRegistrationMethodv4::SetMetricSamplingStrategy */ - Self &SetMetricSamplingStrategy( MetricSamplingStrategyType strategy); + SITK_RETURN_SELF_TYPE_HEADER SetMetricSamplingStrategy( MetricSamplingStrategyType strategy); /** \brief Enable image gradient computation by a filter. * @@ -424,9 +424,9 @@ namespace simple * \sa itk::ImageToImageMetricv4::SetUseFixedImageGradientFilter * @{ */ - Self& SetMetricUseFixedImageGradientFilter(bool); - Self& MetricUseFixedImageGradientFilterOn() {return this->SetMetricUseFixedImageGradientFilter(true);} - Self& MetricUseFixedImageGradientFilterOff() {return this->SetMetricUseFixedImageGradientFilter(false);} + SITK_RETURN_SELF_TYPE_HEADER SetMetricUseFixedImageGradientFilter(bool); + SITK_RETURN_SELF_TYPE_HEADER MetricUseFixedImageGradientFilterOn() {return this->SetMetricUseFixedImageGradientFilter(true);} + SITK_RETURN_SELF_TYPE_HEADER MetricUseFixedImageGradientFilterOff() {return this->SetMetricUseFixedImageGradientFilter(false);} /** @} */ @@ -439,9 +439,9 @@ namespace simple * \sa itk::ImageToImageMetricv4::SetUseMovingImageGradientFilter * @{ */ - Self& SetMetricUseMovingImageGradientFilter(bool); - Self& MetricUseMovingImageGradientFilterOn() {return this->SetMetricUseMovingImageGradientFilter(true);} - Self& MetricUseMovingImageGradientFilterOff() {return this->SetMetricUseMovingImageGradientFilter(false);} + SITK_RETURN_SELF_TYPE_HEADER SetMetricUseMovingImageGradientFilter(bool); + SITK_RETURN_SELF_TYPE_HEADER MetricUseMovingImageGradientFilterOn() {return this->SetMetricUseMovingImageGradientFilter(true);} + SITK_RETURN_SELF_TYPE_HEADER MetricUseMovingImageGradientFilterOff() {return this->SetMetricUseMovingImageGradientFilter(false);} /** @} */ @@ -450,14 +450,14 @@ namespace simple * * \sa itk::ImageRegistrationMethodv4::SetShrinkFactorsPerLevel */ - Self &SetShrinkFactorsPerLevel( const std::vector &shrinkFactors ); + SITK_RETURN_SELF_TYPE_HEADER SetShrinkFactorsPerLevel( const std::vector &shrinkFactors ); /** \brief Set the sigmas of Gaussian used for smoothing at each * level. * * \sa itk::ImageRegistrationMethodv4::SetSmoothingSigmasPerLevel */ - Self &SetSmoothingSigmasPerLevel( const std::vector &smoothingSigmas ); + SITK_RETURN_SELF_TYPE_HEADER SetSmoothingSigmasPerLevel( const std::vector &smoothingSigmas ); /** \brief Enable the smoothing sigmas for each level in physical * units (default) or in terms of voxels. @@ -465,9 +465,9 @@ namespace simple * \sa itk::ImageRegistrationMethodv4::SetSmoothingSigmasAreSpecifiedInPhysicalUnits * @{ */ - Self &SetSmoothingSigmasAreSpecifiedInPhysicalUnits(bool arg); - Self &SmoothingSigmasAreSpecifiedInPhysicalUnitsOn() { this->SetSmoothingSigmasAreSpecifiedInPhysicalUnits(true); return *this;} - Self &SmoothingSigmasAreSpecifiedInPhysicalUnitsOff() { this->SetSmoothingSigmasAreSpecifiedInPhysicalUnits(false); return *this;} + SITK_RETURN_SELF_TYPE_HEADER SetSmoothingSigmasAreSpecifiedInPhysicalUnits(bool arg); + SITK_RETURN_SELF_TYPE_HEADER SmoothingSigmasAreSpecifiedInPhysicalUnitsOn() { this->SetSmoothingSigmasAreSpecifiedInPhysicalUnits(true); return *this;} + SITK_RETURN_SELF_TYPE_HEADER SmoothingSigmasAreSpecifiedInPhysicalUnitsOff() { this->SetSmoothingSigmasAreSpecifiedInPhysicalUnits(false); return *this;} /** @} */ diff --git a/TemplateComponents/MemberGetSetDeclarations.h.in b/TemplateComponents/MemberGetSetDeclarations.h.in index 4de3dc00a..8b05c3b25 100644 --- a/TemplateComponents/MemberGetSetDeclarations.h.in +++ b/TemplateComponents/MemberGetSetDeclarations.h.in @@ -28,7 +28,7 @@ $(if (not no_set_method) or (no_set_method == 0) then end OUT= OUT .. '\ */\ - Self& Set${name} (' + SITK_RETURN_SELF_TYPE_HEADER Set${name} (' if not type and enum then OUT=OUT..' ${name}Type' elseif dim_vec and (dim_vec == 1) then @@ -43,15 +43,15 @@ $(if (not no_set_method) or (no_set_method == 0) then OUT = OUT .. '\ \ /** Set the values of the ${name} vector all to value */\ - Self& Set${name}( ${type} value ) { this->m_${name} = std::vector<${type}>(3, value); return *this; }\ + SITK_RETURN_SELF_TYPE_HEADER Set${name}( ${type} value ) { this->m_${name} = std::vector<${type}>(3, value); return *this; }\ ' end if type == "bool" and ( not dim_vec or not dim_vec == 1 ) then OUT = OUT .. '\ \ /** Set the value of ${name} to true or false respectfully. */\ - Self& ${name}On() { return this->Set${name}(true); }\ - Self& ${name}Off() { return this->Set${name}(false); }' + SITK_RETURN_SELF_TYPE_HEADER ${name}On() { return this->Set${name}(true); }\ + SITK_RETURN_SELF_TYPE_HEADER ${name}Off() { return this->Set${name}(false); }' end end) $(if (not no_get_method) or (no_get_method == 0) then @@ -82,9 +82,9 @@ end)$(if point_vec and (point_vec == 1) then OUT=[[ /** \brief Add ${name} point */ - Self& Add${name:gsub("s([0-9]?)$","%1")}( const std::vector< ${type} > &point ) { this->m_${name}.push_back(point); return *this;} + SITK_RETURN_SELF_TYPE_HEADER Add${name:gsub("s([0-9]?)$","%1")}( const std::vector< ${type} > &point ) { this->m_${name}.push_back(point); return *this;} /** \brief Remove all ${name} points */ - Self& Clear${name}( ) { this->m_${name}.clear(); return *this;} + SITK_RETURN_SELF_TYPE_HEADER Clear${name}( ) { this->m_${name}.clear(); return *this;} ]] end))$(when measurements $(foreach measurements From 2f4d72817445aed55ee1bf1abf13c159f17e9ee5 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 14:07:14 -0400 Subject: [PATCH 283/412] Remove unneeded private copy operators in Command classes The parent class is derived from NonCopyable, which enforces the no copy policy. Change-Id: Idf17d32de52bfb67420670d74824ee6986a5386c --- Wrapping/Python/sitkPyCommand.h | 5 ----- Wrapping/R/sitkRCommand.h | 2 -- 2 files changed, 7 deletions(-) diff --git a/Wrapping/Python/sitkPyCommand.h b/Wrapping/Python/sitkPyCommand.h index 6158e246a..42eb85ac6 100644 --- a/Wrapping/Python/sitkPyCommand.h +++ b/Wrapping/Python/sitkPyCommand.h @@ -71,11 +71,6 @@ class PyCommand using Super::OwnedByProcessObjectsOff; #endif - -protected: - PyCommand(const Self&); - PyCommand & operator=(const Self&); - private: PyObject *m_Object; }; diff --git a/Wrapping/R/sitkRCommand.h b/Wrapping/R/sitkRCommand.h index 5ef88e383..a2175be99 100644 --- a/Wrapping/R/sitkRCommand.h +++ b/Wrapping/R/sitkRCommand.h @@ -81,8 +81,6 @@ class RCommand protected: - RCommand(const Self&); - RCommand & operator=(const Self&); void SetCallbackRCallable(SEXP obj); void SetCallbackREnviron(SEXP rho); From b1c88870cee74724b0ea04461838ac90417602bc Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 14:26:59 -0400 Subject: [PATCH 284/412] Defining self return value Restore the return Self value for Swig wrapping, but change it to void for R wrapping. The resolve the issue for R to print all return values by default. Change-Id: I3e2b65e5ee6b991d5f842964360e21065b9c1dc9 --- Wrapping/Common/SimpleITK_Common.i | 6 ++++++ Wrapping/R/R.i | 2 ++ 2 files changed, 8 insertions(+) diff --git a/Wrapping/Common/SimpleITK_Common.i b/Wrapping/Common/SimpleITK_Common.i index f363992c7..4beff34eb 100644 --- a/Wrapping/Common/SimpleITK_Common.i +++ b/Wrapping/Common/SimpleITK_Common.i @@ -102,6 +102,12 @@ %include Ruby.i #endif + +#ifndef SITK_RETURN_SELF_TYPE_HEADER +#define SITK_RETURN_SELF_TYPE_HEADER Self & +#endif + + // Help SWIG handle std vectors namespace std { diff --git a/Wrapping/R/R.i b/Wrapping/R/R.i index f59534ed9..9b7df1d30 100644 --- a/Wrapping/R/R.i +++ b/Wrapping/R/R.i @@ -5,6 +5,8 @@ %ignore itk::simple::CastImageFilter::SetOutputPixelType( PixelIDValueType pixelID ); %ignore itk::simple::GetPixelIDValueAsString( PixelIDValueType type ); +#define SITK_RETURN_SELF_TYPE_HEADER void + %include // we don't want a class assigned to unsigned char %typemap(scoerceout) unsigned char, From 030b1942e686ad06c55447e1656c6a496d0adfe1 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 14:28:56 -0400 Subject: [PATCH 285/412] Adding Doxygen macro for the return by self value. Change-Id: I14b9776a3c7f328c04585ad800b297484fd4eba6 --- Utilities/Doxygen/doxygen.config.in | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Utilities/Doxygen/doxygen.config.in b/Utilities/Doxygen/doxygen.config.in index 87ac545e6..bb297c5a9 100644 --- a/Utilities/Doxygen/doxygen.config.in +++ b/Utilities/Doxygen/doxygen.config.in @@ -1993,7 +1993,8 @@ INCLUDE_FILE_PATTERNS = PREDEFINED = "itkNotUsed(x)=" \ "SITKBasicFilters_EXPORT= " \ "SITKITKIO_EXPORT= " \ - "SITKITKCommon_EXPORT= " + "SITKITKCommon_EXPORT= " \ + "SITK_RETURN_SELF_TYPE_HEADER=Self &" # 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 From 57006fd8656da1cf0480aa91180bbc96fe754ddc Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Fri, 10 Jun 2016 14:53:29 -0400 Subject: [PATCH 286/412] Remove old python virtualenv on rebuild Every time the python virtual environment in Testing/Installation/PythonVirtualEnv is re-built, remove any prior virtual environment. This is needed because on Windows, the build was failing when trying to write the tcl sub-directory if it already existed. Change-Id: If70ea0f85ae88805c9b0c5bd41280cfd5ae83975 --- Wrapping/Python/PythonVirtualEnvInstall.cmake.in | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Wrapping/Python/PythonVirtualEnvInstall.cmake.in b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in index 68912c061..24f140554 100644 --- a/Wrapping/Python/PythonVirtualEnvInstall.cmake.in +++ b/Wrapping/Python/PythonVirtualEnvInstall.cmake.in @@ -19,6 +19,12 @@ endif() # # Create the Python virtual environment. # +execute_process( + COMMAND ${CMAKE_COMMAND} + "-E" + "remove_directory" + "@PythonVirtualenvHome@" + ) execute_process( COMMAND "@PYTHON_EXECUTABLE@" "@PYTHON_VIRTUALENV_SCRIPT@" From 4e559697497be8f3e7c40bc885f8adbaa063b500 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 16:37:08 -0400 Subject: [PATCH 287/412] Adding option for no_size_check to named inputs Change-Id: I899cbd4ea857c524ec9d8e6ee74fe4882b5f3b06 --- TemplateComponents/ExecuteNoParameters.cxx.in | 8 ++++++-- Testing/Unit/sitkImageFilterTestTemplate.cxx.in | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/TemplateComponents/ExecuteNoParameters.cxx.in b/TemplateComponents/ExecuteNoParameters.cxx.in index a759f9993..abc65c6cd 100644 --- a/TemplateComponents/ExecuteNoParameters.cxx.in +++ b/TemplateComponents/ExecuteNoParameters.cxx.in @@ -19,8 +19,12 @@ if inputs then OUT=OUT..[[ // todo need better error handling and potential type conversion - if ( ]]..inputName..[[.GetDimension() != ]]..currentInputName..[[.GetDimension() || - ]]..inputName..[[.GetSize() != ]]..currentInputName..[[.GetSize() ) + if ( ]]..inputName..[[.GetDimension() != ]]..currentInputName..[[.GetDimension()]] + if not inputs[inum].no_size_check then + OUT=OUT..[[ || + ]]..inputName..[[.GetSize() != ]]..currentInputName..[[.GetSize()]] + end + OUT=OUT..[[ ) { sitkExceptionMacro ( "Input image ]]..currentInputName..[[ does not match dimension or size of first image!" ); } diff --git a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in index 951655f1c..a2015f60a 100644 --- a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in +++ b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in @@ -185,7 +185,7 @@ OUT = OUT .. [[ itk::simple::Image largeImage( 10,10,10,itk::simple::sitkUInt8 ); ]] for inum=2,#inputs do - if not inputs[inum].optional then + if not inputs[inum].optional and not inputs[inum].no_size_check then OUT = OUT .. [[ EXPECT_THROW ( filter.Execute ( largeImage]] for jnum=2,#inputs do From 3a866403dbe556df67e0c1acb438a31186f47737 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 16:37:26 -0400 Subject: [PATCH 288/412] Reducing check to expect from assert Change-Id: I77c60264639815f5fa2e2966ad33c8243596b5ae --- Testing/Unit/sitkImageFilterTestTemplate.cxx.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in index a2015f60a..726db1329 100644 --- a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in +++ b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in @@ -254,8 +254,8 @@ OUT=[=[ // Do we get the same image back, if we use the functional interface? itk::simple::Image fromFunctional( 0, 0, itk::simple::sitkUInt8 ); itk::simple::Image fromProcedural( 0, 0, itk::simple::sitkUInt8 ); - ASSERT_NO_THROW ( fromProcedural = filter.Execute ( $(if #inputs > 0 then OUT=[[inputs[0] ]] end)$(for inum=1,#inputs-1 do OUT=OUT..", inputs["..inum.."]" end) ) ) << "Procedural interface to ${name}"; - ASSERT_NO_THROW ( fromFunctional = itk::simple::${name:gsub("ImageFilter$", ""):gsub("Filter$", ""):gsub("ImageSource$", "Source")} ( $(if true then + EXPECT_NO_THROW ( fromProcedural = filter.Execute ( $(if #inputs > 0 then OUT=[[inputs[0] ]] end)$(for inum=1,#inputs-1 do OUT=OUT..", inputs["..inum.."]" end) ) ) << "Procedural interface to ${name}"; + EXPECT_NO_THROW ( fromFunctional = itk::simple::${name:gsub("ImageFilter$", ""):gsub("Filter$", ""):gsub("ImageSource$", "Source")} ( $(if true then local count = 0 if #inputs > 0 then OUT=[[inputs[0] ]] From ff2b8ac5ab34124257807704245f13983faffe21 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 16:42:27 -0400 Subject: [PATCH 289/412] Changing to Named inputs for NormalizedCorrelation filter. The unlabeled 3 inputs were very confusing. Adding names clarifies their purpose. Change-Id: Ia839e8d2525bdcfd5045094c279d5e2c460d069b --- .../NormalizedCorrelationImageFilter.json | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/Code/BasicFilters/json/NormalizedCorrelationImageFilter.json b/Code/BasicFilters/json/NormalizedCorrelationImageFilter.json index f695a8fad..4aa63aa53 100644 --- a/Code/BasicFilters/json/NormalizedCorrelationImageFilter.json +++ b/Code/BasicFilters/json/NormalizedCorrelationImageFilter.json @@ -2,14 +2,29 @@ "name" : "NormalizedCorrelationImageFilter", "template_code_filename" : "ImageFilter", "template_test_filename" : "ImageFilter", - "number_of_inputs" : 3, + "number_of_inputs" : 0, "pixel_types" : "BasicPixelIDTypeList", "include_files" : [ "sitkImageToKernel.hxx" ], + "inputs" : [ + { + "name" : "Image", + "type" : "Image" + }, + { + "name" : "MaskImage", + "type" : "Image" + }, + { + "name" : "TemplateImage", + "type" : "Image", + "no_size_check" : 0, + "custom_itk_cast" : "filter->SetTemplate( *CreateOperatorFromImage( this->CastImageToITK(*inTemplateImage).GetPointer() ).get() );" + } + ], "output_pixel_type" : "typename itk::NumericTraits::RealType", - "filter_type" : "itk::NormalizedCorrelationImageFilter", - "custom_set_input" : "filter->SetInput( 0, image1 ); filter->SetMaskImage( image2 ); filter->SetTemplate( *CreateOperatorFromImage( image3.GetPointer() ).get() );", + "filter_type" : "itk::NormalizedCorrelationImageFilter", "members" : [], "tests" : [ { From 1589df6c29ec2f55b2d5e4473f5176d81c7a9a80 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 10 Jun 2016 17:18:51 -0400 Subject: [PATCH 290/412] Updating Masked FFT Normalized Correlation with named inputs --- ...edFFTNormalizedCorrelationImageFilter.json | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/Code/BasicFilters/json/MaskedFFTNormalizedCorrelationImageFilter.json b/Code/BasicFilters/json/MaskedFFTNormalizedCorrelationImageFilter.json index 0911b1313..eb5cf38a8 100644 --- a/Code/BasicFilters/json/MaskedFFTNormalizedCorrelationImageFilter.json +++ b/Code/BasicFilters/json/MaskedFFTNormalizedCorrelationImageFilter.json @@ -2,11 +2,32 @@ "name" : "MaskedFFTNormalizedCorrelationImageFilter", "template_code_filename" : "ImageFilter", "template_test_filename" : "ImageFilter", - "number_of_inputs" : 4, + "number_of_inputs" : 0, "pixel_types" : "BasicPixelIDTypeList", "output_pixel_type" : "typename itk::NumericTraits::RealType", "filter_type" : "itk::MaskedFFTNormalizedCorrelationImageFilter", - "custom_set_input" : "filter->SetFixedImage( image1 ); filter->SetMovingImage( image2 ); filter->SetFixedImageMask( image3 ); filter->SetMovingImageMask( image4 );", + "inputs" : [ + { + "name" : "FixedImage", + "type" : "Image", + "custom_itk_cast" : "filter->SetFixedImage( this->CastImageToITK(*inFixedImage) );" + }, + { + "name" : "MovingImage", + "type" : "Image", + "custom_itk_cast" : "filter->SetMovingImage( this->CastImageToITK(*inMovingImage) );" + }, + { + "name" : "FixedImageMask", + "type" : "Image", + "custom_itk_cast" : "filter->SetFixedImageMask( this->CastImageToITK(*inFixedImageMask) );" + }, + { + "name" : "MovingImageMask", + "type" : "Image", + "custom_itk_cast" : "filter->SetMovingImageMask( this->CastImageToITK(*inMovingImageMask) );" + } + ], "members" : [ { "name" : "RequiredNumberOfOverlappingPixels", From 8dabc9f86cd36e51cbc7483c84a3f668c52d649b Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 13 Jun 2016 13:18:39 -0400 Subject: [PATCH 291/412] Don't check size of Moving images Change-Id: I342d50d609ac998aeaa9f3b4c25f29c0c7dae0fd --- .../json/MaskedFFTNormalizedCorrelationImageFilter.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Code/BasicFilters/json/MaskedFFTNormalizedCorrelationImageFilter.json b/Code/BasicFilters/json/MaskedFFTNormalizedCorrelationImageFilter.json index eb5cf38a8..f67b4e84d 100644 --- a/Code/BasicFilters/json/MaskedFFTNormalizedCorrelationImageFilter.json +++ b/Code/BasicFilters/json/MaskedFFTNormalizedCorrelationImageFilter.json @@ -15,6 +15,7 @@ { "name" : "MovingImage", "type" : "Image", + "no_size_check" : 0, "custom_itk_cast" : "filter->SetMovingImage( this->CastImageToITK(*inMovingImage) );" }, { @@ -25,6 +26,7 @@ { "name" : "MovingImageMask", "type" : "Image", + "no_size_check" : 0, "custom_itk_cast" : "filter->SetMovingImageMask( this->CastImageToITK(*inMovingImageMask) );" } ], From 842849d89673ba7ddea721d4fbbb99a156406e94 Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Wed, 15 Jun 2016 11:31:46 +1000 Subject: [PATCH 292/412] Advances in bracket operator/slicing The R bracket operator now uses the Slice and Extract filters, rather than custom C code. The major change is that arbitary slicing is no longer supported - there must be consistent spacing along each extracted dimension. The R code checks this kind of issue and attempts to produce sensible warnings/errors. A notable difference to array indexing is: a[c(),1:2] or a[0,1:2] These will produce an empty array with the first dimension size of 0. This doesn't have any particular use, and doesn't make sense for images, so this operation will raise an error for images. The Method code is quite complicated in terms due to the potentially arbitary number of dimensions that may be used. I have what I think is a solution, but will continue to search for improvments in dealing with the scenario. There is a test that covers origins, spacings and a few warning/error scenarios. A manual doc file has been created to cover some of the basics of the image class: library(SimpleITK) help("SimpleITK_Image-class") Change-Id: I2dcfcc042154f910360b1c1fac2ae037a10736d6 --- Testing/Unit/AdditionalTests.cmake | 3 + Testing/Unit/RImageSlicingTests.R | 245 ++++++++++++++ Wrapping/R/Packaging/SimpleITK/R/zA.R | 135 +++++--- .../SimpleITK/man/SimpleITK_Image-class.Rd | 106 +++++++ Wrapping/R/R.i | 298 ------------------ 5 files changed, 449 insertions(+), 338 deletions(-) create mode 100644 Testing/Unit/RImageSlicingTests.R create mode 100644 Wrapping/R/Packaging/SimpleITK/man/SimpleITK_Image-class.Rd diff --git a/Testing/Unit/AdditionalTests.cmake b/Testing/Unit/AdditionalTests.cmake index 901a6b15c..4b2375608 100644 --- a/Testing/Unit/AdditionalTests.cmake +++ b/Testing/Unit/AdditionalTests.cmake @@ -65,6 +65,9 @@ sitk_add_r_test( ImageListArguments sitk_add_r_test( SwigVectorConversion "--file=${SimpleITK_SOURCE_DIR}/Testing/Unit/RSwigVectorConversionTests.R" ) +sitk_add_r_test( ImageSlicing + "--file=${SimpleITK_SOURCE_DIR}/Testing/Unit/RImageSlicingTests.R" + ) # diff --git a/Testing/Unit/RImageSlicingTests.R b/Testing/Unit/RImageSlicingTests.R new file mode 100644 index 000000000..a1b31f9b2 --- /dev/null +++ b/Testing/Unit/RImageSlicingTests.R @@ -0,0 +1,245 @@ +## Test image slicing operators. They need to conform to rules that are slightly +## different to those for R matrices. +## +## These rules are: spacing needs to be uniform per dimension +## i.e. im[c(1,2,11),] is not accepted +## This means that creating reflected images isn't possible +## with slicing - use slicing + Tile. +## Dropping dimensions is the default, but SimpleITK does not +## support 1D images. The slicing operator will issue a warning if +## this is attempted. +## +## The bracket operator used for slicing now constructs calls to Slice and Extract, +## rather than using special C routines. This means that the operation is multithreaded +## and preserves spacing, origin and direction. +library(SimpleITK) +slicingOperatorUnitSpacingTest<- function() +{ + ## Cropping test - unit spacing + im <- Image(15,15,"sitkFloat64") + im$SetSpacing(c(0.3,0.6)) + t <- 0.4 + ct <- cos(t) + st <- sin(t) + im$SetDirection(c(ct,-st,st,ct)) + + e1 <- im[2:10,3:5] + + ef <- ExtractImageFilter() + ef <- ef$SetSize(c(9,3)) + ef <- ef$SetIndex(c(1,2)) + e2 <- ef$Execute(im) + + ## meta-data for slicing operator should match the metadata for the extract + ## filter which we know to be correct. + if(!all(e1$GetOrigin() == e2$GetOrigin())) + { + cat("slicing operator failed, origins don't match") + quit(save="no", status=1) + } + if(!all(e1$GetSpacing() == e2$GetSpacing())) + { + cat("slicing operator failed, spacings don't match") + quit(save="no", status=1) + } + if(!all(e1$GetDirection() == e2$GetDirection())) + { + cat("slicing operator failed, directions don't match") + quit(save="no", status=1) + } +} + + +dirToMat <- function(im) +{ + ## produce an R formatted direction matrix + d1 <- im$GetDirection() + dim(d1) <- c(2,2) + d1 <- t(d1) + return(d1) +} +slicingOperatorNegativeSpacingTest<- function() +{ + ## Cropping test - unit spacing + im <- Image(15,15,"sitkFloat64") + im$SetSpacing(c(0.3,0.6)) + t <- 0.4 + ct <- cos(t) + st <- sin(t) + im$SetDirection(c(ct,-st,st,ct)) + + e1 <- im[2:10,5:3] + + + ## meta-data for slicing operator should match the metadata for the extract + ## filter which we know to be correct. + if(!all(e1$GetOrigin() == im$TransformIndexToPhysicalPoint(c(1,4)))) + { + cat("slicing operator failed, origins don't match") + quit(save="no", status=1) + } + d1 <- dirToMat(im) + d2 <- dirToMat(e1) + ## reversed the second dimension, so d2[,2] == -d1[,2] + ## negate the second column and compare to original + d2[,2] <- -d2[,2] + if(!all(d1 == d2)) + { + cat("slicing operator failed, directions incorrect") + quit(save="no", status=1) + } +} + +slicingPositionChecks <- function() +{ + x<-rep(1:10, rep(12, 10)) + dim(x) <- c(12, 10) + x[5:9, 6:9] <- 21 + xim <- as.image(x) + + row3 <- as.array(xim[,3,drop=FALSE]) + if (!(all(row3 == 3))) { + cat("Incorrect pixel values - should be all 3\n") + quit(save="no", status=1) + + } + + b <- as.array(xim[5:9, 6:9]) + if (!all(b==21)) { + cat("Failed block extract - voxels should have value 21\n") + quit(save="no", status=1) + } +} +slicingOperatorWarningsErrors <- function() +{ + im <- Image(15,15,"sitkFloat64") + + ## this should issue a warning + msg <- list() + try(msg <- tools::assertWarning(im[1, 2:3]), silent=TRUE) + if (length(msg) == 0) { + cat("Slicing operator should have issued a warning, but did not.\n") + quit(save="no", status=1) + } + ## Turning drop off - no warning + msg <- list() + try(msg <- tools::assertCondition(im[1, 2:3, ,drop=FALSE]), silent=TRUE) + if (length(msg) != 0) { + cat("Slicing operator issued a warning/error, but should not.\n") + quit(save="no", status=1) + } + + ## Irregular spacing - should issue an error + msg <- list() + try(msg <- tools::assertError(im[c(1,2, 4), 2:3]), silent=TRUE) + if (length(msg) == 0) { + cat("Slicing operator should have issued an error, but did not.\n") + quit(save="no", status=1) + } +} + +slicingSyntaxTrials <- function() +{ + im2 <- Image(15,15,"sitkFloat64") + im3 <- Image(15,15, 15, "sitkFloat64") + + ## slicing requires all dimensions to be included - these should produce an + ## error + msg <- list() + try(msg <- tools::assertError(im3[1:2, 2:3]), silent=TRUE) + if (length(msg) == 0) { + cat("Slicing operator should have issued an error, but did not.\n") + quit(save="no", status=1) + } + + msg <- list() + try(msg <- tools::assertError(im3[1, 2:3,drop=TRUE]), silent=TRUE) + if (length(msg) == 0) { + cat("Slicing operator should have issued an error, but did not.\n") + quit(save="no", status=1) + } + ## this should be OK + msg <- list() + try(msg <- tools::assertCondition(im3[1:2, 2:3,]), silent=TRUE) + if (length(msg) != 0) { + cat("Slicing issued an error/warning, but should not.\n") + quit(save="no", status=1) + } + msg <- list() + try(msg <- tools::assertCondition(im3[1:2, 2:3,,drop=FALSE]), silent=TRUE) + if (length(msg) != 0) { + cat("Slicing issued an error/warning, but should not.\n") + quit(save="no", status=1) + } + ## this should be OK + msg <- list() + try(msg <- tools::assertCondition(im3[1:2, ,2:3,]), silent=TRUE) + if (length(msg) != 0) { + cat("Slicing issued an error/warning, but should not.\n") + quit(save="no", status=1) + } + + ## dropping tests + j<-im3[,,3,drop=FALSE] + if (any(j$GetSize() != c(15, 15, 1))) { + cat("Image slicing error - incorrect dimensions returned\n") + cat("Expected [15, 15, 1] - got [", j$GetSize(), "]\n") + quit(save="no", status=1) + } + j<-im3[,,3,drop=TRUE] + if (any(j$GetSize() != c(15, 15))) { + cat("Image slicing error - incorrect dimensions returned\n") + cat("Expected [15, 15] - got [", j$GetSize(), "]\n") + quit(save="no", status=1) + } + ## logical indexing, with variables + xidx <- (1:im3$GetWidth()) > 5 + msg <- list() + try(msg <- tools::assertCondition(im3[xidx, ,2:3]), silent=TRUE) + if (length(msg) != 0) { + cat("Slicing using logical issued an error/warning, but should not.\n") + quit(save="no", status=1) + } +} + +slicingZeroIndexTrials <- function() +{ + ## various forms of indexes are illegal because we can't support + ## an "empty" image in the way R supports an "empty" array + im3 <- Image(15,15, 15, "sitkFloat64") + + ## error caused by calling with c() + msg <- list() + try(msg <- tools::assertError(im3[c(), 2:3,]), silent=TRUE) + if (length(msg) == 0) { + cat("Slicing operator should have issued an error, but did not.\n") + quit(save="no", status=1) + } + ## check the 3rd dimension, which is handled differently to the first 2 + msg <- list() + try(msg <- tools::assertError(im3[2:3, 2:3, c()]), silent=TRUE) + if (length(msg) == 0) { + cat("Slicing operator should have issued an error, but did not.\n") + quit(save="no", status=1) + } + ## check 0 + msg <- list() + try(msg <- tools::assertError(im3[2:3, 0, 2:3]), silent=TRUE) + if (length(msg) == 0) { + cat("Slicing operator should have issued an error, but did not.\n") + quit(save="no", status=1) + } + msg <- list() + try(msg <- tools::assertError(im3[2:3, 2:3, 0]), silent=TRUE) + if (length(msg) == 0) { + cat("Slicing operator should have issued an error, but did not.\n") + quit(save="no", status=1) + } + + +} +slicingOperatorUnitSpacingTest() +slicingOperatorNegativeSpacingTest() +slicingPositionChecks() +slicingSyntaxTrials() +slicingZeroIndexTrials() diff --git a/Wrapping/R/Packaging/SimpleITK/R/zA.R b/Wrapping/R/Packaging/SimpleITK/R/zA.R index 0186ada88..6a648c54b 100644 --- a/Wrapping/R/Packaging/SimpleITK/R/zA.R +++ b/Wrapping/R/Packaging/SimpleITK/R/zA.R @@ -104,61 +104,116 @@ attr(`Image_GetPixel`, "inputTypes") = c('_p_itk__simple__Image', 'integer') class(`Image_GetPixel`) = c("SWIGFunction", class('Image_GetPixel')) ## experimental bracket operator for images -setMethod('[', "_p_itk__simple__Image", - function(x,i, j, k, drop=TRUE) { - # check to see whether this is returning a single number or an image - m <- sys.call() - - imdim <- Image_GetDimension(x) - if ((length(m)-2) < imdim) +setMethod('[', + signature=c(x="_p_itk__simple__Image", i="ANY", j="ANY"), + function(x,i, j, ..., drop=TRUE) { + m <- sys.call() + args = as.list(m[-c(1L, 2L)]) + numIndices = length(args) - !is.null(args$drop) + imdim <- Image_GetDimension(x) + if (numIndices < imdim) { - stop("Image has more dimensions") + stop("Image has more dimensions") } - imsize <- rep(1, 5) - imsize[1:imdim] <- Image_GetSize(x) - - if (missing(i)) { - i <- 1:imsize[1] - } else { - i <- (1:imsize[1])[i] - } - - if (missing(j)) { - j <- 1:imsize[2] - } else { - j <- (1:imsize[2])[j] - } - if (missing(k)) { - k <- 1:imsize[3] - } else { - k <- (1:imsize[3])[k] - } - - - if (any(is.na(c(i,j,k)))) { - stop("Indexes out of range") - } - i <- i - 1 - j <- j - 1 - k <- k - 1 - if ((length(i) == 1) & (length(j) == 1) & (length(k) == 1) ) { + imsize <- rep(1, 5) + imsize[1:imdim] <- Image_GetSize(x) + if (missing(i)) { + i <- 1:imsize[1] + } else { + i <- (1:imsize[1])[i] + } + if (missing(j)) { + j <- 1:imsize[2] + } else { + j <- (1:imsize[2])[j] + } + if (numIndices >= 3) { + k <- args[[3]] + if (missing(k)) { + k <- 1:imsize[3] + } else { + k <- (1:imsize[3])[eval.parent(k)] + } + } else { + k <- 1 + } + if (numIndices >=4) { + l <- args[[4]] + if (missing(l)) { + l <- 1:imsize[4] + } else { + l <- (1:imsize[4])[eval.parent(l)] + } + } else { + l <- 1 + } + if (any(is.na(c(i,j,k, l)))) { + stop("Indexes out of range") + } + i <- i - 1 + j <- j - 1 + k <- k - 1 + lenI <- length(i) + lenJ <- length(j) + lenK <- length(k) + lenL <- length(l) + + ll <- c(lenI, lenJ, lenK, lenL) + ## check for 0, c() indexes and flag an error + if (any(ll==0) ) { + stop("Illegal 0 or empty index in image slicing\n") + } + ## check to see whether this is returning a single number or an image + if (all(ll == 1)) { ## return a single point pixtype <- x$GetPixelID() aF <- sitkPixelAccessMap[[pixtype]] if (!is.null(aF)) { ## need to check whether we are using R or C indexing. - return(ImportPixVec(aF(x, c(i, j,k)))) + return(ImportPixVec(aF(x, c(i, j,k, l)))) } } else { - ## construct and return an image - pixtype <- x$GetPixelIDValue() - resIm <- SingleBracketOperator(i,j,k,x) + ## create call to SliceImageFilter + ## Check index spacing is uniform + dx <- diff(i) + if (!(all(dx==dx[1]))) { + stop("X spacing is not uniform\n") + } + dy <- diff(j) + if (!all(dy==dy[1])) { + stop("Y spacing is not uniform\n") + } + dz <- diff(k) + if (!all(dz==dz[1])) { + stop("Z spacing is not uniform\n") + } + dt <- diff(l) + if (!all(dt==dt[1])) { + stop("T spacing is not uniform\n") + } + start <- c(i[1], j[1], k[1], l[1]) + step <- c(dx[1], dy[1], dz[1], dt[1]) + ## deal with single row/column + step[is.na(step)] <- 1 + finish <- c(i[lenI], j[lenJ], k[lenK], l[lenK]) + step + resIm <- Slice(x, start, finish, step) + ## Drop dimensions + sz <- Image_GetSize(resIm) + if (drop & any(sz==1)) { + sz[sz==1] <- 0 + if (sum(sz != 0) > 1) { + resIm <- Extract(resIm, sz) + } else { + warning("Cannot return 1D image - returning image with some dimensions=1") + } + } return(resIm); } } ) + setMethod('[[', "_p_itk__simple__Image", function(x, i, j, ...) { return(VectorIndexSelectionCast(x, i-1)) diff --git a/Wrapping/R/Packaging/SimpleITK/man/SimpleITK_Image-class.Rd b/Wrapping/R/Packaging/SimpleITK/man/SimpleITK_Image-class.Rd new file mode 100644 index 000000000..7a2d963ee --- /dev/null +++ b/Wrapping/R/Packaging/SimpleITK/man/SimpleITK_Image-class.Rd @@ -0,0 +1,106 @@ +\name{_p_itk__simple__Image} +\Rdversion{1.1} +\docType{class} +\alias{_p_itk__simple__Image-class} +\alias{_p_itk__simple__Image} +\alias{SimpleITK_Image-class} +\alias{Image-class} +\alias{[,_p_itk__simple__Image-method} +\alias{[[,_p_itk__simple__Image-method} + +\title{Class \code{"_p_itk__simple__Image"}} +\description{ +The image class object used in SimpleITK. This object is a pointer to a C++ object +that contains the image voxel data and a range of meta data. + +Classes in SimpleITK have methods accessible via '$' operator. These methods are used +to set and get class meta data. +} +\section{Image objecst}{ + Objects can be created by calls of the form + + \code{Image(xsize, ysize, zsize, 'sitkUInt8')}, + + where 'sitkUInt8' defines the pixel type. + +Most SimpleITK functions and filter classes also return images. + +Images will often be saved in files and loaded using \code{im <- ReadImage(filename)}. + +Arrays can be converted to images using \code{as.image}. +} + +\section{Methods}{ + \describe{ + \item{[}{ The extract operator is used to perform image slicing in a + similar fashion to array slicing, with indexes starting from 1. + Standard slicing options are available, such as deleting using + negative indexes or using logical indexes. + + There are some image specific conventions/differences, as follows. + + Using zero or empty indexes will raise an error: + + \code{im[c(), 1:3]} + + \code{im[1, 1:3, 0]} + + Slicing operations must produce constant voxel spacing in each + dimension. i.e. subsampling must be uniform. + + Dropping a dimension (the default) is not always + possible as SimpleITK images must be at least 2 + dimensional. Operations that request a 1D image will return a + higher dimension image with some dimensions of size 1 and issue a + warning. + + An R object (number or vector) will be return if the operation + would otherwise result in an image with a single voxel. + + \code{im[1,2]} + + Array style assignment to image voxels is not yet supported. + + } + \item{[[}{ The list access operator is used to extract an image + component, such as the red channel from a colour image: + + \code{ red <- im[[1]] } + } + \item{Ops}{Arithmetic and logical operators are overloaded for + images. Images are checked for consistency of spacing and spatial + location. + + \code{ im1 * (im2 > 5) } + + Care may be required concerning pixel types - see the + \code{\link{Cast}} function. + } + \item{Meta data methods are accessible using the '$' operator}{} + \item{GetDimension}{Image dimension information + + \code{im$GetDimension()} + + } + \item{GetNumberOfComponentsPerPixel}{} + \item{SetOrigin/GetOrigin}{Image spatial origin meta data - + + \code{im$GetOrigin()} + } + \item{SetSpacing/GetSpacing}{Image voxel size meta data} + \item{GetSize}{Image size meta data (dimensions in voxels)} + \item{GetHeight/GetWidth/GetDepth}{Lengths of various image + dimensions} + \item{GetDirection/SetDirection}{Spatial transformation matrix} + \item{TransformIndexToPhysicalPoint}{Spatial location from index} + \item{TransformPhysicalPointToIndex}{Spatial location to index} + \item{TransformPhysicalPointToContinuousIndex}{} + \item{TransformContinuousIndexToPhysicalPoint}{} + \item{CopyInformation}{Copy meta data information from another image} + \item{GetPixel/SetPixel}{Pixel access methods - note indexing is + C-style, starting from 0} +} +} +\references{ +\link{https://itk.org/SimpleITKDoxygen/html/index.html} +} diff --git a/Wrapping/R/R.i b/Wrapping/R/R.i index f59534ed9..00bc533d2 100644 --- a/Wrapping/R/R.i +++ b/Wrapping/R/R.i @@ -83,304 +83,6 @@ std::vector, std::vector *, std::vector & %{ #include "sitkConditional.h" - - // functions for image content access via bracket operator - itk::simple::Image SingleBracketOperator(std::vector xcoord, std::vector ycoord, std::vector zcoord, const itk::simple::Image src) - { - itk::simple::PixelIDValueType PID=src.GetPixelIDValue(); - // use 3D coords. They get trimmed appropriately for 2D during access. - std::vector scoord(3); - std::vector dcoord(3); - - itk::simple::Image dest; - - if (zcoord.size() > 1) - { - dest = itk::simple::Image(xcoord.size(),ycoord.size(), zcoord.size(), - static_cast(src.GetPixelIDValue())); - } - else - { - dest = itk::simple::Image(xcoord.size(),ycoord.size(), - static_cast(src.GetPixelIDValue())); - - } - dest.SetSpacing(src.GetSpacing()); - - switch (PID) { - case itk::simple::ConditionalValue< itk::simple::sitkUInt8 != itk::simple::sitkUnknown, itk::simple::sitkUInt8, -2 >::Value: - { - for (unsigned z = 0, K=0; z < zcoord.size(); z++) - { - scoord[2]=static_cast(zcoord[z]); - dcoord[2]=K; - for (unsigned y = 0,J=0; y < ycoord.size(); y++) - { - scoord[1]=static_cast(ycoord[y]); - dcoord[1]=J; - for (unsigned x = 0,I=0; x < xcoord.size(); x++) - { - scoord[0]=static_cast(xcoord[x]); - dcoord[0]=I; - dest.SetPixelAsUInt8(dcoord, src.GetPixelAsUInt8(scoord)); - I++; - } - J++; - } - K++; - } - return(dest); - } - break; - case itk::simple::ConditionalValue< itk::simple::sitkInt8 != itk::simple::sitkUnknown, itk::simple::sitkInt8, -3 >::Value: - { - for (unsigned z = 0, K=0; z < zcoord.size(); z++) - { - scoord[2]=static_cast(zcoord[z]); - dcoord[2]=K; - for (unsigned y = 0,J=0; y < ycoord.size(); y++) - { - scoord[1]=static_cast(ycoord[y]); - dcoord[1]=J; - for (unsigned x = 0,I=0; x < xcoord.size(); x++) - { - scoord[0]=static_cast(xcoord[x]); - dcoord[0]=I; - dest.SetPixelAsInt8(dcoord, src.GetPixelAsInt8(scoord)); - I++; - } - J++; - } - K++; - } - return(dest); - } - break; - case itk::simple::ConditionalValue< itk::simple::sitkUInt16 != itk::simple::sitkUnknown, itk::simple::sitkUInt16, -4 >::Value: - { - for (unsigned z = 0, K=0; z < zcoord.size(); z++) - { - scoord[2]=static_cast(zcoord[z]); - dcoord[2]=K; - for (unsigned y = 0,J=0; y < ycoord.size(); y++) - { - scoord[1]=static_cast(ycoord[y]); - dcoord[1]=J; - for (unsigned x = 0,I=0; x < xcoord.size(); x++) - { - scoord[0]=static_cast(xcoord[x]); - dcoord[0]=I; - dest.SetPixelAsUInt16(dcoord, src.GetPixelAsUInt16(scoord)); - I++; - } - J++; - } - K++; - } - return(dest); - } - break; - case itk::simple::ConditionalValue< itk::simple::sitkInt16 != itk::simple::sitkUnknown, itk::simple::sitkInt16, -5 >::Value: - { - for (unsigned z = 0, K=0; z < zcoord.size(); z++) - { - scoord[2]=static_cast(zcoord[z]); - dcoord[2]=K; - for (unsigned y = 0,J=0; y < ycoord.size(); y++) - { - scoord[1]=static_cast(ycoord[y]); - dcoord[1]=J; - for (unsigned x = 0,I=0; x < xcoord.size(); x++) - { - scoord[0]=static_cast(xcoord[x]); - dcoord[0]=I; - dest.SetPixelAsInt16(dcoord, src.GetPixelAsInt16(scoord)); - I++; - } - J++; - } - K++; - } - return(dest); - } - break; - case itk::simple::ConditionalValue< itk::simple::sitkUInt32 != itk::simple::sitkUnknown, itk::simple::sitkUInt32, -6 >::Value: - { - for (unsigned z = 0, K=0; z < zcoord.size(); z++) - { - scoord[2]=static_cast(zcoord[z]); - dcoord[2]=K; - for (unsigned y = 0,J=0; y < ycoord.size(); y++) - { - scoord[1]=static_cast(ycoord[y]); - dcoord[1]=J; - for (unsigned x = 0,I=0; x < xcoord.size(); x++) - { - scoord[0]=static_cast(xcoord[x]); - dcoord[0]=I; - dest.SetPixelAsUInt32(dcoord, src.GetPixelAsUInt32(scoord)); - I++; - } - J++; - } - K++; - } - return(dest); - } - break; - case itk::simple::ConditionalValue< itk::simple::sitkInt32 != itk::simple::sitkUnknown, itk::simple::sitkInt32, -7 >::Value: - { - for (unsigned z = 0, K=0; z < zcoord.size(); z++) - { - scoord[2]=static_cast(zcoord[z]); - dcoord[2]=K; - for (unsigned y = 0,J=0; y < ycoord.size(); y++) - { - scoord[1]=static_cast(ycoord[y]); - dcoord[1]=J; - for (unsigned x = 0,I=0; x < xcoord.size(); x++) - { - scoord[0]=static_cast(xcoord[x]); - dcoord[0]=I; - dest.SetPixelAsInt32(dcoord, src.GetPixelAsInt32(scoord)); - I++; - } - J++; - } - K++; - } - return(dest); - } - break; - case itk::simple::ConditionalValue< itk::simple::sitkUInt64 != itk::simple::sitkUnknown, itk::simple::sitkUInt64, -8 >::Value: - { - for (unsigned z = 0, K=0; z < zcoord.size(); z++) - { - scoord[2]=static_cast(zcoord[z]); - dcoord[2]=K; - for (unsigned y = 0,J=0; y < ycoord.size(); y++) - { - scoord[1]=static_cast(ycoord[y]); - dcoord[1]=J; - for (unsigned x = 0,I=0; x < xcoord.size(); x++) - { - scoord[0]=static_cast(xcoord[x]); - dcoord[0]=I; - dest.SetPixelAsUInt64(dcoord, src.GetPixelAsUInt64(scoord)); - I++; - } - J++; - } - K++; - } - return(dest); - } - break; - case itk::simple::ConditionalValue< itk::simple::sitkInt64 != itk::simple::sitkUnknown, itk::simple::sitkInt64, -9 >::Value: - { - for (unsigned z = 0, K=0; z < zcoord.size(); z++) - { - scoord[2]=static_cast(zcoord[z]); - dcoord[2]=K; - for (unsigned y = 0,J=0; y < ycoord.size(); y++) - { - scoord[1]=static_cast(ycoord[y]); - dcoord[1]=J; - for (unsigned x = 0,I=0; x < xcoord.size(); x++) - { - scoord[0]=static_cast(xcoord[x]); - dcoord[0]=I; - dest.SetPixelAsInt64(dcoord, src.GetPixelAsInt64(scoord)); - I++; - } - J++; - } - K++; - } - return(dest); - } - break; - case itk::simple::ConditionalValue< itk::simple::sitkFloat32 != itk::simple::sitkUnknown, itk::simple::sitkFloat32, -10 >::Value: - - { - for (unsigned z = 0, K=0; z < zcoord.size(); z++) - { - scoord[2]=static_cast(zcoord[z]); - dcoord[2]=K; - for (unsigned y = 0,J=0; y < ycoord.size(); y++) - { - scoord[1]=static_cast(ycoord[y]); - dcoord[1]=J; - for (unsigned x = 0,I=0; x < xcoord.size(); x++) - { - scoord[0]=static_cast(xcoord[x]); - dcoord[0]=I; - dest.SetPixelAsFloat(dcoord, src.GetPixelAsFloat(scoord)); - I++; - } - J++; - } - K++; - } - return(dest); - } - break; - case itk::simple::ConditionalValue< itk::simple::sitkFloat64 != itk::simple::sitkUnknown, itk::simple::sitkFloat64, -11 >::Value: - { - for (unsigned z = 0, K=0; z < zcoord.size(); z++) - { - scoord[2]=static_cast(zcoord[z]); - dcoord[2]=K; - for (unsigned y = 0,J=0; y < ycoord.size(); y++) - { - scoord[1]=static_cast(ycoord[y]); - dcoord[1]=J; - for (unsigned x = 0,I=0; x < xcoord.size(); x++) - { - scoord[0]=static_cast(xcoord[x]); - dcoord[0]=I; - dest.SetPixelAsDouble(dcoord, src.GetPixelAsDouble(scoord)); - I++; - } - J++; - } - K++; - } - return(dest); - } - case itk::simple::ConditionalValue< itk::simple::sitkComplexFloat32 != itk::simple::sitkUnknown, itk::simple::sitkComplexFloat32, -12 >::Value: - case itk::simple::ConditionalValue< itk::simple::sitkComplexFloat64 != itk::simple::sitkUnknown, itk::simple::sitkComplexFloat64, -13 >::Value: - { - char error_msg[1024]; - snprintf( error_msg, 1024, "Exception thrown SingleBracketOperator : complex floating types not supported"); - Rprintf(error_msg); - } - break; - case itk::simple::ConditionalValue< itk::simple::sitkVectorUInt8 != itk::simple::sitkUnknown, itk::simple::sitkVectorUInt8, -14 >::Value: - case itk::simple::ConditionalValue< itk::simple::sitkVectorInt8 != itk::simple::sitkUnknown, itk::simple::sitkVectorInt8, -15 >::Value: - case itk::simple::ConditionalValue< itk::simple::sitkVectorUInt16 != itk::simple::sitkUnknown, itk::simple::sitkVectorUInt16, -16 >::Value: - case itk::simple::ConditionalValue< itk::simple::sitkVectorInt16 != itk::simple::sitkUnknown, itk::simple::sitkVectorInt16, -17 >::Value: - case itk::simple::ConditionalValue< itk::simple::sitkVectorUInt32 != itk::simple::sitkUnknown, itk::simple::sitkVectorUInt32, -18 >::Value: - case itk::simple::ConditionalValue< itk::simple::sitkVectorInt32 != itk::simple::sitkUnknown, itk::simple::sitkVectorInt32, -19 >::Value: - case itk::simple::ConditionalValue< itk::simple::sitkVectorUInt64 != itk::simple::sitkUnknown, itk::simple::sitkVectorUInt64, -20 >::Value: - case itk::simple::ConditionalValue< itk::simple::sitkVectorInt64 != itk::simple::sitkUnknown, itk::simple::sitkVectorInt64, -21 >::Value: - case itk::simple::ConditionalValue< itk::simple::sitkVectorFloat32 != itk::simple::sitkUnknown, itk::simple::sitkVectorFloat32, -22 >::Value: - case itk::simple::ConditionalValue< itk::simple::sitkVectorFloat64 != itk::simple::sitkUnknown, itk::simple::sitkVectorFloat64, -23 >::Value: - { - char error_msg[1024]; - snprintf( error_msg, 1024, "Images of Vector Pixel types currently are not supported." ); - Rprintf(error_msg); - } - break; - default: - char error_msg[1024]; - snprintf( error_msg, 1024, "Exception thrown SingleBrackeOperator : unsupported pixel type: %d", PID ); - Rprintf(error_msg); - } - // return something to keep R happy. - return(itk::simple::Image(0,0,0, itk::simple::sitkUInt8)); - } - SEXP ImAsArray(itk::simple::Image src) { // tricky to make this efficient with memory and fast. From 219e7732216171bad40c84960f70c883693479e6 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 17 Jun 2016 15:34:05 -0400 Subject: [PATCH 293/412] Updating SimpleITK JSON from ITK doxygen This contains a large change to https URL along with minor tweaks. Change-Id: I0f9aca0d969a0bfbda1a63b7f1aeee956998abb5 --- Code/BasicFilters/json/AbsImageFilter.json | 2 +- .../AdaptiveHistogramEqualizationImageFilter.json | 6 +++--- .../json/AdditiveGaussianNoiseImageFilter.json | 2 +- .../BasicFilters/json/AggregateLabelMapFilter.json | 2 +- Code/BasicFilters/json/BinShrinkImageFilter.json | 2 +- .../BinaryClosingByReconstructionImageFilter.json | 2 +- .../json/BinaryContourImageFilter.json | 2 +- .../json/BinaryFillholeImageFilter.json | 2 +- .../json/BinaryGrindPeakImageFilter.json | 2 +- .../json/BinaryImageToLabelMapFilter.json | 10 +++++----- .../BinaryMorphologicalClosingImageFilter.json | 2 +- .../BinaryMorphologicalOpeningImageFilter.json | 2 +- Code/BasicFilters/json/BinaryNotImageFilter.json | 2 +- .../BinaryOpeningByReconstructionImageFilter.json | 2 +- .../json/BinaryProjectionImageFilter.json | 2 +- .../BinaryReconstructionByDilationImageFilter.json | 2 +- .../BinaryReconstructionByErosionImageFilter.json | 2 +- .../json/BinaryThresholdImageFilter.json | 2 +- .../json/BinaryThresholdProjectionImageFilter.json | 2 +- Code/BasicFilters/json/BoxMeanImageFilter.json | 2 +- Code/BasicFilters/json/BoxSigmaImageFilter.json | 2 +- .../json/ChangeLabelLabelMapFilter.json | 2 +- .../json/ConnectedComponentImageFilter.json | 4 ++-- Code/BasicFilters/json/ConvolutionImageFilter.json | 2 +- Code/BasicFilters/json/DerivativeImageFilter.json | 8 ++++---- .../DiffeomorphicDemonsRegistrationFilter.json | 2 +- .../DiscreteGaussianDerivativeImageFilter.json | 2 +- .../json/DoubleThresholdImageFilter.json | 2 +- .../json/FFTConvolutionImageFilter.json | 2 +- Code/BasicFilters/json/FFTPadImageFilter.json | 2 +- Code/BasicFilters/json/FFTShiftImageFilter.json | 2 +- .../json/FastApproximateRankImageFilter.json | 2 +- ...astSymmetricForcesDemonsRegistrationFilter.json | 2 +- Code/BasicFilters/json/GaborImageSource.json | 2 +- Code/BasicFilters/json/GridImageSource.json | 2 +- .../json/HuangThresholdImageFilter.json | 2 +- .../json/IntermodesThresholdImageFilter.json | 2 +- .../json/IsoDataThresholdImageFilter.json | 2 +- .../KittlerIllingworthThresholdImageFilter.json | 2 +- .../BasicFilters/json/LabelContourImageFilter.json | 2 +- .../json/LabelImageToLabelMapFilter.json | 6 +++--- .../json/LabelIntensityStatisticsImageFilter.json | 2 +- .../json/LabelMapContourOverlayImageFilter.json | 2 +- .../BasicFilters/json/LabelMapMaskImageFilter.json | 6 +++--- .../json/LabelMapOverlayImageFilter.json | 2 +- .../json/LabelMapToBinaryImageFilter.json | 2 +- .../json/LabelMapToLabelImageFilter.json | 2 +- .../json/LabelMapToRGBImageFilter.json | 2 +- .../json/LabelOverlapMeasuresImageFilter.json | 2 +- .../BasicFilters/json/LabelOverlayImageFilter.json | 2 +- .../json/LabelShapeStatisticsImageFilter.json | 2 +- .../json/LabelStatisticsImageFilter.json | 4 ++-- Code/BasicFilters/json/LabelToRGBImageFilter.json | 2 +- .../json/LabelUniqueLabelMapFilter.json | 2 +- .../json/LandweberDeconvolutionImageFilter.json | 2 +- .../json/LevelSetMotionRegistrationFilter.json | 4 ++-- Code/BasicFilters/json/LiThresholdImageFilter.json | 2 +- .../json/MaximumEntropyThresholdImageFilter.json | 2 +- .../json/MaximumProjectionImageFilter.json | 2 +- .../json/MeanProjectionImageFilter.json | 2 +- .../json/MedianProjectionImageFilter.json | 2 +- Code/BasicFilters/json/MergeLabelMapFilter.json | 2 +- .../json/MinimumProjectionImageFilter.json | 2 +- .../json/MomentsThresholdImageFilter.json | 2 +- ...rphologicalWatershedFromMarkersImageFilter.json | 2 +- .../json/MorphologicalWatershedImageFilter.json | 2 +- .../json/MultiLabelSTAPLEImageFilter.json | 14 +++++++++----- .../json/N4BiasFieldCorrectionImageFilter.json | 2 +- .../json/NormalizeToConstantImageFilter.json | 2 +- .../json/OtsuThresholdImageFilter.json | 2 +- ...ProjectedLandweberDeconvolutionImageFilter.json | 2 +- Code/BasicFilters/json/RankImageFilter.json | 2 +- .../json/RegionalMaximaImageFilter.json | 2 +- .../json/RegionalMinimaImageFilter.json | 2 +- Code/BasicFilters/json/RelabelLabelMapFilter.json | 2 +- .../json/RenyiEntropyThresholdImageFilter.json | 2 +- .../RichardsonLucyDeconvolutionImageFilter.json | 2 +- .../json/SaltAndPepperNoiseImageFilter.json | 2 +- .../ScalarChanAndVeseDenseLevelSetImageFilter.json | 2 +- .../json/ScalarToRGBColormapImageFilter.json | 2 +- .../json/ShanbhagThresholdImageFilter.json | 2 +- Code/BasicFilters/json/ShotNoiseImageFilter.json | 2 +- .../BasicFilters/json/SpeckleNoiseImageFilter.json | 2 +- .../json/SquaredDifferenceImageFilter.json | 2 +- .../StandardDeviationProjectionImageFilter.json | 2 +- .../json/SumProjectionImageFilter.json | 2 +- Code/BasicFilters/json/ThresholdImageFilter.json | 2 +- ...sholdMaximumConnectedComponentsImageFilter.json | 6 +++--- .../json/TransformToDisplacementFieldFilter.json | 2 +- .../json/TriangleThresholdImageFilter.json | 2 +- .../json/ValuedRegionalMaximaImageFilter.json | 2 +- .../json/ValuedRegionalMinimaImageFilter.json | 2 +- .../BasicFilters/json/YenThresholdImageFilter.json | 2 +- .../BasicFilters/json/ZeroCrossingImageFilter.json | 2 +- 94 files changed, 120 insertions(+), 116 deletions(-) diff --git a/Code/BasicFilters/json/AbsImageFilter.json b/Code/BasicFilters/json/AbsImageFilter.json index 8576beafa..f77fc78ac 100644 --- a/Code/BasicFilters/json/AbsImageFilter.json +++ b/Code/BasicFilters/json/AbsImageFilter.json @@ -28,5 +28,5 @@ } ], "briefdescription" : "Computes the absolute value of each pixel.", - "detaileddescription" : "vnl_math_abs() is used to perform the computation.\n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Compute the absolute value of an image" + "detaileddescription" : "itk::Math::abs() is used to perform the computation.\n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Compute the absolute value of an image" } diff --git a/Code/BasicFilters/json/AdaptiveHistogramEqualizationImageFilter.json b/Code/BasicFilters/json/AdaptiveHistogramEqualizationImageFilter.json index 19c4d5613..20bd54e4b 100644 --- a/Code/BasicFilters/json/AdaptiveHistogramEqualizationImageFilter.json +++ b/Code/BasicFilters/json/AdaptiveHistogramEqualizationImageFilter.json @@ -39,9 +39,9 @@ "type" : "bool", "default" : "false", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set/Get whether an optimized lookup table for the intensity mapping function is used. Default is off.", + "detaileddescriptionSet" : "Set/Get whether an optimized lookup table for the intensity mapping function is used. Default is off.Deprecated", "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Set/Get whether an optimized lookup table for the intensity mapping function is used. Default is off." + "detaileddescriptionGet" : "Set/Get whether an optimized lookup table for the intensity mapping function is used. Default is off.Deprecated" } ], "tests" : [ @@ -75,5 +75,5 @@ } ], "briefdescription" : "Power Law Adaptive Histogram Equalization.", - "detaileddescription" : "Histogram equalization modifies the contrast in an image. The AdaptiveHistogramEqualizationImageFilter is a superset of many contrast enhancing filters. By modifying its parameters (alpha, beta, and window), the AdaptiveHistogramEqualizationImageFilter can produce an adaptively equalized histogram or a version of unsharp mask (local mean subtraction). Instead of applying a strict histogram equalization in a window about a pixel, this filter prescribes a mapping function (power law) controlled by the parameters alpha and beta.\n\nThe parameter alpha controls how much the filter acts like the classical histogram equalization method (alpha=0) to how much the filter acts like an unsharp mask (alpha=1).\n\nThe parameter beta controls how much the filter acts like an unsharp mask (beta=0) to much the filter acts like pass through (beta=1, with alpha=1).\n\nThe parameter window controls the size of the region over which local statistics are calculated.\n\nBy altering alpha, beta and window, a host of equalization and unsharp masking filters is available.\n\nFor detail description, reference \"Adaptive Image Contrast\nEnhancement using Generalizations of Histogram Equalization.\" J.Alex Stark. IEEE Transactions on Image Processing, May 2000.\n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Adaptive histogram equalization" + "detaileddescription" : "Histogram equalization modifies the contrast in an image. The AdaptiveHistogramEqualizationImageFilter is a superset of many contrast enhancing filters. By modifying its parameters (alpha, beta, and window), the AdaptiveHistogramEqualizationImageFilter can produce an adaptively equalized histogram or a version of unsharp mask (local mean subtraction). Instead of applying a strict histogram equalization in a window about a pixel, this filter prescribes a mapping function (power law) controlled by the parameters alpha and beta.\n\nThe parameter alpha controls how much the filter acts like the classical histogram equalization method (alpha=0) to how much the filter acts like an unsharp mask (alpha=1).\n\nThe parameter beta controls how much the filter acts like an unsharp mask (beta=0) to much the filter acts like pass through (beta=1, with alpha=1).\n\nThe parameter window controls the size of the region over which local statistics are calculated.\n\nBy altering alpha, beta and window, a host of equalization and unsharp masking filters is available.\n\nThe boundary condition ignores the part of the neighborhood outside the image, and over-weights the valid part of the neighborhood.\n\nFor detail description, reference \"Adaptive Image Contrast\nEnhancement using Generalizations of Histogram Equalization.\" J.Alex Stark. IEEE Transactions on Image Processing, May 2000.\n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Adaptive histogram equalization" } diff --git a/Code/BasicFilters/json/AdditiveGaussianNoiseImageFilter.json b/Code/BasicFilters/json/AdditiveGaussianNoiseImageFilter.json index 7b693dc38..560a98850 100644 --- a/Code/BasicFilters/json/AdditiveGaussianNoiseImageFilter.json +++ b/Code/BasicFilters/json/AdditiveGaussianNoiseImageFilter.json @@ -94,5 +94,5 @@ } ], "briefdescription" : "Alter an image with additive gaussian white noise.", - "detaileddescription" : "\\author Gaetan Lehmann\n\nThis code was contributed in the Insight Journal paper \"Noise\nSimulation\". http://hdl.handle.net/10380/3158" + "detaileddescription" : "\\author Gaetan Lehmann\n\nThis code was contributed in the Insight Journal paper \"Noise\nSimulation\". https://hdl.handle.net/10380/3158" } diff --git a/Code/BasicFilters/json/AggregateLabelMapFilter.json b/Code/BasicFilters/json/AggregateLabelMapFilter.json index 266fcc1ed..6e5f7ff2f 100644 --- a/Code/BasicFilters/json/AggregateLabelMapFilter.json +++ b/Code/BasicFilters/json/AggregateLabelMapFilter.json @@ -31,5 +31,5 @@ } ], "briefdescription" : "Collapses all labels into the first label.", - "detaileddescription" : "This filter takes a label map as input and visits the pixels of all labels and assigns them to the first label of the label map. At the end of the execution of this filter, the map will contain a single filter.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ShapeLabelObject , RelabelComponentImageFilter" + "detaileddescription" : "This filter takes a label map as input and visits the pixels of all labels and assigns them to the first label of the label map. At the end of the execution of this filter, the map will contain a single filter.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ShapeLabelObject , RelabelComponentImageFilter" } diff --git a/Code/BasicFilters/json/BinShrinkImageFilter.json b/Code/BasicFilters/json/BinShrinkImageFilter.json index eba90d004..a7d0be0f9 100644 --- a/Code/BasicFilters/json/BinShrinkImageFilter.json +++ b/Code/BasicFilters/json/BinShrinkImageFilter.json @@ -47,5 +47,5 @@ } ], "briefdescription" : "Reduce the size of an image by an integer factor in each dimension while performing averaging of an input neighborhood.", - "detaileddescription" : "The output image size in each dimension is given by:\n\noutputSize[j] = max( std::floor(inputSize[j]/shrinkFactor[j]), 1 );\n\nThe algorithm implemented can be describe with the following equation for 2D: \\f[ \\mathsf{I}_{out}(x_o,x_1) = \\frac{\\sum_{i=0}^{f_0}\\sum_{j=0}^{f_1}\\mathsf{I}_{in}(f_0 x_o+i,f_1 x_1+j)}{f_0 f_1} \\f] \n\nThis filter is implemented so that the starting extent of the first pixel of the output matches that of the input.\n\nThe change in image geometry from a 5x5 image binned by a factor of 2x2.This code was contributed in the Insight Journal paper: \"BinShrink: A multi-resolution filter with cache efficient averaging\" by Lowekamp B., Chen D. http://hdl.handle.net/10380/3450" + "detaileddescription" : "The output image size in each dimension is given by:\n\noutputSize[j] = max( std::floor(inputSize[j]/shrinkFactor[j]), 1 );\n\nThe algorithm implemented can be describe with the following equation for 2D: \\f[ \\mathsf{I}_{out}(x_o,x_1) = \\frac{\\sum_{i=0}^{f_0}\\sum_{j=0}^{f_1}\\mathsf{I}_{in}(f_0 x_o+i,f_1 x_1+j)}{f_0 f_1} \\f] \n\nThis filter is implemented so that the starting extent of the first pixel of the output matches that of the input.\n\nThe change in image geometry from a 5x5 image binned by a factor of 2x2.This code was contributed in the Insight Journal paper: \"BinShrink: A multi-resolution filter with cache efficient averaging\" by Lowekamp B., Chen D. https://hdl.handle.net/10380/3450" } diff --git a/Code/BasicFilters/json/BinaryClosingByReconstructionImageFilter.json b/Code/BasicFilters/json/BinaryClosingByReconstructionImageFilter.json index c468dbdac..71bb1cba9 100644 --- a/Code/BasicFilters/json/BinaryClosingByReconstructionImageFilter.json +++ b/Code/BasicFilters/json/BinaryClosingByReconstructionImageFilter.json @@ -62,5 +62,5 @@ } ], "briefdescription" : "binary closing by reconstruction of an image.", - "detaileddescription" : "This filter removes small (i.e., smaller than the structuring element) holes in the image. It is defined as: Closing(f) = ReconstructionByErosion(Dilation(f)).\n\nThe structuring element is assumed to be composed of binary values (zero or one). Only elements of the structuring element having values > 0 are candidates for affecting the center pixel.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see MorphologyImageFilter , ClosingByReconstructionImageFilter , BinaryOpeningByReconstructionImageFilter" + "detaileddescription" : "This filter removes small (i.e., smaller than the structuring element) holes in the image. It is defined as: Closing(f) = ReconstructionByErosion(Dilation(f)).\n\nThe structuring element is assumed to be composed of binary values (zero or one). Only elements of the structuring element having values > 0 are candidates for affecting the center pixel.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see MorphologyImageFilter , ClosingByReconstructionImageFilter , BinaryOpeningByReconstructionImageFilter" } diff --git a/Code/BasicFilters/json/BinaryContourImageFilter.json b/Code/BasicFilters/json/BinaryContourImageFilter.json index cad1fb14c..7a023ff9b 100644 --- a/Code/BasicFilters/json/BinaryContourImageFilter.json +++ b/Code/BasicFilters/json/BinaryContourImageFilter.json @@ -75,5 +75,5 @@ } ], "briefdescription" : "Labels the pixels on the border of the objects in a binary image.", - "detaileddescription" : "BinaryContourImageFilter takes a binary image as input, where the pixels in the objects are the pixels with a value equal to ForegroundValue. Only the pixels on the contours of the objects are kept. The pixels not on the border are changed to BackgroundValue.\n\nThe connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours.\n\nhttp://hdl.handle.net/1926/1352 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see LabelContourImageFilter BinaryErodeImageFilter SimpleContourExtractorImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Extract the boundaries of connected regions in a binary image \n\n\\li Extract the inner and outer boundaries of blobs in a binary image" + "detaileddescription" : "BinaryContourImageFilter takes a binary image as input, where the pixels in the objects are the pixels with a value equal to ForegroundValue. Only the pixels on the contours of the objects are kept. The pixels not on the border are changed to BackgroundValue.\n\nThe connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours.\n\nhttps://hdl.handle.net/1926/1352 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see LabelContourImageFilter BinaryErodeImageFilter SimpleContourExtractorImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Extract the boundaries of connected regions in a binary image \n\n\\li Extract the inner and outer boundaries of blobs in a binary image" } diff --git a/Code/BasicFilters/json/BinaryFillholeImageFilter.json b/Code/BasicFilters/json/BinaryFillholeImageFilter.json index 6eb2b2cc7..5b6f64c2c 100644 --- a/Code/BasicFilters/json/BinaryFillholeImageFilter.json +++ b/Code/BasicFilters/json/BinaryFillholeImageFilter.json @@ -66,5 +66,5 @@ } ], "briefdescription" : "Remove holes not connected to the boundary of the image.", - "detaileddescription" : "BinaryFillholeImageFilter fills holes in a binary image.\n\nGeodesic morphology and the Fillhole algorithm is described in Chapter 6 of Pierre Soille's book \"Morphological Image Analysis:\nPrinciples and Applications\", Second Edition, Springer, 2003.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see GrayscaleFillholeImageFilter" + "detaileddescription" : "BinaryFillholeImageFilter fills holes in a binary image.\n\nGeodesic morphology and the Fillhole algorithm is described in Chapter 6 of Pierre Soille's book \"Morphological Image Analysis:\nPrinciples and Applications\", Second Edition, Springer, 2003.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see GrayscaleFillholeImageFilter" } diff --git a/Code/BasicFilters/json/BinaryGrindPeakImageFilter.json b/Code/BasicFilters/json/BinaryGrindPeakImageFilter.json index cf4c1796e..f00f67aaf 100644 --- a/Code/BasicFilters/json/BinaryGrindPeakImageFilter.json +++ b/Code/BasicFilters/json/BinaryGrindPeakImageFilter.json @@ -76,5 +76,5 @@ } ], "briefdescription" : "Remove the objects not connected to the boundary of the image.", - "detaileddescription" : "BinaryGrindPeakImageFilter ginds peaks in a grayscale image.\n\nGeodesic morphology and the grind peak algorithm is described in Chapter 6 of Pierre Soille's book \"Morphological Image Analysis:\nPrinciples and Applications\", Second Edition, Springer, 2003.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see GrayscaleGrindPeakImageFilter" + "detaileddescription" : "BinaryGrindPeakImageFilter ginds peaks in a grayscale image.\n\nGeodesic morphology and the grind peak algorithm is described in Chapter 6 of Pierre Soille's book \"Morphological Image Analysis:\nPrinciples and Applications\", Second Edition, Springer, 2003.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see GrayscaleGrindPeakImageFilter" } diff --git a/Code/BasicFilters/json/BinaryImageToLabelMapFilter.json b/Code/BasicFilters/json/BinaryImageToLabelMapFilter.json index e3a296ca6..903727c40 100644 --- a/Code/BasicFilters/json/BinaryImageToLabelMapFilter.json +++ b/Code/BasicFilters/json/BinaryImageToLabelMapFilter.json @@ -22,9 +22,9 @@ "default" : "1.0", "pixeltype" : "Input", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set/Get the value to be consider \"foreground\" in the input image. Defaults to NumericTraits::max().", + "detaileddescriptionSet" : "Set/Get the value to be consider \"foreground\" in the input image. Defaults to NumericTraits::max() .", "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Set/Get the value to be consider \"foreground\" in the input image. Defaults to NumericTraits::max()." + "detaileddescriptionGet" : "Set/Get the value to be consider \"foreground\" in the input image. Defaults to NumericTraits::max() ." }, { "name" : "OutputBackgroundValue", @@ -32,9 +32,9 @@ "default" : "0.0", "pixeltype" : "Output", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::NonpositiveMin().", + "detaileddescriptionSet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::NonpositiveMin() .", "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::NonpositiveMin()." + "detaileddescriptionGet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::NonpositiveMin() ." } ], "tests" : [ @@ -74,5 +74,5 @@ } ], "briefdescription" : "Label the connected components in a binary image and produce a collection of label objects.", - "detaileddescription" : "BinaryImageToLabelMapFilter labels the objects in a binary image. Each distinct object is assigned a unique label. The final object labels start with 1 and are consecutive. Objects that are reached earlier by a raster order scan have a lower label.\n\nThe GetOutput() function of this class returns an itk::LabelMap .\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ConnectedComponentImageFilter , LabelImageToLabelMapFilter , LabelMap , LabelObject \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Label binary regions in an image" + "detaileddescription" : "BinaryImageToLabelMapFilter labels the objects in a binary image. Each distinct object is assigned a unique label. The final object labels start with 1 and are consecutive. Objects that are reached earlier by a raster order scan have a lower label.\n\nThe GetOutput() function of this class returns an itk::LabelMap .\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ConnectedComponentImageFilter , LabelImageToLabelMapFilter , LabelMap , LabelObject \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Label binary regions in an image" } diff --git a/Code/BasicFilters/json/BinaryMorphologicalClosingImageFilter.json b/Code/BasicFilters/json/BinaryMorphologicalClosingImageFilter.json index 91165d32f..cf96d5159 100644 --- a/Code/BasicFilters/json/BinaryMorphologicalClosingImageFilter.json +++ b/Code/BasicFilters/json/BinaryMorphologicalClosingImageFilter.json @@ -93,5 +93,5 @@ } ], "briefdescription" : "binary morphological closing of an image.", - "detaileddescription" : "This filter removes small (i.e., smaller than the structuring element) holes and tube like structures in the interior or at the boundaries of the image. The morphological closing of an image \"f\" is defined as: Closing(f) = Erosion(Dilation(f)).\n\nThe structuring element is assumed to be composed of binary values (zero or one). Only elements of the structuring element having values > 0 are candidates for affecting the center pixel.\n\nThis code was contributed in the Insight Journal paper: \"Binary morphological closing and opening image filters\" by Lehmann G. http://hdl.handle.net/1926/141 http://www.insight-journal.org/browse/publication/58 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see MorphologyImageFilter , GrayscaleDilateImageFilter , GrayscaleErodeImageFilter" + "detaileddescription" : "This filter removes small (i.e., smaller than the structuring element) holes and tube like structures in the interior or at the boundaries of the image. The morphological closing of an image \"f\" is defined as: Closing(f) = Erosion(Dilation(f)).\n\nThe structuring element is assumed to be composed of binary values (zero or one). Only elements of the structuring element having values > 0 are candidates for affecting the center pixel.\n\nThis code was contributed in the Insight Journal paper: \"Binary morphological closing and opening image filters\" by Lehmann G. https://hdl.handle.net/1926/141 http://www.insight-journal.org/browse/publication/58 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see MorphologyImageFilter , GrayscaleDilateImageFilter , GrayscaleErodeImageFilter" } diff --git a/Code/BasicFilters/json/BinaryMorphologicalOpeningImageFilter.json b/Code/BasicFilters/json/BinaryMorphologicalOpeningImageFilter.json index 56ca62291..54c7f8ebc 100644 --- a/Code/BasicFilters/json/BinaryMorphologicalOpeningImageFilter.json +++ b/Code/BasicFilters/json/BinaryMorphologicalOpeningImageFilter.json @@ -61,5 +61,5 @@ } ], "briefdescription" : "binary morphological opening of an image.", - "detaileddescription" : "This filter removes small (i.e., smaller than the structuring element) structures in the interior or at the boundaries of the image. The morphological opening of an image \"f\" is defined as: Opening(f) = Dilatation(Erosion(f)).\n\nThe structuring element is assumed to be composed of binary values (zero or one). Only elements of the structuring element having values > 0 are candidates for affecting the center pixel.\n\nThis code was contributed in the Insight Journal paper: \"Binary morphological closing and opening image filters\" by Lehmann G. http://hdl.handle.net/1926/141 http://www.insight-journal.org/browse/publication/58 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see MorphologyImageFilter , GrayscaleDilateImageFilter , GrayscaleErodeImageFilter" + "detaileddescription" : "This filter removes small (i.e., smaller than the structuring element) structures in the interior or at the boundaries of the image. The morphological opening of an image \"f\" is defined as: Opening(f) = Dilatation(Erosion(f)).\n\nThe structuring element is assumed to be composed of binary values (zero or one). Only elements of the structuring element having values > 0 are candidates for affecting the center pixel.\n\nThis code was contributed in the Insight Journal paper: \"Binary morphological closing and opening image filters\" by Lehmann G. https://hdl.handle.net/1926/141 http://www.insight-journal.org/browse/publication/58 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see MorphologyImageFilter , GrayscaleDilateImageFilter , GrayscaleErodeImageFilter" } diff --git a/Code/BasicFilters/json/BinaryNotImageFilter.json b/Code/BasicFilters/json/BinaryNotImageFilter.json index fba562f85..fc2729125 100644 --- a/Code/BasicFilters/json/BinaryNotImageFilter.json +++ b/Code/BasicFilters/json/BinaryNotImageFilter.json @@ -54,5 +54,5 @@ } ], "briefdescription" : "Implements the BinaryNot logical operator pixel-wise between two images.", - "detaileddescription" : "This class is parametrized over the types of the two input images and the type of the output image. Numeric conversions (castings) are done by the C++ defaults.\n\nThe total operation over one pixel will be\n\noutput_pixel = static_cast( input1_pixel != input2_pixel )\n\nWhere \"!=\" is the equality operator in C++.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Invert an image using the Binary Not operation" + "detaileddescription" : "This class is parametrized over the types of the two input images and the type of the output image. Numeric conversions (castings) are done by the C++ defaults.\n\nThe total operation over one pixel will be\n\noutput_pixel = static_cast( input1_pixel != input2_pixel )\n\nWhere \"!=\" is the equality operator in C++.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Invert an image using the Binary Not operation" } diff --git a/Code/BasicFilters/json/BinaryOpeningByReconstructionImageFilter.json b/Code/BasicFilters/json/BinaryOpeningByReconstructionImageFilter.json index 457fd3b29..e01452a4a 100644 --- a/Code/BasicFilters/json/BinaryOpeningByReconstructionImageFilter.json +++ b/Code/BasicFilters/json/BinaryOpeningByReconstructionImageFilter.json @@ -72,5 +72,5 @@ } ], "briefdescription" : "binary morphological closing of an image.", - "detaileddescription" : "This filter removes small (i.e., smaller than the structuring element) objects in the image. It is defined as: Opening(f) = ReconstructionByDilatation(Erosion(f)).\n\nThe structuring element is assumed to be composed of binary values (zero or one). Only elements of the structuring element having values > 0 are candidates for affecting the center pixel.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see MorphologyImageFilter , OpeningByReconstructionImageFilter , BinaryClosingByReconstructionImageFilter" + "detaileddescription" : "This filter removes small (i.e., smaller than the structuring element) objects in the image. It is defined as: Opening(f) = ReconstructionByDilatation(Erosion(f)).\n\nThe structuring element is assumed to be composed of binary values (zero or one). Only elements of the structuring element having values > 0 are candidates for affecting the center pixel.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see MorphologyImageFilter , OpeningByReconstructionImageFilter , BinaryClosingByReconstructionImageFilter" } diff --git a/Code/BasicFilters/json/BinaryProjectionImageFilter.json b/Code/BasicFilters/json/BinaryProjectionImageFilter.json index ddd2a68d1..5f14356af 100644 --- a/Code/BasicFilters/json/BinaryProjectionImageFilter.json +++ b/Code/BasicFilters/json/BinaryProjectionImageFilter.json @@ -62,5 +62,5 @@ } ], "briefdescription" : "Binary projection.", - "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. The original paper can be found at http://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see MedianProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter" + "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. The original paper can be found at https://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see MedianProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter" } diff --git a/Code/BasicFilters/json/BinaryReconstructionByDilationImageFilter.json b/Code/BasicFilters/json/BinaryReconstructionByDilationImageFilter.json index 6aa06df29..08660bd86 100644 --- a/Code/BasicFilters/json/BinaryReconstructionByDilationImageFilter.json +++ b/Code/BasicFilters/json/BinaryReconstructionByDilationImageFilter.json @@ -58,5 +58,5 @@ } ], "briefdescription" : "binary reconstruction by dilation of an image", - "detaileddescription" : "Reconstruction by dilation operates on a \"marker\" image and a \"mask\" image, and is defined as the dilation of the marker image with respect to the mask image iterated until stability.\n\nGeodesic morphology is described in Chapter 6.2 of Pierre Soille's book \"Morphological Image Analysis: Principles and Applications\", Second Edition, Springer, 2003.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see MorphologyImageFilter , ReconstructionByDilationImageFilter , BinaryReconstructionByErosionImageFilter" + "detaileddescription" : "Reconstruction by dilation operates on a \"marker\" image and a \"mask\" image, and is defined as the dilation of the marker image with respect to the mask image iterated until stability.\n\nGeodesic morphology is described in Chapter 6.2 of Pierre Soille's book \"Morphological Image Analysis: Principles and Applications\", Second Edition, Springer, 2003.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see MorphologyImageFilter , ReconstructionByDilationImageFilter , BinaryReconstructionByErosionImageFilter" } diff --git a/Code/BasicFilters/json/BinaryReconstructionByErosionImageFilter.json b/Code/BasicFilters/json/BinaryReconstructionByErosionImageFilter.json index fab4ba35f..f2720e900 100644 --- a/Code/BasicFilters/json/BinaryReconstructionByErosionImageFilter.json +++ b/Code/BasicFilters/json/BinaryReconstructionByErosionImageFilter.json @@ -58,5 +58,5 @@ } ], "briefdescription" : "binary reconstruction by erosion of an image", - "detaileddescription" : "Reconstruction by erosion operates on a \"marker\" image and a \"mask\" image, and is defined as the erosion of the marker image with respect to the mask image iterated until stability.\n\nGeodesic morphology is described in Chapter 6.2 of Pierre Soille's book \"Morphological Image Analysis: Principles and Applications\", Second Edition, Springer, 2003.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see MorphologyImageFilter , ReconstructionByErosionImageFilter , BinaryReconstructionByDilationImageFilter" + "detaileddescription" : "Reconstruction by erosion operates on a \"marker\" image and a \"mask\" image, and is defined as the erosion of the marker image with respect to the mask image iterated until stability.\n\nGeodesic morphology is described in Chapter 6.2 of Pierre Soille's book \"Morphological Image Analysis: Principles and Applications\", Second Edition, Springer, 2003.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see MorphologyImageFilter , ReconstructionByErosionImageFilter , BinaryReconstructionByDilationImageFilter" } diff --git a/Code/BasicFilters/json/BinaryThresholdImageFilter.json b/Code/BasicFilters/json/BinaryThresholdImageFilter.json index 29dfbb4e2..6d8dd8959 100644 --- a/Code/BasicFilters/json/BinaryThresholdImageFilter.json +++ b/Code/BasicFilters/json/BinaryThresholdImageFilter.json @@ -43,7 +43,7 @@ "default" : "0u", "pixeltype" : "Output", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set the \"outside\" pixel value. The default value NumericTraits::Zero .", + "detaileddescriptionSet" : "Set the \"outside\" pixel value. The default value NumericTraits::ZeroValue() .", "briefdescriptionGet" : "", "detaileddescriptionGet" : "Get the \"outside\" pixel value." } diff --git a/Code/BasicFilters/json/BinaryThresholdProjectionImageFilter.json b/Code/BasicFilters/json/BinaryThresholdProjectionImageFilter.json index 5c6e4f0a9..dfa7a5472 100644 --- a/Code/BasicFilters/json/BinaryThresholdProjectionImageFilter.json +++ b/Code/BasicFilters/json/BinaryThresholdProjectionImageFilter.json @@ -78,5 +78,5 @@ } ], "briefdescription" : "BinaryThreshold projection.", - "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. the original paper can be found at http://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see MedianProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter" + "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. the original paper can be found at https://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see MedianProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter" } diff --git a/Code/BasicFilters/json/BoxMeanImageFilter.json b/Code/BasicFilters/json/BoxMeanImageFilter.json index fa51f9d9e..9d02b5284 100644 --- a/Code/BasicFilters/json/BoxMeanImageFilter.json +++ b/Code/BasicFilters/json/BoxMeanImageFilter.json @@ -68,5 +68,5 @@ } ], "briefdescription" : "Implements a fast rectangular mean filter using the accumulator approach.", - "detaileddescription" : "This code was contributed in the Insight Journal paper: \"Efficient implementation of kernel filtering\" by Beare R., Lehmann G http://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 \n\n\\author Richard Beare" + "detaileddescription" : "This code was contributed in the Insight Journal paper: \"Efficient implementation of kernel filtering\" by Beare R., Lehmann G https://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 \n\n\\author Richard Beare" } diff --git a/Code/BasicFilters/json/BoxSigmaImageFilter.json b/Code/BasicFilters/json/BoxSigmaImageFilter.json index 964afb7b8..7cc670687 100644 --- a/Code/BasicFilters/json/BoxSigmaImageFilter.json +++ b/Code/BasicFilters/json/BoxSigmaImageFilter.json @@ -68,5 +68,5 @@ } ], "briefdescription" : "Implements a fast rectangular sigma filter using the accumulator approach.", - "detaileddescription" : "This code was contributed in the Insight Journal paper: \"Efficient implementation of kernel filtering\" by Beare R., Lehmann G http://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 \n\n\\author Gaetan Lehmann" + "detaileddescription" : "This code was contributed in the Insight Journal paper: \"Efficient implementation of kernel filtering\" by Beare R., Lehmann G https://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 \n\n\\author Gaetan Lehmann" } diff --git a/Code/BasicFilters/json/ChangeLabelLabelMapFilter.json b/Code/BasicFilters/json/ChangeLabelLabelMapFilter.json index 6c3696bf5..4f0a69866 100644 --- a/Code/BasicFilters/json/ChangeLabelLabelMapFilter.json +++ b/Code/BasicFilters/json/ChangeLabelLabelMapFilter.json @@ -33,5 +33,5 @@ } ], "briefdescription" : "Replace the label Ids of selected LabelObjects with new label Ids.", - "detaileddescription" : "This filter takes as input a label map and a list of pairs of Label Ids, to produce as output a new label map where the label Ids have been replaced according to the pairs in the list.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ShapeLabelObject , RelabelComponentImageFilter" + "detaileddescription" : "This filter takes as input a label map and a list of pairs of Label Ids, to produce as output a new label map where the label Ids have been replaced according to the pairs in the list.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ShapeLabelObject , RelabelComponentImageFilter" } diff --git a/Code/BasicFilters/json/ConnectedComponentImageFilter.json b/Code/BasicFilters/json/ConnectedComponentImageFilter.json index 0d761512c..fd4de53aa 100644 --- a/Code/BasicFilters/json/ConnectedComponentImageFilter.json +++ b/Code/BasicFilters/json/ConnectedComponentImageFilter.json @@ -24,7 +24,7 @@ "type" : "uint32_t", "default" : "0u", "briefdescriptionGet" : "", - "detaileddescriptionGet" : "After the filter is executed, holds the number of connected components." + "detaileddescriptionGet" : "" } ], "custom_methods" : [], @@ -62,5 +62,5 @@ } ], "briefdescription" : "Label the objects in a binary image.", - "detaileddescription" : "ConnectedComponentImageFilter labels the objects in a binary image (non-zero pixels are considered to be objects, zero-valued pixels are considered to be background). Each distinct object is assigned a unique label. The filter experiments with some improvements to the existing implementation, and is based on run length encoding along raster lines. The final object labels start with 1 and are consecutive. Objects that are reached earlier by a raster order scan have a lower label. This is different to the behaviour of the original connected component image filter which did not produce consecutive labels or impose any particular ordering.\n\n\\see ImageToImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Label connected components in a binary image" + "detaileddescription" : "ConnectedComponentImageFilter labels the objects in a binary image (non-zero pixels are considered to be objects, zero-valued pixels are considered to be background). Each distinct object is assigned a unique label. The filter experiments with some improvements to the existing implementation, and is based on run length encoding along raster lines. The final object labels start with 1 and are consecutive. Objects that are reached earlier by a raster order scan have a lower label. This is different to the behaviour of the original connected component image filter which did not produce consecutive labels or impose any particular ordering.\n\nAfter the filter is executed, ObjectCount holds the number of connected components.\n\n\\see ImageToImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Label connected components in a binary image" } diff --git a/Code/BasicFilters/json/ConvolutionImageFilter.json b/Code/BasicFilters/json/ConvolutionImageFilter.json index 6ffa6b7c8..3d78468b9 100644 --- a/Code/BasicFilters/json/ConvolutionImageFilter.json +++ b/Code/BasicFilters/json/ConvolutionImageFilter.json @@ -53,5 +53,5 @@ } ], "briefdescription" : "Convolve a given image with an arbitrary image kernel.", - "detaileddescription" : "This filter operates by centering the flipped kernel at each pixel in the image and computing the inner product between pixel values in the image and pixel values in the kernel. The center of the kernel is defined as\\f$ \\lfloor (2*i+s-1)/2 \\rfloor \\f$ where\\f$i\\f$ is the index and\\f$s\\f$ is the size of the largest possible region of the kernel image. For kernels with odd sizes in all dimensions, this corresponds to the center pixel. If a dimension of the kernel image has an even size, then the center index of the kernel in that dimension will be the largest integral index that is less than the continuous index of the image center.\n\nThe kernel can optionally be normalized to sum to 1 using NormalizeOn() . Normalization is off by default.\n\n\\warning This filter ignores the spacing, origin, and orientation of the kernel image and treats them as identical to those in the input image.\n\nThis code was contributed in the Insight Journal paper:\n\n\"Image Kernel Convolution\" by Tustison N., Gee J. http://hdl.handle.net/1926/1323 http://www.insight-journal.org/browse/publication/208 \n\n\\author Nicholas J. Tustison\n\nJames C. Gee\n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Convolve an image with a kernel" + "detaileddescription" : "This filter operates by centering the flipped kernel at each pixel in the image and computing the inner product between pixel values in the image and pixel values in the kernel. The center of the kernel is defined as\\f$ \\lfloor (2*i+s-1)/2 \\rfloor \\f$ where\\f$i\\f$ is the index and\\f$s\\f$ is the size of the largest possible region of the kernel image. For kernels with odd sizes in all dimensions, this corresponds to the center pixel. If a dimension of the kernel image has an even size, then the center index of the kernel in that dimension will be the largest integral index that is less than the continuous index of the image center.\n\nThe kernel can optionally be normalized to sum to 1 using NormalizeOn() . Normalization is off by default.\n\n\\warning This filter ignores the spacing, origin, and orientation of the kernel image and treats them as identical to those in the input image.\n\nThis code was contributed in the Insight Journal paper:\n\n\"Image Kernel Convolution\" by Tustison N., Gee J. https://hdl.handle.net/1926/1323 http://www.insight-journal.org/browse/publication/208 \n\n\\author Nicholas J. Tustison\n\nJames C. Gee\n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Convolve an image with a kernel" } diff --git a/Code/BasicFilters/json/DerivativeImageFilter.json b/Code/BasicFilters/json/DerivativeImageFilter.json index 50e9911af..2f7623689 100644 --- a/Code/BasicFilters/json/DerivativeImageFilter.json +++ b/Code/BasicFilters/json/DerivativeImageFilter.json @@ -12,18 +12,18 @@ "type" : "unsigned int", "default" : "0u", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Standard get/set macros for filter parameters.", + "detaileddescriptionSet" : "The output pixel type must be signed. Standard get/set macros for filter parameters.", "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Standard get/set macros for filter parameters." + "detaileddescriptionGet" : "The output pixel type must be signed. Standard get/set macros for filter parameters." }, { "name" : "Order", "type" : "unsigned int", "default" : "1u", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Standard get/set macros for filter parameters.", + "detaileddescriptionSet" : "The output pixel type must be signed. Standard get/set macros for filter parameters.", "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Standard get/set macros for filter parameters." + "detaileddescriptionGet" : "The output pixel type must be signed. Standard get/set macros for filter parameters." }, { "name" : "UseImageSpacing", diff --git a/Code/BasicFilters/json/DiffeomorphicDemonsRegistrationFilter.json b/Code/BasicFilters/json/DiffeomorphicDemonsRegistrationFilter.json index 53a94e4a1..cb7693df0 100644 --- a/Code/BasicFilters/json/DiffeomorphicDemonsRegistrationFilter.json +++ b/Code/BasicFilters/json/DiffeomorphicDemonsRegistrationFilter.json @@ -216,5 +216,5 @@ } ], "briefdescription" : "Deformably register two images using a diffeomorphic demons algorithm.", - "detaileddescription" : "This class was contributed by Tom Vercauteren, INRIA & Mauna Kea Technologies, based on a variation of the DemonsRegistrationFilter . The basic modification is to use diffeomorphism exponentials.\n\nSee T. Vercauteren, X. Pennec, A. Perchant and N. Ayache, \"Non-parametric Diffeomorphic Image Registration with the Demons Algorithm\", Proc. of MICCAI 2007.\n\nDiffeomorphicDemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the deformation field which will map a moving image onto a fixed image.\n\nA deformation field is represented as a image whose pixel type is some vector type with at least N elements, where N is the dimension of the fixed image. The vector type must support element access via operator []. It is assumed that the vector elements behave like floating point scalars.\n\nThis class is templated over the fixed image type, moving image type and the deformation field type.\n\nThe input fixed and moving images are set via methods SetFixedImage and SetMovingImage respectively. An initial deformation field maybe set via SetInitialDisplacementField or SetInput. If no initial field is set, a zero field is used as the initial condition.\n\nThe output deformation field can be obtained via methods GetOutput or GetDisplacementField.\n\nThis class make use of the finite difference solver hierarchy. Update for each iteration is computed in DemonsRegistrationFunction .\n\n\\author Tom Vercauteren, INRIA & Mauna Kea Technologies\n\n\\warning This filter assumes that the fixed image type, moving image type and deformation field type all have the same number of dimensions.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/510 \n\n\\see DemonsRegistrationFilter \n\\see \n\\see DemonsRegistrationFunction" + "detaileddescription" : "This class was contributed by Tom Vercauteren, INRIA & Mauna Kea Technologies, based on a variation of the DemonsRegistrationFilter . The basic modification is to use diffeomorphism exponentials.\n\nSee T. Vercauteren, X. Pennec, A. Perchant and N. Ayache, \"Non-parametric Diffeomorphic Image Registration with the Demons Algorithm\", Proc. of MICCAI 2007.\n\nDiffeomorphicDemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the deformation field which will map a moving image onto a fixed image.\n\nA deformation field is represented as a image whose pixel type is some vector type with at least N elements, where N is the dimension of the fixed image. The vector type must support element access via operator []. It is assumed that the vector elements behave like floating point scalars.\n\nThis class is templated over the fixed image type, moving image type and the deformation field type.\n\nThe input fixed and moving images are set via methods SetFixedImage and SetMovingImage respectively. An initial deformation field maybe set via SetInitialDisplacementField or SetInput. If no initial field is set, a zero field is used as the initial condition.\n\nThe output deformation field can be obtained via methods GetOutput or GetDisplacementField.\n\nThis class make use of the finite difference solver hierarchy. Update for each iteration is computed in DemonsRegistrationFunction .\n\n\\author Tom Vercauteren, INRIA & Mauna Kea Technologies\n\n\\warning This filter assumes that the fixed image type, moving image type and deformation field type all have the same number of dimensions.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/510 \n\n\\see DemonsRegistrationFilter \n\\see \n\\see DemonsRegistrationFunction" } diff --git a/Code/BasicFilters/json/DiscreteGaussianDerivativeImageFilter.json b/Code/BasicFilters/json/DiscreteGaussianDerivativeImageFilter.json index 3564a23cd..2d4a74336 100644 --- a/Code/BasicFilters/json/DiscreteGaussianDerivativeImageFilter.json +++ b/Code/BasicFilters/json/DiscreteGaussianDerivativeImageFilter.json @@ -145,5 +145,5 @@ } ], "briefdescription" : "Calculates image derivatives using discrete derivative gaussian kernels. This filter calculates Gaussian derivative by separable convolution of an image and a discrete Gaussian derivative operator (kernel).", - "detaileddescription" : "The Gaussian operators used here were described by Tony Lindeberg (Discrete Scale-Space Theory and the Scale-Space Primal Sketch. Dissertation. Royal Institute of Technology, Stockholm, Sweden. May 1991.)\n\nThe variance or standard deviation (sigma) will be evaluated as pixel units if SetUseImageSpacing is off (false) or as physical units if SetUseImageSpacing is on (true, default). The variance can be set independently in each dimension.\n\nWhen the Gaussian kernel is small, this filter tends to run faster than itk::RecursiveGaussianImageFilter .\n\n\\author Ivan Macia, VICOMTech, Spain, http://www.vicomtech.es \n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/1290 \n\n\\see GaussianDerivativeOperator \n\\see \n\\see Image \n\\see \n\\see Neighborhood \n\\see \n\\see NeighborhoodOperator" + "detaileddescription" : "The Gaussian operators used here were described by Tony Lindeberg (Discrete Scale-Space Theory and the Scale-Space Primal Sketch. Dissertation. Royal Institute of Technology, Stockholm, Sweden. May 1991.)\n\nThe variance or standard deviation (sigma) will be evaluated as pixel units if SetUseImageSpacing is off (false) or as physical units if SetUseImageSpacing is on (true, default). The variance can be set independently in each dimension.\n\nWhen the Gaussian kernel is small, this filter tends to run faster than itk::RecursiveGaussianImageFilter .\n\n\\author Ivan Macia, VICOMTech, Spain, http://www.vicomtech.es \n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/1290 \n\n\\see GaussianDerivativeOperator \n\\see \n\\see Image \n\\see \n\\see Neighborhood \n\\see \n\\see NeighborhoodOperator" } diff --git a/Code/BasicFilters/json/DoubleThresholdImageFilter.json b/Code/BasicFilters/json/DoubleThresholdImageFilter.json index 0c2c101fa..988a99198 100644 --- a/Code/BasicFilters/json/DoubleThresholdImageFilter.json +++ b/Code/BasicFilters/json/DoubleThresholdImageFilter.json @@ -63,7 +63,7 @@ "default" : "0u", "pixeltype" : "Output", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set the \"outside\" pixel value. The default value NumericTraits::Zero .", + "detaileddescriptionSet" : "Set the \"outside\" pixel value. The default value NumericTraits::ZeroValue() .", "briefdescriptionGet" : "", "detaileddescriptionGet" : "Get the \"outside\" pixel value." }, diff --git a/Code/BasicFilters/json/FFTConvolutionImageFilter.json b/Code/BasicFilters/json/FFTConvolutionImageFilter.json index ff8b4594d..531df1c20 100644 --- a/Code/BasicFilters/json/FFTConvolutionImageFilter.json +++ b/Code/BasicFilters/json/FFTConvolutionImageFilter.json @@ -53,5 +53,5 @@ } ], "briefdescription" : "Convolve a given image with an arbitrary image kernel using multiplication in the Fourier domain.", - "detaileddescription" : "This filter produces output equivalent to the output of the ConvolutionImageFilter . However, it takes advantage of the convolution theorem to accelerate the convolution computation when the kernel is large.\n\n\\warning This filter ignores the spacing, origin, and orientation of the kernel image and treats them as identical to those in the input image.\n\nThis code was adapted from the Insight Journal contribution:\n\n\"FFT Based Convolution\" by Gaetan Lehmann http://hdl.handle.net/10380/3154 \n\n\\see ConvolutionImageFilter" + "detaileddescription" : "This filter produces output equivalent to the output of the ConvolutionImageFilter . However, it takes advantage of the convolution theorem to accelerate the convolution computation when the kernel is large.\n\n\\warning This filter ignores the spacing, origin, and orientation of the kernel image and treats them as identical to those in the input image.\n\nThis code was adapted from the Insight Journal contribution:\n\n\"FFT Based Convolution\" by Gaetan Lehmann https://hdl.handle.net/10380/3154 \n\n\\see ConvolutionImageFilter" } diff --git a/Code/BasicFilters/json/FFTPadImageFilter.json b/Code/BasicFilters/json/FFTPadImageFilter.json index 9cd899d33..c1e5bb866 100644 --- a/Code/BasicFilters/json/FFTPadImageFilter.json +++ b/Code/BasicFilters/json/FFTPadImageFilter.json @@ -65,5 +65,5 @@ } ], "briefdescription" : "Pad an image to make it suitable for an FFT transformation.", - "detaileddescription" : "FFT filters usually requires a specific image size. The size is decomposed in several prime factors, and the filter only supports prime factors up to a maximum value. This filter automatically finds the greatest prime factor required by the available implementation and pads the input appropriately.\n\nThis code was adapted from the Insight Journal contribution:\n\n\"FFT Based Convolution\" by Gaetan Lehmann http://hdl.handle.net/10380/3154 \n\n\\author Gaetan Lehmann\n\n\\see FFTShiftImageFilter" + "detaileddescription" : "FFT filters usually requires a specific image size. The size is decomposed in several prime factors, and the filter only supports prime factors up to a maximum value. This filter automatically finds the greatest prime factor required by the available implementation and pads the input appropriately.\n\nThis code was adapted from the Insight Journal contribution:\n\n\"FFT Based Convolution\" by Gaetan Lehmann https://hdl.handle.net/10380/3154 \n\n\\author Gaetan Lehmann\n\n\\see FFTShiftImageFilter" } diff --git a/Code/BasicFilters/json/FFTShiftImageFilter.json b/Code/BasicFilters/json/FFTShiftImageFilter.json index 70309f752..291780a8a 100644 --- a/Code/BasicFilters/json/FFTShiftImageFilter.json +++ b/Code/BasicFilters/json/FFTShiftImageFilter.json @@ -38,5 +38,5 @@ } ], "briefdescription" : "Shift the zero-frequency components of a Fourier transfrom to the center of the image.", - "detaileddescription" : "The Fourier transform produces an image where the zero frequency components are in the corner of the image, making it difficult to understand. This filter shifts the component to the center of the image.\n\n\\note For images with an odd-sized dimension, applying this filter twice will not produce the same image as the original one without using SetInverse(true) on one (and only one) of the two filters.\n\n http://hdl.handle.net/1926/321 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ForwardFFTImageFilter , InverseFFTImageFilter" + "detaileddescription" : "The Fourier transform produces an image where the zero frequency components are in the corner of the image, making it difficult to understand. This filter shifts the component to the center of the image.\n\n\\note For images with an odd-sized dimension, applying this filter twice will not produce the same image as the original one without using SetInverse(true) on one (and only one) of the two filters.\n\n https://hdl.handle.net/1926/321 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ForwardFFTImageFilter , InverseFFTImageFilter" } diff --git a/Code/BasicFilters/json/FastApproximateRankImageFilter.json b/Code/BasicFilters/json/FastApproximateRankImageFilter.json index 9e6e4bf6f..48ae71706 100644 --- a/Code/BasicFilters/json/FastApproximateRankImageFilter.json +++ b/Code/BasicFilters/json/FastApproximateRankImageFilter.json @@ -71,5 +71,5 @@ } ], "briefdescription" : "A separable rank filter.", - "detaileddescription" : "Medians aren't separable, but if you want a large robust smoother to be relatively quick then it is worthwhile pretending that they are.\n\nThis code was contributed in the Insight Journal paper: \"Efficient implementation of kernel filtering\" by Beare R., Lehmann G http://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 \n\n\\author Richard Beare" + "detaileddescription" : "Medians aren't separable, but if you want a large robust smoother to be relatively quick then it is worthwhile pretending that they are.\n\nThis code was contributed in the Insight Journal paper: \"Efficient implementation of kernel filtering\" by Beare R., Lehmann G https://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 \n\n\\author Richard Beare" } diff --git a/Code/BasicFilters/json/FastSymmetricForcesDemonsRegistrationFilter.json b/Code/BasicFilters/json/FastSymmetricForcesDemonsRegistrationFilter.json index 373ecab8f..b125af03f 100644 --- a/Code/BasicFilters/json/FastSymmetricForcesDemonsRegistrationFilter.json +++ b/Code/BasicFilters/json/FastSymmetricForcesDemonsRegistrationFilter.json @@ -207,5 +207,5 @@ } ], "briefdescription" : "Deformably register two images using a symmetric forces demons algorithm.", - "detaileddescription" : "This class was contributed by Tom Vercauteren, INRIA & Mauna Kea Technologies based on a variation of the DemonsRegistrationFilter .\n\nFastSymmetricForcesDemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the deformation field which will map a moving image onto a fixed image.\n\nA deformation field is represented as a image whose pixel type is some vector type with at least N elements, where N is the dimension of the fixed image. The vector type must support element access via operator []. It is assumed that the vector elements behave like floating point scalars.\n\nThis class is templated over the fixed image type, moving image type and the deformation field type.\n\nThe input fixed and moving images are set via methods SetFixedImage and SetMovingImage respectively. An initial deformation field maybe set via SetInitialDisplacementField or SetInput. If no initial field is set, a zero field is used as the initial condition.\n\nThe output deformation field can be obtained via methods GetOutput or GetDisplacementField.\n\nThis class make use of the finite difference solver hierarchy. Update for each iteration is computed in DemonsRegistrationFunction .\n\n\\author Tom Vercauteren, INRIA & Mauna Kea Technologies\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/510 \n\n\\warning This filter assumes that the fixed image type, moving image type and deformation field type all have the same number of dimensions.\n\n\\see DemonsRegistrationFilter \n\\see \n\\see DemonsRegistrationFunction" + "detaileddescription" : "This class was contributed by Tom Vercauteren, INRIA & Mauna Kea Technologies based on a variation of the DemonsRegistrationFilter .\n\nFastSymmetricForcesDemonsRegistrationFilter implements the demons deformable algorithm that register two images by computing the deformation field which will map a moving image onto a fixed image.\n\nA deformation field is represented as a image whose pixel type is some vector type with at least N elements, where N is the dimension of the fixed image. The vector type must support element access via operator []. It is assumed that the vector elements behave like floating point scalars.\n\nThis class is templated over the fixed image type, moving image type and the deformation field type.\n\nThe input fixed and moving images are set via methods SetFixedImage and SetMovingImage respectively. An initial deformation field maybe set via SetInitialDisplacementField or SetInput. If no initial field is set, a zero field is used as the initial condition.\n\nThe output deformation field can be obtained via methods GetOutput or GetDisplacementField.\n\nThis class make use of the finite difference solver hierarchy. Update for each iteration is computed in DemonsRegistrationFunction .\n\n\\author Tom Vercauteren, INRIA & Mauna Kea Technologies\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/510 \n\n\\warning This filter assumes that the fixed image type, moving image type and deformation field type all have the same number of dimensions.\n\n\\see DemonsRegistrationFilter \n\\see \n\\see DemonsRegistrationFunction" } diff --git a/Code/BasicFilters/json/GaborImageSource.json b/Code/BasicFilters/json/GaborImageSource.json index fb23adf0d..b4ce82a4a 100644 --- a/Code/BasicFilters/json/GaborImageSource.json +++ b/Code/BasicFilters/json/GaborImageSource.json @@ -87,5 +87,5 @@ } ], "briefdescription" : "Generate an n-dimensional image of a Gabor filter.", - "detaileddescription" : "GaborImageSource generates an image of either the real (i.e. symmetric) or complex (i.e. antisymmetric) part of the Gabor filter with the orientation directed along the x-axis. The GaborKernelFunction is used to evaluate the contribution along the x-axis whereas a non-normalized 1-D Gaussian envelope provides the contribution in each of the remaining N dimensions. Orientation can be manipulated via the Transform classes of the toolkit.\n\nThe output image may be of any dimension.\n\nThis implementation was contributed as a paper to the Insight Journal http://hdl.handle.net/1926/500" + "detaileddescription" : "GaborImageSource generates an image of either the real (i.e. symmetric) or complex (i.e. antisymmetric) part of the Gabor filter with the orientation directed along the x-axis. The GaborKernelFunction is used to evaluate the contribution along the x-axis whereas a non-normalized 1-D Gaussian envelope provides the contribution in each of the remaining N dimensions. Orientation can be manipulated via the Transform classes of the toolkit.\n\nThe output image may be of any dimension.\n\nThis implementation was contributed as a paper to the Insight Journal https://hdl.handle.net/1926/500" } diff --git a/Code/BasicFilters/json/GridImageSource.json b/Code/BasicFilters/json/GridImageSource.json index 7094970c6..a1a1964e7 100644 --- a/Code/BasicFilters/json/GridImageSource.json +++ b/Code/BasicFilters/json/GridImageSource.json @@ -96,5 +96,5 @@ } ], "briefdescription" : "Generate an n-dimensional image of a grid.", - "detaileddescription" : "GridImageSource generates an image of a grid. From the abstract... \"Certain classes of images find disparate use amongst members of the ITK community for such purposes as visualization, simulation, testing, etc. Currently there exists two derived classes from the ImageSource class used for generating specific images for various applications, viz. RandomImageSource and GaussianImageSource . We propose to add to this set with the class GridImageSource which, obviously enough, produces a grid image. Such images are useful for visualizing deformation when used in conjunction with the WarpImageFilter , simulating magnetic resonance tagging images, or creating optical illusions with which to amaze your friends.\"\n\nThe output image may be of any dimension.\n\n\\author Tustison N., Avants B., Gee J. University of Pennsylvania\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/475" + "detaileddescription" : "GridImageSource generates an image of a grid. From the abstract... \"Certain classes of images find disparate use amongst members of the ITK community for such purposes as visualization, simulation, testing, etc. Currently there exists two derived classes from the ImageSource class used for generating specific images for various applications, viz. RandomImageSource and GaussianImageSource . We propose to add to this set with the class GridImageSource which, obviously enough, produces a grid image. Such images are useful for visualizing deformation when used in conjunction with the WarpImageFilter , simulating magnetic resonance tagging images, or creating optical illusions with which to amaze your friends.\"\n\nThe output image may be of any dimension.\n\n\\author Tustison N., Avants B., Gee J. University of Pennsylvania\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/475" } diff --git a/Code/BasicFilters/json/HuangThresholdImageFilter.json b/Code/BasicFilters/json/HuangThresholdImageFilter.json index ecadb0a27..5df792631 100644 --- a/Code/BasicFilters/json/HuangThresholdImageFilter.json +++ b/Code/BasicFilters/json/HuangThresholdImageFilter.json @@ -126,5 +126,5 @@ } ], "briefdescription" : "Threshold an image using the Huang Threshold.", - "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the HuangThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" + "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the HuangThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" } diff --git a/Code/BasicFilters/json/IntermodesThresholdImageFilter.json b/Code/BasicFilters/json/IntermodesThresholdImageFilter.json index ca22e122f..01750184e 100644 --- a/Code/BasicFilters/json/IntermodesThresholdImageFilter.json +++ b/Code/BasicFilters/json/IntermodesThresholdImageFilter.json @@ -126,5 +126,5 @@ } ], "briefdescription" : "Threshold an image using the Intermodes Threshold.", - "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the IntermodesThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" + "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the IntermodesThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" } diff --git a/Code/BasicFilters/json/IsoDataThresholdImageFilter.json b/Code/BasicFilters/json/IsoDataThresholdImageFilter.json index 3280645b9..914f993a3 100644 --- a/Code/BasicFilters/json/IsoDataThresholdImageFilter.json +++ b/Code/BasicFilters/json/IsoDataThresholdImageFilter.json @@ -113,5 +113,5 @@ } ], "briefdescription" : "Threshold an image using the IsoData Threshold.", - "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the IsoDataThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" + "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the IsoDataThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" } diff --git a/Code/BasicFilters/json/KittlerIllingworthThresholdImageFilter.json b/Code/BasicFilters/json/KittlerIllingworthThresholdImageFilter.json index bf2afa074..1c11b9ba4 100644 --- a/Code/BasicFilters/json/KittlerIllingworthThresholdImageFilter.json +++ b/Code/BasicFilters/json/KittlerIllingworthThresholdImageFilter.json @@ -126,5 +126,5 @@ } ], "briefdescription" : "Threshold an image using the KittlerIllingworth Threshold.", - "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the KittlerIllingworthThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" + "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the KittlerIllingworthThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" } diff --git a/Code/BasicFilters/json/LabelContourImageFilter.json b/Code/BasicFilters/json/LabelContourImageFilter.json index 53e4527eb..a09121cff 100644 --- a/Code/BasicFilters/json/LabelContourImageFilter.json +++ b/Code/BasicFilters/json/LabelContourImageFilter.json @@ -39,5 +39,5 @@ } ], "briefdescription" : "Labels the pixels on the border of the objects in a labeled image.", - "detaileddescription" : "LabelContourImageFilter takes a labeled image as input, where the pixels in the objects are the pixels with a value different of the BackgroundValue. Only the pixels on the contours of the objects are kept. The pixels not on the border are changed to BackgroundValue. The labels of the object are the same in the input and in the output image.\n\nThe connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours.\n\nhttp://hdl.handle.net/1926/1352 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see BinaryContourImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Label the contours of connected components" + "detaileddescription" : "LabelContourImageFilter takes a labeled image as input, where the pixels in the objects are the pixels with a value different of the BackgroundValue. Only the pixels on the contours of the objects are kept. The pixels not on the border are changed to BackgroundValue. The labels of the object are the same in the input and in the output image.\n\nThe connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours.\n\nhttps://hdl.handle.net/1926/1352 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see BinaryContourImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Label the contours of connected components" } diff --git a/Code/BasicFilters/json/LabelImageToLabelMapFilter.json b/Code/BasicFilters/json/LabelImageToLabelMapFilter.json index 18447d570..c9ba1c805 100644 --- a/Code/BasicFilters/json/LabelImageToLabelMapFilter.json +++ b/Code/BasicFilters/json/LabelImageToLabelMapFilter.json @@ -14,9 +14,9 @@ "doc" : "", "pixeltype" : "Output", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::NonpositiveMin().", + "detaileddescriptionSet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::NonpositiveMin() .", "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::NonpositiveMin()." + "detaileddescriptionGet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::NonpositiveMin() ." } ], "tests" : [ @@ -45,5 +45,5 @@ } ], "briefdescription" : "convert a labeled image to a label collection image", - "detaileddescription" : "LabelImageToLabelMapFilter converts a label image to a label collection image. The labels are the same in the input and the output image.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see BinaryImageToLabelMapFilter , LabelMapToLabelImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Convert an itk::Image consisting of labeled regions to a LabelMap" + "detaileddescription" : "LabelImageToLabelMapFilter converts a label image to a label collection image. The labels are the same in the input and the output image.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see BinaryImageToLabelMapFilter , LabelMapToLabelImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Convert an itk::Image consisting of labeled regions to a LabelMap" } diff --git a/Code/BasicFilters/json/LabelIntensityStatisticsImageFilter.json b/Code/BasicFilters/json/LabelIntensityStatisticsImageFilter.json index 9dcf6a998..a875e6218 100644 --- a/Code/BasicFilters/json/LabelIntensityStatisticsImageFilter.json +++ b/Code/BasicFilters/json/LabelIntensityStatisticsImageFilter.json @@ -731,5 +731,5 @@ } ], "briefdescription" : "a convenient class to convert a label image to a label map and valuate the statistics attributes at once", - "detaileddescription" : "\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see StatisticsLabelObject , LabelStatisticsOpeningImageFilter , LabelStatisticsOpeningImageFilter" + "detaileddescription" : "\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see StatisticsLabelObject , LabelStatisticsOpeningImageFilter , LabelStatisticsOpeningImageFilter" } diff --git a/Code/BasicFilters/json/LabelMapContourOverlayImageFilter.json b/Code/BasicFilters/json/LabelMapContourOverlayImageFilter.json index d08928b9f..4710b7af4 100644 --- a/Code/BasicFilters/json/LabelMapContourOverlayImageFilter.json +++ b/Code/BasicFilters/json/LabelMapContourOverlayImageFilter.json @@ -104,5 +104,5 @@ } ], "briefdescription" : "Apply a colormap to the contours (outlines) of each object in a label map and superimpose it on top of the feature image.", - "detaileddescription" : "The feature image is typically the image from which the labeling was produced. Use the SetInput function to set the LabelMap , and the SetFeatureImage function to set the feature image.\n\nApply a colormap to a label map and put it on top of the input image. The set of colors is a good selection of distinct colors. The opacity of the label map can be defined by the user. A background label produce a gray pixel with the same intensity than the input one.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see LabelMapToBinaryImageFilter , LabelMapToLabelImageFilter , LabelMapOverlayImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Color the boundaries of labeled regions in an image" + "detaileddescription" : "The feature image is typically the image from which the labeling was produced. Use the SetInput function to set the LabelMap , and the SetFeatureImage function to set the feature image.\n\nApply a colormap to a label map and put it on top of the input image. The set of colors is a good selection of distinct colors. The opacity of the label map can be defined by the user. A background label produce a gray pixel with the same intensity than the input one.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see LabelMapToBinaryImageFilter , LabelMapToLabelImageFilter , LabelMapOverlayImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Color the boundaries of labeled regions in an image" } diff --git a/Code/BasicFilters/json/LabelMapMaskImageFilter.json b/Code/BasicFilters/json/LabelMapMaskImageFilter.json index 6396bfae8..3f3dc8851 100644 --- a/Code/BasicFilters/json/LabelMapMaskImageFilter.json +++ b/Code/BasicFilters/json/LabelMapMaskImageFilter.json @@ -37,9 +37,9 @@ "doc" : "", "pixeltype" : "Output", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::Zero .", + "detaileddescriptionSet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::ZeroValue() .", "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::Zero ." + "detaileddescriptionGet" : "Set/Get the value used as \"background\" in the output image. Defaults to NumericTraits::ZeroValue() ." }, { "name" : "Negated", @@ -113,5 +113,5 @@ } ], "briefdescription" : "Mask and image with a LabelMap .", - "detaileddescription" : "LabelMapMaskImageFilter mask the content of an input image according to the content of the input LabelMap . The masked pixel of the input image are set to the BackgroundValue. LabelMapMaskImageFilter can keep the input image for one label only, with Negated = false (the default) or it can mask the input image for a single label, when Negated equals true. In Both cases, the label is set with SetLabel() .\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see LabelMapToBinaryImageFilter , LabelMapToLabelImageFilter" + "detaileddescription" : "LabelMapMaskImageFilter mask the content of an input image according to the content of the input LabelMap . The masked pixel of the input image are set to the BackgroundValue. LabelMapMaskImageFilter can keep the input image for one label only, with Negated = false (the default) or it can mask the input image for a single label, when Negated equals true. In Both cases, the label is set with SetLabel() .\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see LabelMapToBinaryImageFilter , LabelMapToLabelImageFilter" } diff --git a/Code/BasicFilters/json/LabelMapOverlayImageFilter.json b/Code/BasicFilters/json/LabelMapOverlayImageFilter.json index b5ed89b80..afd29c182 100644 --- a/Code/BasicFilters/json/LabelMapOverlayImageFilter.json +++ b/Code/BasicFilters/json/LabelMapOverlayImageFilter.json @@ -35,5 +35,5 @@ } ], "briefdescription" : "Apply a colormap to a label map and superimpose it on an image.", - "detaileddescription" : "Apply a colormap to a label map and put it on top of the feature image. The feature image is typically the image from which the labeling was produced. Use the SetInput function to set the LabelMap , and the SetFeatureImage function to set the feature image.\n\nThe set of colors is a good selection of distinct colors. The opacity of the label map can be defined by the user. A background label produce a gray pixel with the same intensity than the input one.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see LabelMapToBinaryImageFilter , LabelMapToLabelImageFilter" + "detaileddescription" : "Apply a colormap to a label map and put it on top of the feature image. The feature image is typically the image from which the labeling was produced. Use the SetInput function to set the LabelMap , and the SetFeatureImage function to set the feature image.\n\nThe set of colors is a good selection of distinct colors. The opacity of the label map can be defined by the user. A background label produce a gray pixel with the same intensity than the input one.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see LabelMapToBinaryImageFilter , LabelMapToLabelImageFilter" } diff --git a/Code/BasicFilters/json/LabelMapToBinaryImageFilter.json b/Code/BasicFilters/json/LabelMapToBinaryImageFilter.json index 43e797d2c..7b99e9548 100644 --- a/Code/BasicFilters/json/LabelMapToBinaryImageFilter.json +++ b/Code/BasicFilters/json/LabelMapToBinaryImageFilter.json @@ -43,5 +43,5 @@ } ], "briefdescription" : "Convert a LabelMap to a binary image.", - "detaileddescription" : "LabelMapToBinaryImageFilter to a binary image. All the objects in the image are used as foreground. The background values of the original binary image can be restored by passing this image to the filter with the SetBackgroundImage() method.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see LabelMapToLabelImageFilter , LabelMapMaskImageFilter" + "detaileddescription" : "LabelMapToBinaryImageFilter to a binary image. All the objects in the image are used as foreground. The background values of the original binary image can be restored by passing this image to the filter with the SetBackgroundImage() method.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see LabelMapToLabelImageFilter , LabelMapMaskImageFilter" } diff --git a/Code/BasicFilters/json/LabelMapToLabelImageFilter.json b/Code/BasicFilters/json/LabelMapToLabelImageFilter.json index 44c6a54af..dd2c0e63e 100644 --- a/Code/BasicFilters/json/LabelMapToLabelImageFilter.json +++ b/Code/BasicFilters/json/LabelMapToLabelImageFilter.json @@ -20,5 +20,5 @@ } ], "briefdescription" : "Converts a LabelMap to a labeled image.", - "detaileddescription" : "LabelMapToBinaryImageFilter to a label image.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see LabelMapToBinaryImageFilter , LabelMapMaskImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Convert a LabelMap to a normal image with different values representing each region" + "detaileddescription" : "LabelMapToBinaryImageFilter to a label image.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see LabelMapToBinaryImageFilter , LabelMapMaskImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Convert a LabelMap to a normal image with different values representing each region" } diff --git a/Code/BasicFilters/json/LabelMapToRGBImageFilter.json b/Code/BasicFilters/json/LabelMapToRGBImageFilter.json index dcc93eee2..d498d01d7 100644 --- a/Code/BasicFilters/json/LabelMapToRGBImageFilter.json +++ b/Code/BasicFilters/json/LabelMapToRGBImageFilter.json @@ -20,5 +20,5 @@ } ], "briefdescription" : "Convert a LabelMap to a colored image.", - "detaileddescription" : "\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see LabelMapToBinaryImageFilter , LabelMapMaskImageFilter" + "detaileddescription" : "\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see LabelMapToBinaryImageFilter , LabelMapMaskImageFilter" } diff --git a/Code/BasicFilters/json/LabelOverlapMeasuresImageFilter.json b/Code/BasicFilters/json/LabelOverlapMeasuresImageFilter.json index c661eec5b..af8999d21 100644 --- a/Code/BasicFilters/json/LabelOverlapMeasuresImageFilter.json +++ b/Code/BasicFilters/json/LabelOverlapMeasuresImageFilter.json @@ -154,5 +154,5 @@ } ], "briefdescription" : "Computes overlap measures between the set same set of labels of pixels of two images. Background is assumed to be 0.", - "detaileddescription" : "This code was contributed in the Insight Journal paper: \"Introducing Dice, Jaccard, and Other Label Overlap Measures To ITK\" by Nicholas J. Tustison, James C. Gee http://hdl.handle.net/10380/3141 http://www.insight-journal.org/browse/publication/707 \n\n\\author Nicholas J. Tustison\n\n\\see LabelOverlapMeasuresImageFilter" + "detaileddescription" : "This code was contributed in the Insight Journal paper: \"Introducing Dice, Jaccard, and Other Label Overlap Measures To ITK\" by Nicholas J. Tustison, James C. Gee https://hdl.handle.net/10380/3141 http://www.insight-journal.org/browse/publication/707 \n\n\\author Nicholas J. Tustison\n\n\\see LabelOverlapMeasuresImageFilter" } diff --git a/Code/BasicFilters/json/LabelOverlayImageFilter.json b/Code/BasicFilters/json/LabelOverlayImageFilter.json index 256c7995a..fb71804f2 100644 --- a/Code/BasicFilters/json/LabelOverlayImageFilter.json +++ b/Code/BasicFilters/json/LabelOverlayImageFilter.json @@ -53,5 +53,5 @@ } ], "briefdescription" : "Apply a colormap to a label image and put it on top of the input image.", - "detaileddescription" : "Apply a colormap to a label image and put it on top of the input image. The set of colors is a good selection of distinct colors. The opacity of the label image can be defined by the user. The user can also choose if the want to use a background and which label value is the background. A background label produce a gray pixel with the same intensity than the input one.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis class was contributed to the Insight Journal http://hdl.handle.net/1926/172 \n\n\\see ScalarToRGBPixelFunctor LabelToRGBImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Overlay a LabelMap on an image" + "detaileddescription" : "Apply a colormap to a label image and put it on top of the input image. The set of colors is a good selection of distinct colors. The opacity of the label image can be defined by the user. The user can also choose if the want to use a background and which label value is the background. A background label produce a gray pixel with the same intensity than the input one.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis class was contributed to the Insight Journal https://hdl.handle.net/1926/172 \n\n\\see ScalarToRGBPixelFunctor LabelToRGBImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Overlay a LabelMap on an image" } diff --git a/Code/BasicFilters/json/LabelShapeStatisticsImageFilter.json b/Code/BasicFilters/json/LabelShapeStatisticsImageFilter.json index 4ef1f55ed..b107b78ef 100644 --- a/Code/BasicFilters/json/LabelShapeStatisticsImageFilter.json +++ b/Code/BasicFilters/json/LabelShapeStatisticsImageFilter.json @@ -404,5 +404,5 @@ } ], "briefdescription" : "Converts a label image to a label map and valuates the shape attributes.", - "detaileddescription" : "A convenient class that converts a label image to a label map and valuates the shape attribute at once.\n\nThis implementation was taken from the Insight Journal paper:\n\nhttp://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ShapeLabelObject , LabelShapeOpeningImageFilter , LabelStatisticsOpeningImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Convert an itk::Image consisting of labeled regions to a ShapeLabelMap" + "detaileddescription" : "A convenient class that converts a label image to a label map and valuates the shape attribute at once.\n\nThis implementation was taken from the Insight Journal paper:\n\nhttps://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ShapeLabelObject , LabelShapeOpeningImageFilter , LabelStatisticsOpeningImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Convert an itk::Image consisting of labeled regions to a ShapeLabelMap" } diff --git a/Code/BasicFilters/json/LabelStatisticsImageFilter.json b/Code/BasicFilters/json/LabelStatisticsImageFilter.json index 29feee103..dd3f8b6df 100644 --- a/Code/BasicFilters/json/LabelStatisticsImageFilter.json +++ b/Code/BasicFilters/json/LabelStatisticsImageFilter.json @@ -180,8 +180,8 @@ "type" : "int64_t" } ], - "briefdescriptionGet" : "Return the computed bounding box for a label.", - "detaileddescriptionGet" : "Defined by the closed interval of indexes, with a lower index followed by the upper for each dimension. i.e. [0,255,0,255]. The bounding box always has a positive size." + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Return the computed bounding box for a label." }, { "name" : "Labels", diff --git a/Code/BasicFilters/json/LabelToRGBImageFilter.json b/Code/BasicFilters/json/LabelToRGBImageFilter.json index 7a0d114b6..6b18812ff 100644 --- a/Code/BasicFilters/json/LabelToRGBImageFilter.json +++ b/Code/BasicFilters/json/LabelToRGBImageFilter.json @@ -31,5 +31,5 @@ } ], "briefdescription" : "Apply a colormap to a label image.", - "detaileddescription" : "Apply a colormap to a label image. The set of colors is a good selection of distinct colors. The user can choose to use a background value. In that case, a gray pixel with the same intensity than the background label is produced.\n\nThis code was contributed in the Insight Journal paper: \"The watershed transform in ITK - discussion and new developments\" by Beare R., Lehmann G. http://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nRichard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\n\\see ScalarToRGBPixelFunctor LabelOverlayImageFilter" + "detaileddescription" : "Apply a colormap to a label image. The set of colors is a good selection of distinct colors. The user can choose to use a background value. In that case, a gray pixel with the same intensity than the background label is produced.\n\nThis code was contributed in the Insight Journal paper: \"The watershed transform in ITK - discussion and new developments\" by Beare R., Lehmann G. https://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nRichard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\n\\see ScalarToRGBPixelFunctor LabelOverlayImageFilter" } diff --git a/Code/BasicFilters/json/LabelUniqueLabelMapFilter.json b/Code/BasicFilters/json/LabelUniqueLabelMapFilter.json index 8e10b2bbd..6f495b50f 100644 --- a/Code/BasicFilters/json/LabelUniqueLabelMapFilter.json +++ b/Code/BasicFilters/json/LabelUniqueLabelMapFilter.json @@ -45,5 +45,5 @@ } ], "briefdescription" : "Make sure that the objects are not overlapping.", - "detaileddescription" : "AttributeUniqueLabelMapFilter search the overlapping zones in the overlapping objects and keeps only a single object on all the pixels of the image. The object to keep is selected according to their label.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see AttributeLabelObject" + "detaileddescription" : "AttributeUniqueLabelMapFilter search the overlapping zones in the overlapping objects and keeps only a single object on all the pixels of the image. The object to keep is selected according to their label.\n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\see AttributeLabelObject" } diff --git a/Code/BasicFilters/json/LandweberDeconvolutionImageFilter.json b/Code/BasicFilters/json/LandweberDeconvolutionImageFilter.json index 68f491b59..240f603db 100644 --- a/Code/BasicFilters/json/LandweberDeconvolutionImageFilter.json +++ b/Code/BasicFilters/json/LandweberDeconvolutionImageFilter.json @@ -78,5 +78,5 @@ } ], "briefdescription" : "Deconvolve an image using the Landweber deconvolution algorithm.", - "detaileddescription" : "This filter implements the Landweber deconvolution algorthm as defined in Bertero M and Boccacci P, \"Introduction to Inverse\nProblems in Imaging\", 1998. The algorithm assumes that the input image has been formed by a linear shift-invariant system with a known kernel.\n\nThe Landweber algorithm converges to a solution that minimizes the sum of squared errors\\f$||f \\otimes h - g||\\f$ where\\f$f\\f$ is the estimate of the unblurred image,\\f$\\otimes\\f$ is the convolution operator,\\f$h\\f$ is the blurring kernel, and\\f$g\\f$ is the blurred input image. As such, it is best suited for images that have zero-mean Gaussian white noise.\n\nThis is the base implementation of the Landweber algorithm. It may produce results with negative values. For a version of this algorithm that enforces a positivity constraint on each intermediate solution, see ProjectedLandweberDeconvolutionImageFilter .\n\nThis code was adapted from the Insight Journal contribution:\n\n\"Deconvolution: infrastructure and reference algorithms\" by Gaetan Lehmann http://hdl.handle.net/10380/3207 \n\n\\author Gaetan Lehmann, Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France\n\nCory Quammen, The University of North Carolina at Chapel Hill\n\n\\see IterativeDeconvolutionImageFilter \n\\see \n\\see RichardsonLucyDeconvolutionImageFilter \n\\see \n\\see ProjectedLandweberDeconvolutionImageFilter" + "detaileddescription" : "This filter implements the Landweber deconvolution algorthm as defined in Bertero M and Boccacci P, \"Introduction to Inverse\nProblems in Imaging\", 1998. The algorithm assumes that the input image has been formed by a linear shift-invariant system with a known kernel.\n\nThe Landweber algorithm converges to a solution that minimizes the sum of squared errors\\f$||f \\otimes h - g||\\f$ where\\f$f\\f$ is the estimate of the unblurred image,\\f$\\otimes\\f$ is the convolution operator,\\f$h\\f$ is the blurring kernel, and\\f$g\\f$ is the blurred input image. As such, it is best suited for images that have zero-mean Gaussian white noise.\n\nThis is the base implementation of the Landweber algorithm. It may produce results with negative values. For a version of this algorithm that enforces a positivity constraint on each intermediate solution, see ProjectedLandweberDeconvolutionImageFilter .\n\nThis code was adapted from the Insight Journal contribution:\n\n\"Deconvolution: infrastructure and reference algorithms\" by Gaetan Lehmann https://hdl.handle.net/10380/3207 \n\n\\author Gaetan Lehmann, Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France\n\nCory Quammen, The University of North Carolina at Chapel Hill\n\n\\see IterativeDeconvolutionImageFilter \n\\see \n\\see RichardsonLucyDeconvolutionImageFilter \n\\see \n\\see ProjectedLandweberDeconvolutionImageFilter" } diff --git a/Code/BasicFilters/json/LevelSetMotionRegistrationFilter.json b/Code/BasicFilters/json/LevelSetMotionRegistrationFilter.json index 5ec439307..4fd57c693 100644 --- a/Code/BasicFilters/json/LevelSetMotionRegistrationFilter.json +++ b/Code/BasicFilters/json/LevelSetMotionRegistrationFilter.json @@ -23,7 +23,7 @@ "type" : "double", "default" : "1.0", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set/Get the standard deviation used for smoothing the moving image prior to calculating gradients. The standard deviation is measured in physical units (for instance mm). Note that this smoothing value is not to be confused with the PDEDeformableRegistrationFilter::SetStandardDeviations()method. The method in PDEDeformableRegistrationFilteris for setting the smoothing parameters for regularizing the deformation field between interations. Those smoothing parameters are set in pixel units not physical units. Deformation field smoothing is not done by default in LevelSetMotionRegistration. This smoothing parameter is to condition the gradient calculation and parameter is specified in physical units.", + "detaileddescriptionSet" : "Set/Get the standard deviation used for smoothing the moving image prior to calculating gradients. The standard deviation is measured in physical units (for instance mm). Note that this smoothing value is not to be confused with the PDEDeformableRegistrationFilter::SetStandardDeviations() method. The method in PDEDeformableRegistrationFilter is for setting the smoothing parameters for regularizing the deformation field between interations. Those smoothing parameters are set in pixel units not physical units. Deformation field smoothing is not done by default in LevelSetMotionRegistration. This smoothing parameter is to condition the gradient calculation and parameter is specified in physical units.", "briefdescriptionGet" : "", "detaileddescriptionGet" : "" }, @@ -170,5 +170,5 @@ } ], "briefdescription" : "Deformably register two images using level set motion.", - "detaileddescription" : "LevelSetMotionFilter implements a deformable registration algorithm that aligns a fixed and a moving image under level set motion. The equations of motion are similar to those of the DemonsRegistrationFilter. The main differences are: (1) Gradients of the moving image are calculated on a smoothed image while intensity difference are measured on the original images (2) Magnitude of the motion vector is a function of the differences in intensity between the fixed and moving pixel. An adaptive timestep is calculated based on the maximum motion vector over the entire field to ensure stability. The timestep also implictly converts the motion vector measured in units of intensity to a vector measured in physical units. Demons, on the other hand, defines its motion vectors as function of both the intensity differences and gradient magnitude at each respective pixel. Consider two separate pixels with the same intensity differences between the corresponding fixed and moving pixel pairs. In demons, the motion vector of the pixel over a low gradient region will be larger than the motion vector of the pixel over a large gradient region. This leads to an unstable vector field. In the levelset approach, the motion vectors will be proportional to the gradients, scaled by the maximum gradient over the entire field. The pixel with at the lower gradient position will more less than the pixel at the higher gradient position. (3) Gradients are calculated using minmod finite difference instead of using central differences.\n\nA deformation field is represented as a image whose pixel type is some vector type with at least N elements, where N is the dimension of the fixed image. The vector type must support element access via operator []. It is assumed that the vector elements behave like floating point scalars.\n\nThis class is templated over the fixed image type, moving image type and the deformation field type.\n\nThe input fixed and moving images are set via methods SetFixedImage and SetMovingImage respectively. An initial deformation field maybe set via SetInitialDisplacementField or SetInput. If no initial field is set, a zero field is used as the initial condition.\n\nThe algorithm has one parameters: the number of iteration to be performed.\n\nThe output deformation field can be obtained via methods GetOutput or GetDisplacementField.\n\nThis class make use of the finite difference solver hierarchy. Update for each iteration is computed in LevelSetMotionFunction.\n\n\\warning This filter assumes that the fixed image type, moving image type and deformation field type all have the same number of dimensions.\n\nRef: B.C. Vemuri, J. Ye, Y. Chen, C.M. Leonard. \" Imageregistration via level-set motion: applications to atlas-based segmentation\". Medical ImageAnalysis. Vol. 7. pp. 1-20. 2003.\n\n\\see LevelSetMotionRegistrationFunction\n\\see \n\\see DemonsRegistrationFilter" + "detaileddescription" : "LevelSetMotionFilter implements a deformable registration algorithm that aligns a fixed and a moving image under level set motion. The equations of motion are similar to those of the DemonsRegistrationFilter . The main differences are: (1) Gradients of the moving image are calculated on a smoothed image while intensity difference are measured on the original images (2) Magnitude of the motion vector is a function of the differences in intensity between the fixed and moving pixel. An adaptive timestep is calculated based on the maximum motion vector over the entire field to ensure stability. The timestep also implictly converts the motion vector measured in units of intensity to a vector measured in physical units. Demons, on the other hand, defines its motion vectors as function of both the intensity differences and gradient magnitude at each respective pixel. Consider two separate pixels with the same intensity differences between the corresponding fixed and moving pixel pairs. In demons, the motion vector of the pixel over a low gradient region will be larger than the motion vector of the pixel over a large gradient region. This leads to an unstable vector field. In the levelset approach, the motion vectors will be proportional to the gradients, scaled by the maximum gradient over the entire field. The pixel with at the lower gradient position will more less than the pixel at the higher gradient position. (3) Gradients are calculated using minmod finite difference instead of using central differences.\n\nA deformation field is represented as a image whose pixel type is some vector type with at least N elements, where N is the dimension of the fixed image. The vector type must support element access via operator []. It is assumed that the vector elements behave like floating point scalars.\n\nThis class is templated over the fixed image type, moving image type and the deformation field type.\n\nThe input fixed and moving images are set via methods SetFixedImage and SetMovingImage respectively. An initial deformation field maybe set via SetInitialDisplacementField or SetInput. If no initial field is set, a zero field is used as the initial condition.\n\nThe algorithm has one parameters: the number of iteration to be performed.\n\nThe output deformation field can be obtained via methods GetOutput or GetDisplacementField.\n\nThis class make use of the finite difference solver hierarchy. Update for each iteration is computed in LevelSetMotionFunction.\n\n\\warning This filter assumes that the fixed image type, moving image type and deformation field type all have the same number of dimensions.\n\nRef: B.C. Vemuri, J. Ye, Y. Chen, C.M. Leonard. \" Image registration via level-set motion: applications to atlas-based segmentation\". Medical Image Analysis. Vol. 7. pp. 1-20. 2003.\n\n\\see LevelSetMotionRegistrationFunction \n\\see \n\\see DemonsRegistrationFilter" } diff --git a/Code/BasicFilters/json/LiThresholdImageFilter.json b/Code/BasicFilters/json/LiThresholdImageFilter.json index b9fef46a2..09a65cbfa 100644 --- a/Code/BasicFilters/json/LiThresholdImageFilter.json +++ b/Code/BasicFilters/json/LiThresholdImageFilter.json @@ -126,5 +126,5 @@ } ], "briefdescription" : "Threshold an image using the Li Threshold.", - "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the LiThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" + "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the LiThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" } diff --git a/Code/BasicFilters/json/MaximumEntropyThresholdImageFilter.json b/Code/BasicFilters/json/MaximumEntropyThresholdImageFilter.json index cadb5db70..3899374c5 100644 --- a/Code/BasicFilters/json/MaximumEntropyThresholdImageFilter.json +++ b/Code/BasicFilters/json/MaximumEntropyThresholdImageFilter.json @@ -126,5 +126,5 @@ } ], "briefdescription" : "Threshold an image using the MaximumEntropy Threshold.", - "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the MaximumEntropyThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" + "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the MaximumEntropyThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" } diff --git a/Code/BasicFilters/json/MaximumProjectionImageFilter.json b/Code/BasicFilters/json/MaximumProjectionImageFilter.json index 7d8e1db38..5494b57fa 100644 --- a/Code/BasicFilters/json/MaximumProjectionImageFilter.json +++ b/Code/BasicFilters/json/MaximumProjectionImageFilter.json @@ -62,5 +62,5 @@ } ], "briefdescription" : "Maximum projection.", - "detaileddescription" : "This class was contributed to the insight journal by Gaetan Lehmann. The original paper can be found at http://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la reproduction, inra de jouy-en-josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see MedianProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter \n\\see \n\\see BinaryProjectionImageFilter" + "detaileddescription" : "This class was contributed to the insight journal by Gaetan Lehmann. The original paper can be found at https://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la reproduction, inra de jouy-en-josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see MedianProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter \n\\see \n\\see BinaryProjectionImageFilter" } diff --git a/Code/BasicFilters/json/MeanProjectionImageFilter.json b/Code/BasicFilters/json/MeanProjectionImageFilter.json index e92b9547e..a9bd84175 100644 --- a/Code/BasicFilters/json/MeanProjectionImageFilter.json +++ b/Code/BasicFilters/json/MeanProjectionImageFilter.json @@ -31,5 +31,5 @@ } ], "briefdescription" : "Mean projection.", - "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. The original paper can be found at http://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see MedianProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter \n\\see \n\\see BinaryProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter" + "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. The original paper can be found at https://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see MedianProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter \n\\see \n\\see BinaryProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter" } diff --git a/Code/BasicFilters/json/MedianProjectionImageFilter.json b/Code/BasicFilters/json/MedianProjectionImageFilter.json index 36754185b..26b4275cf 100644 --- a/Code/BasicFilters/json/MedianProjectionImageFilter.json +++ b/Code/BasicFilters/json/MedianProjectionImageFilter.json @@ -62,5 +62,5 @@ } ], "briefdescription" : "Median projection.", - "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. The original paper can be found at http://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter \n\\see \n\\see BinaryProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter" + "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. The original paper can be found at https://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter \n\\see \n\\see BinaryProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter" } diff --git a/Code/BasicFilters/json/MergeLabelMapFilter.json b/Code/BasicFilters/json/MergeLabelMapFilter.json index 708c06bcb..359599a63 100644 --- a/Code/BasicFilters/json/MergeLabelMapFilter.json +++ b/Code/BasicFilters/json/MergeLabelMapFilter.json @@ -134,5 +134,5 @@ } ], "briefdescription" : "Merges several Label Maps.", - "detaileddescription" : "This filter takes one or more input Label Map and merges them.\n\nSetMethod() can be used to change how the filter manage the labels from the different label maps. KEEP (0): MergeLabelMapFilter do its best to keep the label unchanged, but if a label is already used in a previous label map, a new label is assigned. AGGREGATE (1): If the same label is found several times in the label maps, the label objects with the same label are merged. PACK (2): MergeLabelMapFilter relabel all the label objects by order of processing. No conflict can occur. STRICT (3): MergeLabelMapFilter keeps the labels unchanged and raises an exception if the same label is found in several images.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ShapeLabelObject , RelabelComponentImageFilter" + "detaileddescription" : "This filter takes one or more input Label Map and merges them.\n\nSetMethod() can be used to change how the filter manage the labels from the different label maps. KEEP (0): MergeLabelMapFilter do its best to keep the label unchanged, but if a label is already used in a previous label map, a new label is assigned. AGGREGATE (1): If the same label is found several times in the label maps, the label objects with the same label are merged. PACK (2): MergeLabelMapFilter relabel all the label objects by order of processing. No conflict can occur. STRICT (3): MergeLabelMapFilter keeps the labels unchanged and raises an exception if the same label is found in several images.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ShapeLabelObject , RelabelComponentImageFilter" } diff --git a/Code/BasicFilters/json/MinimumProjectionImageFilter.json b/Code/BasicFilters/json/MinimumProjectionImageFilter.json index fa9f9d3fe..266d097b9 100644 --- a/Code/BasicFilters/json/MinimumProjectionImageFilter.json +++ b/Code/BasicFilters/json/MinimumProjectionImageFilter.json @@ -62,5 +62,5 @@ } ], "briefdescription" : "Minimum projection.", - "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. The original paper can be found at http://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter \n\\see \n\\see BinaryProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter" + "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. The original paper can be found at https://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter \n\\see \n\\see BinaryProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter" } diff --git a/Code/BasicFilters/json/MomentsThresholdImageFilter.json b/Code/BasicFilters/json/MomentsThresholdImageFilter.json index a3d12c09c..4db734135 100644 --- a/Code/BasicFilters/json/MomentsThresholdImageFilter.json +++ b/Code/BasicFilters/json/MomentsThresholdImageFilter.json @@ -126,5 +126,5 @@ } ], "briefdescription" : "Threshold an image using the Moments Threshold.", - "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the MomentsThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" + "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the MomentsThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" } diff --git a/Code/BasicFilters/json/MorphologicalWatershedFromMarkersImageFilter.json b/Code/BasicFilters/json/MorphologicalWatershedFromMarkersImageFilter.json index 6249d66a3..9de254b18 100644 --- a/Code/BasicFilters/json/MorphologicalWatershedFromMarkersImageFilter.json +++ b/Code/BasicFilters/json/MorphologicalWatershedFromMarkersImageFilter.json @@ -52,5 +52,5 @@ } ], "briefdescription" : "Morphological watershed transform from markers.", - "detaileddescription" : "The watershed transform is a tool for image segmentation that is fast and flexible and potentially fairly parameter free. It was originally derived from a geophysical model of rain falling on a terrain and a variety of more formal definitions have been devised to allow development of practical algorithms. If an image is considered as a terrain and divided into catchment basins then the hope is that each catchment basin would contain an object of interest.\n\nThe output is a label image. A label image, sometimes referred to as a categorical image, has unique values for each region. For example, if a watershed produces 2 regions, all pixels belonging to one region would have value A, and all belonging to the other might have value B. Unassigned pixels, such as watershed lines, might have the background value (0 by convention).\n\nThe simplest way of using the watershed is to preprocess the image we want to segment so that the boundaries of our objects are bright (e.g apply an edge detector) and compute the watershed transform of the edge image. Watershed lines will correspond to the boundaries and our problem will be solved. This is rarely useful in practice because there are always more regional minima than there are objects, either due to noise or natural variations in the object surfaces. Therefore, while many watershed lines do lie on significant boundaries, there are many that don't. Various methods can be used to reduce the number of minima in the image, like thresholding the smallest values, filtering the minima and/or smoothing the image.\n\nThis filter use another approach to avoid the problem of over segmentation: it let the user provide a marker image which mark the minima in the input image and give them a label. The minima are imposed in the input image by the markers. The labels of the output image are the label of the marker image.\n\nThe morphological watershed transform algorithm is described in Chapter 9.2 of Pierre Soille's book \"Morphological Image Analysis:\nPrinciples and Applications\", Second Edition, Springer, 2003.\n\nThis code was contributed in the Insight Journal paper: \"The watershed transform in ITK - discussion and new developments\" by Beare R., Lehmann G. http://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nRichard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\n\\see WatershedImageFilter , MorphologicalWatershedImageFilter" + "detaileddescription" : "The watershed transform is a tool for image segmentation that is fast and flexible and potentially fairly parameter free. It was originally derived from a geophysical model of rain falling on a terrain and a variety of more formal definitions have been devised to allow development of practical algorithms. If an image is considered as a terrain and divided into catchment basins then the hope is that each catchment basin would contain an object of interest.\n\nThe output is a label image. A label image, sometimes referred to as a categorical image, has unique values for each region. For example, if a watershed produces 2 regions, all pixels belonging to one region would have value A, and all belonging to the other might have value B. Unassigned pixels, such as watershed lines, might have the background value (0 by convention).\n\nThe simplest way of using the watershed is to preprocess the image we want to segment so that the boundaries of our objects are bright (e.g apply an edge detector) and compute the watershed transform of the edge image. Watershed lines will correspond to the boundaries and our problem will be solved. This is rarely useful in practice because there are always more regional minima than there are objects, either due to noise or natural variations in the object surfaces. Therefore, while many watershed lines do lie on significant boundaries, there are many that don't. Various methods can be used to reduce the number of minima in the image, like thresholding the smallest values, filtering the minima and/or smoothing the image.\n\nThis filter use another approach to avoid the problem of over segmentation: it let the user provide a marker image which mark the minima in the input image and give them a label. The minima are imposed in the input image by the markers. The labels of the output image are the label of the marker image.\n\nThe morphological watershed transform algorithm is described in Chapter 9.2 of Pierre Soille's book \"Morphological Image Analysis:\nPrinciples and Applications\", Second Edition, Springer, 2003.\n\nThis code was contributed in the Insight Journal paper: \"The watershed transform in ITK - discussion and new developments\" by Beare R., Lehmann G. https://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nRichard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\n\\see WatershedImageFilter , MorphologicalWatershedImageFilter" } diff --git a/Code/BasicFilters/json/MorphologicalWatershedImageFilter.json b/Code/BasicFilters/json/MorphologicalWatershedImageFilter.json index 10e0f7414..38eb494e0 100644 --- a/Code/BasicFilters/json/MorphologicalWatershedImageFilter.json +++ b/Code/BasicFilters/json/MorphologicalWatershedImageFilter.json @@ -69,5 +69,5 @@ } ], "briefdescription" : "TODO.", - "detaileddescription" : "TODO\n\nWatershed pixel are labeled 0. TOutputImage should be an integer type. Labels of output image are in no particular order. You can reorder the labels such that object labels are consecutive and sorted based on object size by passing the output of this filter to a RelabelComponentImageFilter .\n\nThe morphological watershed transform algorithm is described in Chapter 9.2 of Pierre Soille's book \"Morphological Image Analysis:\nPrinciples and Applications\", Second Edition, Springer, 2003.\n\nThis code was contributed in the Insight Journal paper: \"The watershed transform in ITK - discussion and new developments\" by Beare R., Lehmann G. http://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see WatershedImageFilter , MorphologicalWatershedFromMarkersImageFilter" + "detaileddescription" : "TODO\n\nWatershed pixel are labeled 0. TOutputImage should be an integer type. Labels of output image are in no particular order. You can reorder the labels such that object labels are consecutive and sorted based on object size by passing the output of this filter to a RelabelComponentImageFilter .\n\nThe morphological watershed transform algorithm is described in Chapter 9.2 of Pierre Soille's book \"Morphological Image Analysis:\nPrinciples and Applications\", Second Edition, Springer, 2003.\n\nThis code was contributed in the Insight Journal paper: \"The watershed transform in ITK - discussion and new developments\" by Beare R., Lehmann G. https://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see WatershedImageFilter , MorphologicalWatershedFromMarkersImageFilter" } diff --git a/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json b/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json index 51e94fe49..0df4a431e 100644 --- a/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json +++ b/Code/BasicFilters/json/MultiLabelSTAPLEImageFilter.json @@ -15,14 +15,16 @@ "briefdescriptionSet" : "", "detaileddescriptionSet" : "Set label value for undecided pixels.", "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Get label value used for undecided pixels. After updating the filter, this function returns the actual label value used for undecided pixels in the current output. Note that this value is overwritten when SetLabelForUndecidedPixels is called and the new value only becomes effective upon the next filter update." + "detaileddescriptionGet" : "Get label value used for undecided pixels.\n\nAfter updating the filter, this function returns the actual label value used for undecided pixels in the current output. Note that this value is overwritten when SetLabelForUndecidedPixels is called and the new value only becomes effective upon the next filter update." }, { "name" : "TerminationUpdateThreshold", "type" : "float", "default" : "1e-5f", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set termination threshold based on confusion matrix parameter updates." + "detaileddescriptionSet" : "Set termination threshold based on confusion matrix parameter updates.", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Set termination threshold based on confusion matrix parameter updates." }, { "name" : "MaximumNumberOfIterations", @@ -30,7 +32,9 @@ "default" : "std::numeric_limits::max()", "custom_itk_cast" : "if (m_MaximumNumberOfIterations!=std::numeric_limits::max()) filter->SetMaximumNumberOfIterations(this->m_MaximumNumberOfIterations);", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set maximum number of iterations." + "detaileddescriptionSet" : "Set maximum number of iterations.", + "briefdescriptionGet" : "", + "detaileddescriptionGet" : "Set maximum number of iterations." }, { "name" : "PriorProbabilities", @@ -38,9 +42,9 @@ "default" : "std::vector()", "briefdescriptionSet" : "", "custom_itk_cast" : "if (!m_PriorProbabilities.empty()) filter->SetPriorProbabilities(typename FilterType::PriorProbabilitiesType(&this->m_PriorProbabilities[0],this->m_PriorProbabilities.size()));", - "detaileddescriptionSet" : "Set label value for undecided pixels.", + "detaileddescriptionSet" : "Set manual estimates for the a priori class probabilities.The size of the array must be greater than the value of the\n largest label. The index into the array corresponds to the label\n value in the segmented image for the class.", "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Get prior class probabilities. After updating the filter, this function returns the actual prior class probabilities. If these were not previously set by a call to SetPriorProbabilities, then they are estimated from the input segmentations and the result is available through this function." + "detaileddescriptionGet" : "Get prior class probabilities.\n\nAfter updating the filter, this function returns the actual prior class probabilities. If these were not previously set by a call to SetPriorProbabilities, then they are estimated from the input segmentations and the result is available through this function." } ], "measurements" : [ diff --git a/Code/BasicFilters/json/N4BiasFieldCorrectionImageFilter.json b/Code/BasicFilters/json/N4BiasFieldCorrectionImageFilter.json index 1fffb76f6..637692333 100644 --- a/Code/BasicFilters/json/N4BiasFieldCorrectionImageFilter.json +++ b/Code/BasicFilters/json/N4BiasFieldCorrectionImageFilter.json @@ -105,5 +105,5 @@ } ], "briefdescription" : "Implementation of the N4 bias field correction algorithm.", - "detaileddescription" : "The nonparametric nonuniform intensity normalization (N3) algorithm, as introduced by Sled et al. in 1998 is a method for correcting nonuniformity associated with MR images. The algorithm assumes a simple parametric model (Gaussian) for the bias field and does not require tissue class segmentation. In addition, there are only a couple of parameters to tune with the default values performing quite well. N3 has been publicly available as a set of perl scripts ( http://www.bic.mni.mcgill.ca/ServicesSoftwareAdvancedImageProcessingTools/HomePage )\n\nThe N4 algorithm, encapsulated with this class, is a variation of the original N3 algorithm with the additional benefits of an improved B-spline fitting routine which allows for multiple resolutions to be used during the correction process. We also modify the iterative update component of algorithm such that the residual bias field is continually updated\n\nNotes for the user:\\li Since much of the image manipulation is done in the log space of the intensities, input images with negative and small values (< 1) can produce poor results.\n\n\\li The original authors recommend performing the bias field correction on a downsampled version of the original image.\n\n\\li A binary mask or a weighted image can be supplied. If a binary mask is specified, those voxels in the input image which correspond to the voxels in the mask image with a value equal to m_MaskLabel, are used to estimate the bias field. If a confidence image is specified, the input voxels are weighted in the b-spline fitting routine according to the confidence voxel values.\n\n\\li The filter returns the corrected image. If the bias field is wanted, one can reconstruct it using the class itkBSplineControlPointImageFilter. See the IJ article and the test file for an example.\n\n\\li The 'Z' parameter in Sled's 1998 paper is the square root of the class variable 'm_WienerFilterNoise'.\n\n\n\nThe basic algorithm iterates between sharpening the intensity histogram of the corrected input image and spatially smoothing those results with a B-spline scalar field estimate of the bias field.\n\n\\author Nicholas J. Tustison\n\nContributed by Nicholas J. Tustison, James C. Gee in the Insight Journal paper: http://hdl.handle.net/10380/3053 \n\n\\par REFERENCE\n\n\nJ.G. Sled, A.P. Zijdenbos and A.C. Evans. \"A Nonparametric Method for\nAutomatic Correction of Intensity Nonuniformity in Data\" IEEE Transactions on Medical Imaging, Vol 17, No 1. Feb 1998.\n\nN.J. Tustison, B.B. Avants, P.A. Cook, Y. Zheng, A. Egan, P.A. Yushkevich, and J.C. Gee. \"N4ITK: Improved N3 Bias Correction\" IEEE Transactions on Medical Imaging, 29(6):1310-1320, June 2010." + "detaileddescription" : "The nonparametric nonuniform intensity normalization (N3) algorithm, as introduced by Sled et al. in 1998 is a method for correcting nonuniformity associated with MR images. The algorithm assumes a simple parametric model (Gaussian) for the bias field and does not require tissue class segmentation. In addition, there are only a couple of parameters to tune with the default values performing quite well. N3 has been publicly available as a set of perl scripts ( http://www.bic.mni.mcgill.ca/ServicesSoftwareAdvancedImageProcessingTools/HomePage )\n\nThe N4 algorithm, encapsulated with this class, is a variation of the original N3 algorithm with the additional benefits of an improved B-spline fitting routine which allows for multiple resolutions to be used during the correction process. We also modify the iterative update component of algorithm such that the residual bias field is continually updated\n\nNotes for the user:\\li Since much of the image manipulation is done in the log space of the intensities, input images with negative and small values (< 1) can produce poor results.\n\n\\li The original authors recommend performing the bias field correction on a downsampled version of the original image.\n\n\\li A binary mask or a weighted image can be supplied. If a binary mask is specified, those voxels in the input image which correspond to the voxels in the mask image are used to estimate the bias field. If a UseMaskLabel value is set to true, only voxels in the MaskImage that match the MaskLabel will be used; otherwise, all non-zero voxels in the MaskImage will be masked. If a confidence image is specified, the input voxels are weighted in the b-spline fitting routine according to the confidence voxel values.\n\n\\li The filter returns the corrected image. If the bias field is wanted, one can reconstruct it using the class itkBSplineControlPointImageFilter. See the IJ article and the test file for an example.\n\n\\li The 'Z' parameter in Sled's 1998 paper is the square root of the class variable 'm_WienerFilterNoise'.\n\n\n\nThe basic algorithm iterates between sharpening the intensity histogram of the corrected input image and spatially smoothing those results with a B-spline scalar field estimate of the bias field.\n\n\\author Nicholas J. Tustison\n\nContributed by Nicholas J. Tustison, James C. Gee in the Insight Journal paper: https://hdl.handle.net/10380/3053 \n\n\\par REFERENCE\n\n\nJ.G. Sled, A.P. Zijdenbos and A.C. Evans. \"A Nonparametric Method for\nAutomatic Correction of Intensity Nonuniformity in Data\" IEEE Transactions on Medical Imaging, Vol 17, No 1. Feb 1998.\n\nN.J. Tustison, B.B. Avants, P.A. Cook, Y. Zheng, A. Egan, P.A. Yushkevich, and J.C. Gee. \"N4ITK: Improved N3 Bias Correction\" IEEE Transactions on Medical Imaging, 29(6):1310-1320, June 2010." } diff --git a/Code/BasicFilters/json/NormalizeToConstantImageFilter.json b/Code/BasicFilters/json/NormalizeToConstantImageFilter.json index efe372fb9..5aa5160d1 100644 --- a/Code/BasicFilters/json/NormalizeToConstantImageFilter.json +++ b/Code/BasicFilters/json/NormalizeToConstantImageFilter.json @@ -44,5 +44,5 @@ } ], "briefdescription" : "Scales image pixel intensities to make the sum of all pixels equal a user-defined constant.", - "detaileddescription" : "The default value of the constant is 1. It can be changed with SetConstant() .\n\nThis transform is especially useful for normalizing a convolution kernel.\n\nThis code was contributed in the Insight Journal paper: \"FFT based\nconvolution\" by Lehmann G. http://hdl.handle.net/10380/3154 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see NormalizeImageFilter \n\\see \n\\see StatisticsImageFilter \n\\see \n\\see DivideImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Scale all pixels so that their sum is a specified constant" + "detaileddescription" : "The default value of the constant is 1. It can be changed with SetConstant() .\n\nThis transform is especially useful for normalizing a convolution kernel.\n\nThis code was contributed in the Insight Journal paper: \"FFT based\nconvolution\" by Lehmann G. https://hdl.handle.net/10380/3154 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see NormalizeImageFilter \n\\see \n\\see StatisticsImageFilter \n\\see \n\\see DivideImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Scale all pixels so that their sum is a specified constant" } diff --git a/Code/BasicFilters/json/OtsuThresholdImageFilter.json b/Code/BasicFilters/json/OtsuThresholdImageFilter.json index a779dcd4e..444227e9c 100644 --- a/Code/BasicFilters/json/OtsuThresholdImageFilter.json +++ b/Code/BasicFilters/json/OtsuThresholdImageFilter.json @@ -149,5 +149,5 @@ } ], "briefdescription" : "Threshold an image using the Otsu Threshold.", - "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the OtsuThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Separate foreground and background using Otsu's method \n\n\n\n\\see HistogramThresholdImageFilter" + "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the OtsuThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Separate foreground and background using Otsu's method \n\n\n\n\\see HistogramThresholdImageFilter" } diff --git a/Code/BasicFilters/json/ProjectedLandweberDeconvolutionImageFilter.json b/Code/BasicFilters/json/ProjectedLandweberDeconvolutionImageFilter.json index 79647f680..1948c7451 100644 --- a/Code/BasicFilters/json/ProjectedLandweberDeconvolutionImageFilter.json +++ b/Code/BasicFilters/json/ProjectedLandweberDeconvolutionImageFilter.json @@ -78,5 +78,5 @@ } ], "briefdescription" : "Deconvolve an image using the projected Landweber deconvolution algorithm.", - "detaileddescription" : "This filter performs the same calculation per iteration as the LandweberDeconvolutionImageFilter . However, at each iteration, negative pixels in the intermediate result are projected (set) to zero. This is useful if the solution is assumed to always be non-negative, which is the case when dealing with images formed by counting photons, for example.\n\nThis code was adapted from the Insight Journal contribution:\n\n\"Deconvolution: infrastructure and reference algorithms\" by Gaetan Lehmann http://hdl.handle.net/10380/3207 \n\n\\author Gaetan Lehmann, Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France\n\nCory Quammen, The University of North Carolina at Chapel Hill\n\n\\see IterativeDeconvolutionImageFilter \n\\see \n\\see RichardsonLucyDeconvolutionImageFilter \n\\see \n\\see LandweberDeconvolutionImageFilter" + "detaileddescription" : "This filter performs the same calculation per iteration as the LandweberDeconvolutionImageFilter . However, at each iteration, negative pixels in the intermediate result are projected (set) to zero. This is useful if the solution is assumed to always be non-negative, which is the case when dealing with images formed by counting photons, for example.\n\nThis code was adapted from the Insight Journal contribution:\n\n\"Deconvolution: infrastructure and reference algorithms\" by Gaetan Lehmann https://hdl.handle.net/10380/3207 \n\n\\author Gaetan Lehmann, Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France\n\nCory Quammen, The University of North Carolina at Chapel Hill\n\n\\see IterativeDeconvolutionImageFilter \n\\see \n\\see RichardsonLucyDeconvolutionImageFilter \n\\see \n\\see LandweberDeconvolutionImageFilter" } diff --git a/Code/BasicFilters/json/RankImageFilter.json b/Code/BasicFilters/json/RankImageFilter.json index 33c9b2120..5bc437a55 100644 --- a/Code/BasicFilters/json/RankImageFilter.json +++ b/Code/BasicFilters/json/RankImageFilter.json @@ -71,5 +71,5 @@ } ], "briefdescription" : "Rank filter of a greyscale image.", - "detaileddescription" : "Nonlinear filter in which each output pixel is a user defined rank of input pixels in a user defined neighborhood. The default rank is 0.5 (median). The boundary conditions are different to the standard itkMedianImageFilter. In this filter the neighborhood is cropped at the boundary, and is therefore smaller.\n\nThis filter uses a recursive implementation - essentially the one by Huang 1979, I believe, to compute the rank, and is therefore usually a lot faster than the direct implementation. The extensions to Huang are support for arbitrary pixel types (using c++ maps) and arbitrary neighborhoods. I presume that these are not new ideas.\n\nThis filter is based on the sliding window code from the consolidatedMorphology package on InsightJournal.\n\nThe structuring element is assumed to be composed of binary values (zero or one). Only elements of the structuring element having values > 0 are candidates for affecting the center pixel.\n\nThis code was contributed in the Insight Journal paper: \"Efficient implementation of kernel filtering\" by Beare R., Lehmann G http://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 \n\n\\author Richard Beare" + "detaileddescription" : "Nonlinear filter in which each output pixel is a user defined rank of input pixels in a user defined neighborhood. The default rank is 0.5 (median). The boundary conditions are different to the standard itkMedianImageFilter. In this filter the neighborhood is cropped at the boundary, and is therefore smaller.\n\nThis filter uses a recursive implementation - essentially the one by Huang 1979, I believe, to compute the rank, and is therefore usually a lot faster than the direct implementation. The extensions to Huang are support for arbitrary pixel types (using c++ maps) and arbitrary neighborhoods. I presume that these are not new ideas.\n\nThis filter is based on the sliding window code from the consolidatedMorphology package on InsightJournal.\n\nThe structuring element is assumed to be composed of binary values (zero or one). Only elements of the structuring element having values > 0 are candidates for affecting the center pixel.\n\nThis code was contributed in the Insight Journal paper: \"Efficient implementation of kernel filtering\" by Beare R., Lehmann G https://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 \n\n\\author Richard Beare" } diff --git a/Code/BasicFilters/json/RegionalMaximaImageFilter.json b/Code/BasicFilters/json/RegionalMaximaImageFilter.json index b006034d1..0b1384676 100644 --- a/Code/BasicFilters/json/RegionalMaximaImageFilter.json +++ b/Code/BasicFilters/json/RegionalMaximaImageFilter.json @@ -61,5 +61,5 @@ } ], "briefdescription" : "Produce a binary image where foreground is the regional maxima of the input image.", - "detaileddescription" : "Regional maxima are flat zones surrounded by pixels of lower value.\n\nIf the input image is constant, the entire image can be considered as a maxima or not. The desired behavior can be selected with the SetFlatIsMaxima() method.\n\n\\author Gaetan Lehmann\n\nThis class was contributed to the Insight Journal by author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. The paper can be found at http://hdl.handle.net/1926/153 \n\n\\see ValuedRegionalMaximaImageFilter \n\\see \n\\see HConvexImageFilter \n\\see \n\\see RegionalMinimaImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li RegionalMaximaImageFilter" + "detaileddescription" : "Regional maxima are flat zones surrounded by pixels of lower value.\n\nIf the input image is constant, the entire image can be considered as a maxima or not. The desired behavior can be selected with the SetFlatIsMaxima() method.\n\n\\author Gaetan Lehmann\n\nThis class was contributed to the Insight Journal by author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. The paper can be found at https://hdl.handle.net/1926/153 \n\n\\see ValuedRegionalMaximaImageFilter \n\\see \n\\see HConvexImageFilter \n\\see \n\\see RegionalMinimaImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li RegionalMaximaImageFilter" } diff --git a/Code/BasicFilters/json/RegionalMinimaImageFilter.json b/Code/BasicFilters/json/RegionalMinimaImageFilter.json index 99400542b..380ad8b65 100644 --- a/Code/BasicFilters/json/RegionalMinimaImageFilter.json +++ b/Code/BasicFilters/json/RegionalMinimaImageFilter.json @@ -61,5 +61,5 @@ } ], "briefdescription" : "Produce a binary image where foreground is the regional minima of the input image.", - "detaileddescription" : "Regional minima are flat zones surrounded by pixels of greater value.\n\nIf the input image is constant, the entire image can be considered as a minima or not. The SetFlatIsMinima() method let the user choose which behavior to use.\n\nThis class was contribtued to the Insight Journal by\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. http://hdl.handle.net/1926/153 \n\n RegionalMaximaImageFilter MathematicalMorphologyImageFilters\n\n\\see ValuedRegionalMinimaImageFilter \n\\see \n\\see HConcaveImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li RegionalMinimaImageFilter" + "detaileddescription" : "Regional minima are flat zones surrounded by pixels of greater value.\n\nIf the input image is constant, the entire image can be considered as a minima or not. The SetFlatIsMinima() method let the user choose which behavior to use.\n\nThis class was contribtued to the Insight Journal by\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. https://hdl.handle.net/1926/153 \n\n RegionalMaximaImageFilter MathematicalMorphologyImageFilters\n\n\\see ValuedRegionalMinimaImageFilter \n\\see \n\\see HConcaveImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li RegionalMinimaImageFilter" } diff --git a/Code/BasicFilters/json/RelabelLabelMapFilter.json b/Code/BasicFilters/json/RelabelLabelMapFilter.json index 0e4cb054e..81a990bed 100644 --- a/Code/BasicFilters/json/RelabelLabelMapFilter.json +++ b/Code/BasicFilters/json/RelabelLabelMapFilter.json @@ -45,5 +45,5 @@ } ], "briefdescription" : "This filter relabels the LabelObjects; the new labels are arranged consecutively with consideration for the background value.", - "detaileddescription" : "This filter takes the LabelObjects from the input and reassigns them to the output by calling the PushLabelObject method, which by default, attempts to reorganize the labels consecutively. The user can assign an arbitrary value to the background; the filter will assign the labels consecutively by skipping the background value.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ShapeLabelObject , RelabelComponentImageFilter" + "detaileddescription" : "This filter takes the LabelObjects from the input and reassigns them to the output by calling the PushLabelObject method, which by default, attempts to reorganize the labels consecutively. The user can assign an arbitrary value to the background; the filter will assign the labels consecutively by skipping the background value.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 \\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ShapeLabelObject , RelabelComponentImageFilter" } diff --git a/Code/BasicFilters/json/RenyiEntropyThresholdImageFilter.json b/Code/BasicFilters/json/RenyiEntropyThresholdImageFilter.json index 6923b4497..d7bed8827 100644 --- a/Code/BasicFilters/json/RenyiEntropyThresholdImageFilter.json +++ b/Code/BasicFilters/json/RenyiEntropyThresholdImageFilter.json @@ -126,5 +126,5 @@ } ], "briefdescription" : "Threshold an image using the RenyiEntropy Threshold.", - "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the RenyiEntropyThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" + "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the RenyiEntropyThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" } diff --git a/Code/BasicFilters/json/RichardsonLucyDeconvolutionImageFilter.json b/Code/BasicFilters/json/RichardsonLucyDeconvolutionImageFilter.json index f75abad2d..13213128b 100644 --- a/Code/BasicFilters/json/RichardsonLucyDeconvolutionImageFilter.json +++ b/Code/BasicFilters/json/RichardsonLucyDeconvolutionImageFilter.json @@ -69,5 +69,5 @@ } ], "briefdescription" : "Deconvolve an image using the Richardson-Lucy deconvolution algorithm.", - "detaileddescription" : "This filter implements the Richardson-Lucy deconvolution algorithm as defined in Bertero M and Boccacci P, \"Introduction to Inverse\nProblems in Imaging\", 1998. The algorithm assumes that the input image has been formed by a linear shift-invariant system with a known kernel.\n\nThe Richardson-Lucy algorithm assumes that noise in the image follows a Poisson distribution and that the distribution for each pixel is independent of the other pixels.\n\nThis code was adapted from the Insight Journal contribution:\n\n\"Deconvolution: infrastructure and reference algorithms\" by Gaetan Lehmann http://hdl.handle.net/10380/3207 \n\n\\author Gaetan Lehmann, Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France\n\nCory Quammen, The University of North Carolina at Chapel Hill\n\n\\see IterativeDeconvolutionImageFilter \n\\see \n\\see LandweberDeconvolutionImageFilter \n\\see \n\\see ProjectedLandweberDeconvolutionImageFilter" + "detaileddescription" : "This filter implements the Richardson-Lucy deconvolution algorithm as defined in Bertero M and Boccacci P, \"Introduction to Inverse\nProblems in Imaging\", 1998. The algorithm assumes that the input image has been formed by a linear shift-invariant system with a known kernel.\n\nThe Richardson-Lucy algorithm assumes that noise in the image follows a Poisson distribution and that the distribution for each pixel is independent of the other pixels.\n\nThis code was adapted from the Insight Journal contribution:\n\n\"Deconvolution: infrastructure and reference algorithms\" by Gaetan Lehmann https://hdl.handle.net/10380/3207 \n\n\\author Gaetan Lehmann, Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France\n\nCory Quammen, The University of North Carolina at Chapel Hill\n\n\\see IterativeDeconvolutionImageFilter \n\\see \n\\see LandweberDeconvolutionImageFilter \n\\see \n\\see ProjectedLandweberDeconvolutionImageFilter" } diff --git a/Code/BasicFilters/json/SaltAndPepperNoiseImageFilter.json b/Code/BasicFilters/json/SaltAndPepperNoiseImageFilter.json index d0446328b..bd853943f 100644 --- a/Code/BasicFilters/json/SaltAndPepperNoiseImageFilter.json +++ b/Code/BasicFilters/json/SaltAndPepperNoiseImageFilter.json @@ -73,5 +73,5 @@ } ], "briefdescription" : "Alter an image with fixed value impulse noise, often called salt and pepper noise.", - "detaileddescription" : "Pixel alteration occurs at a user defined probability. Salt and pepper pixel are equally distributed.\n\n\\author Gaetan Lehmann\n\nThis code was contributed in the Insight Journal paper \"Noise\nSimulation\". http://hdl.handle.net/10380/3158" + "detaileddescription" : "Pixel alteration occurs at a user defined probability. Salt and pepper pixel are equally distributed.\n\n\\author Gaetan Lehmann\n\nThis code was contributed in the Insight Journal paper \"Noise\nSimulation\". https://hdl.handle.net/10380/3158" } diff --git a/Code/BasicFilters/json/ScalarChanAndVeseDenseLevelSetImageFilter.json b/Code/BasicFilters/json/ScalarChanAndVeseDenseLevelSetImageFilter.json index 1cf1f1988..7eaf7cc0b 100644 --- a/Code/BasicFilters/json/ScalarChanAndVeseDenseLevelSetImageFilter.json +++ b/Code/BasicFilters/json/ScalarChanAndVeseDenseLevelSetImageFilter.json @@ -145,5 +145,5 @@ } ], "briefdescription" : "Dense implementation of the Chan and Vese multiphase level set image filter.", - "detaileddescription" : "This code was adapted from the paper:\"An active contour model without edges\"\n T. Chan and L. Vese.\n In Scale-Space Theories in Computer Vision, pages 141-151, 1999.\n\n\\author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S.\n\nThis code was taken from the Insight Journal paper:\"Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes\"\nhttp://www.insight-journal.org/browse/publication/642\nhttp://hdl.handle.net/10380/3055\n\nThat is based on the papers:\"Level Set Segmentation: Active Contours without edge\"\nhttp://www.insight-journal.org/browse/publication/322\nhttp://hdl.handle.net/1926/1532\n\nand\n\n\"Level set segmentation using coupled active surfaces\"\nhttp://www.insight-journal.org/browse/publication/323\nhttp://hdl.handle.net/1926/1533\n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Single-phase Chan And Vese Dense Field Level Set Segmentation" + "detaileddescription" : "This code was adapted from the paper:\"An active contour model without edges\"\n T. Chan and L. Vese.\n In Scale-Space Theories in Computer Vision, pages 141-151, 1999.\n\n\\author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S.\n\nThis code was taken from the Insight Journal paper:\"Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes\"\nhttp://www.insight-journal.org/browse/publication/642\nhttps://hdl.handle.net/10380/3055\n\nThat is based on the papers:\"Level Set Segmentation: Active Contours without edge\"\nhttp://www.insight-journal.org/browse/publication/322\nhttps://hdl.handle.net/1926/1532\n\nand\n\n\"Level set segmentation using coupled active surfaces\"\nhttp://www.insight-journal.org/browse/publication/323\nhttps://hdl.handle.net/1926/1533\n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Single-phase Chan And Vese Dense Field Level Set Segmentation" } diff --git a/Code/BasicFilters/json/ScalarToRGBColormapImageFilter.json b/Code/BasicFilters/json/ScalarToRGBColormapImageFilter.json index 64b4de3e8..1088ed9fa 100644 --- a/Code/BasicFilters/json/ScalarToRGBColormapImageFilter.json +++ b/Code/BasicFilters/json/ScalarToRGBColormapImageFilter.json @@ -66,5 +66,5 @@ } ], "briefdescription" : "Implements pixel-wise intensity->rgb mapping operation on one image.", - "detaileddescription" : "This class is parameterized over the type of the input image and the type of the output image.\n\nThe input image's scalar pixel values are mapped into a color map. The color map is specified by passing the SetColormap function one of the predefined maps. The following selects the \"Hot\" colormap:\\code\n* RGBFilterType::Pointer colormapImageFilter = RGBFilterType::New();\n* colormapImageFilter->SetColormap( RGBFilterType::Hot );\n* \n\\endcode\n\n\nYou can also specify a custom color map. This is done by creating a CustomColormapFunction, and then creating lists of values for the red, green, and blue channel. An example of setting the red channel of a colormap with only 2 colors is given below. The blue and green channels should be specified in the same manner.\n\n\\code\n* // Create the custom colormap\n* typedef itk::Function::CustomColormapFunction ColormapType ;\n* ColormapType::Pointer colormap = ColormapType::New ();\n* // Setup the red channel of the colormap\n* ColormapType::ChannelType redChannel;\n* redChannel.push_back(0); redChannel.push_back(255);\n* colormap->SetRedChannel( channel );\n* \n\\endcode\n\n\nThe range of values present in the input image is the range that is mapped to the entire range of colors.\n\nThis code was contributed in the Insight Journal paper: \"Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK\" by Tustison N., Zhang H., Lehmann G., Yushkevich P., Gee J. http://hdl.handle.net/1926/1452 http://www.insight-journal.org/browse/publication/285 \n\n\\see BinaryFunctionImageFilter TernaryFunctionImageFilter\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Apply a color map to an image" + "detaileddescription" : "This class is parameterized over the type of the input image and the type of the output image.\n\nThe input image's scalar pixel values are mapped into a color map. The color map is specified by passing the SetColormap function one of the predefined maps. The following selects the \"Hot\" colormap:\\code\n* RGBFilterType::Pointer colormapImageFilter = RGBFilterType::New();\n* colormapImageFilter->SetColormap( RGBFilterType::Hot );\n* \n\\endcode\n\n\nYou can also specify a custom color map. This is done by creating a CustomColormapFunction, and then creating lists of values for the red, green, and blue channel. An example of setting the red channel of a colormap with only 2 colors is given below. The blue and green channels should be specified in the same manner.\n\n\\code\n* // Create the custom colormap\n* typedef itk::Function::CustomColormapFunction ColormapType ;\n* ColormapType::Pointer colormap = ColormapType::New ();\n* // Setup the red channel of the colormap\n* ColormapType::ChannelType redChannel;\n* redChannel.push_back(0); redChannel.push_back(255);\n* colormap->SetRedChannel( channel );\n* \n\\endcode\n\n\nThe range of values present in the input image is the range that is mapped to the entire range of colors.\n\nThis code was contributed in the Insight Journal paper: \"Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK\" by Tustison N., Zhang H., Lehmann G., Yushkevich P., Gee J. https://hdl.handle.net/1926/1452 http://www.insight-journal.org/browse/publication/285 \n\n\\see BinaryFunctionImageFilter TernaryFunctionImageFilter\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Apply a color map to an image" } diff --git a/Code/BasicFilters/json/ShanbhagThresholdImageFilter.json b/Code/BasicFilters/json/ShanbhagThresholdImageFilter.json index af140500e..0f86ef258 100644 --- a/Code/BasicFilters/json/ShanbhagThresholdImageFilter.json +++ b/Code/BasicFilters/json/ShanbhagThresholdImageFilter.json @@ -126,5 +126,5 @@ } ], "briefdescription" : "Threshold an image using the Shanbhag Threshold.", - "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the ShanbhagThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" + "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the ShanbhagThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" } diff --git a/Code/BasicFilters/json/ShotNoiseImageFilter.json b/Code/BasicFilters/json/ShotNoiseImageFilter.json index a9ef009c9..2c12fc8b2 100644 --- a/Code/BasicFilters/json/ShotNoiseImageFilter.json +++ b/Code/BasicFilters/json/ShotNoiseImageFilter.json @@ -73,5 +73,5 @@ } ], "briefdescription" : "Alter an image with shot noise.", - "detaileddescription" : "The shot noise follows a Poisson distribution.\n\n\\author Gaetan Lehmann\n\nThis code was contributed in the Insight Journal paper \"Noise\nSimulation\". http://hdl.handle.net/10380/3158" + "detaileddescription" : "The shot noise follows a Poisson distribution.\n\n\\author Gaetan Lehmann\n\nThis code was contributed in the Insight Journal paper \"Noise\nSimulation\". https://hdl.handle.net/10380/3158" } diff --git a/Code/BasicFilters/json/SpeckleNoiseImageFilter.json b/Code/BasicFilters/json/SpeckleNoiseImageFilter.json index fe93bc528..4afa33a56 100644 --- a/Code/BasicFilters/json/SpeckleNoiseImageFilter.json +++ b/Code/BasicFilters/json/SpeckleNoiseImageFilter.json @@ -73,5 +73,5 @@ } ], "briefdescription" : "Alter an image with speckle (multiplicative) noise.", - "detaileddescription" : "The speckle noise follows a Gamma distribution of mean 1 and standard deviation provided by the user. The noise is proportional to the pixel intensity.\n\n\\author Gaetan Lehmann\n\nThis code was contributed in the Insight Journal paper \"Noise\nSimulation\". http://hdl.handle.net/10380/3158" + "detaileddescription" : "The speckle noise follows a Gamma distribution of mean 1 and standard deviation provided by the user. The noise is proportional to the pixel intensity.\n\n\\author Gaetan Lehmann\n\nThis code was contributed in the Insight Journal paper \"Noise\nSimulation\". https://hdl.handle.net/10380/3158" } diff --git a/Code/BasicFilters/json/SquaredDifferenceImageFilter.json b/Code/BasicFilters/json/SquaredDifferenceImageFilter.json index 6c22441a9..8e5a10e70 100644 --- a/Code/BasicFilters/json/SquaredDifferenceImageFilter.json +++ b/Code/BasicFilters/json/SquaredDifferenceImageFilter.json @@ -44,5 +44,5 @@ } ], "briefdescription" : "Implements pixel-wise the computation of squared difference.", - "detaileddescription" : "This filter is parametrized over the types of the two input images and the type of the output image.\n\nNumeric conversions (castings) are done by the C++ defaults.\n\nThe filter will walk over all the pixels in the two input images, and for each one of them it will do the following:\n\n\n\\li cast the input 1 pixel value to double \n\n\\li cast the input 2 pixel value to double \n\n\\li compute the difference of the two pixel values\n\n\\li compute the square of the difference\n\n\\li cast the double value resulting from sqr() to the pixel type of the output image\n\n\\li store the casted value into the output image.\n\n\n\nThe filter expect all images to have the same dimension (e.g. all 2D, or all 3D, or all ND)\n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Compute the squared difference of corresponding pixels in two images" + "detaileddescription" : "This filter is parametrized over the types of the two input images and the type of the output image.\n\nNumeric conversions (castings) are done by the C++ defaults.\n\nThe filter will walk over all the pixels in the two input images, and for each one of them it will do the following:\n\n\n\\li cast the input 1 pixel value to double \n\n\\li cast the input 2 pixel value to double \n\n\\li compute the difference of the two pixel values\n\n\\li compute the square of the difference\n\n\\li cast the double value resulting from sqr() to the pixel type of the output image\n\n\\li store the casted value into the output image.\n\n\n\nThe filter expect all images to have the same dimension (e.g. all 2D, or all 3D, or all ND)\n\n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Compute the squared difference of corresponding pixels in two images" } diff --git a/Code/BasicFilters/json/StandardDeviationProjectionImageFilter.json b/Code/BasicFilters/json/StandardDeviationProjectionImageFilter.json index 67bc18941..055c7e10e 100644 --- a/Code/BasicFilters/json/StandardDeviationProjectionImageFilter.json +++ b/Code/BasicFilters/json/StandardDeviationProjectionImageFilter.json @@ -31,5 +31,5 @@ } ], "briefdescription" : "Mean projection.", - "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. The original paper can be found at http://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see MedianProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see BinaryProjectionImageFilter" + "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. The original paper can be found at https://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see MedianProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see SumProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see BinaryProjectionImageFilter" } diff --git a/Code/BasicFilters/json/SumProjectionImageFilter.json b/Code/BasicFilters/json/SumProjectionImageFilter.json index afdc6284b..5cc50df68 100644 --- a/Code/BasicFilters/json/SumProjectionImageFilter.json +++ b/Code/BasicFilters/json/SumProjectionImageFilter.json @@ -31,5 +31,5 @@ } ], "briefdescription" : "Sum projection.", - "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. The original paper can be found at http://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see MedianProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see BinaryProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter" + "detaileddescription" : "This class was contributed to the Insight Journal by Gaetan Lehmann. The original paper can be found at https://hdl.handle.net/1926/164 \n\n\\author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\n\\see ProjectionImageFilter \n\\see \n\\see MedianProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MeanProjectionImageFilter \n\\see \n\\see MaximumProjectionImageFilter \n\\see \n\\see MinimumProjectionImageFilter \n\\see \n\\see BinaryProjectionImageFilter \n\\see \n\\see StandardDeviationProjectionImageFilter" } diff --git a/Code/BasicFilters/json/ThresholdImageFilter.json b/Code/BasicFilters/json/ThresholdImageFilter.json index 5fad7465b..2b8ffbfbd 100644 --- a/Code/BasicFilters/json/ThresholdImageFilter.json +++ b/Code/BasicFilters/json/ThresholdImageFilter.json @@ -33,7 +33,7 @@ "default" : "0.0", "pixeltype" : "Output", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set the \"outside\" pixel value. The default value NumericTraits::Zero .", + "detaileddescriptionSet" : "The pixel type must support comparison operators. Set the \"outside\" pixel value. The default value NumericTraits::ZeroValue() .", "briefdescriptionGet" : "", "detaileddescriptionGet" : "Get the \"outside\" pixel value." } diff --git a/Code/BasicFilters/json/ThresholdMaximumConnectedComponentsImageFilter.json b/Code/BasicFilters/json/ThresholdMaximumConnectedComponentsImageFilter.json index 13bafc3ae..ce0640a61 100644 --- a/Code/BasicFilters/json/ThresholdMaximumConnectedComponentsImageFilter.json +++ b/Code/BasicFilters/json/ThresholdMaximumConnectedComponentsImageFilter.json @@ -12,9 +12,9 @@ "type" : "uint32_t", "default" : "0u", "briefdescriptionSet" : "", - "detaileddescriptionSet" : "Set the minimum pixel area used to count objects on the image. Thus, only objects that have a pixel area greater than the minimum pixel area will be counted as an object in the optimization portion of this filter. Essentially, it eliminates noise from being counted as an object. The default value is zero.", + "detaileddescriptionSet" : "The pixel type must support comparison operators. Set the minimum pixel area used to count objects on the image. Thus, only objects that have a pixel area greater than the minimum pixel area will be counted as an object in the optimization portion of this filter. Essentially, it eliminates noise from being counted as an object. The default value is zero.", "briefdescriptionGet" : "", - "detaileddescriptionGet" : "Set the minimum pixel area used to count objects on the image. Thus, only objects that have a pixel area greater than the minimum pixel area will be counted as an object in the optimization portion of this filter. Essentially, it eliminates noise from being counted as an object. The default value is zero." + "detaileddescriptionGet" : "The pixel type must support comparison operators. Set the minimum pixel area used to count objects on the image. Thus, only objects that have a pixel area greater than the minimum pixel area will be counted as an object in the optimization portion of this filter. Essentially, it eliminates noise from being counted as an object. The default value is zero." }, { "name" : "UpperBoundary", @@ -89,5 +89,5 @@ } ], "briefdescription" : "Finds the threshold value of an image based on maximizing the number of objects in the image that are larger than a given minimal size.", - "detaileddescription" : "\\par \nThis method is based on Topological Stable State Thresholding to calculate the threshold set point. This method is particularly effective when there are a large number of objects in a microscopy image. Compiling in Debug mode and enable the debug flag for this filter to print debug information to see how the filter focuses in on a threshold value. Please see the Insight Journal's MICCAI 2005 workshop for a complete description. References are below.\n\n\\par Parameters\nThe MinimumObjectSizeInPixels parameter is controlled through the class Get/SetMinimumObjectSizeInPixels() method. Similar to the standard itk::BinaryThresholdImageFilter the Get/SetInside and Get/SetOutside values of the threshold can be set. The GetNumberOfObjects() and GetThresholdValue() methods return the number of objects above the minimum pixel size and the calculated threshold value.\n\n\\par Automatic Thresholding in ITK\nThere are multiple methods to automatically calculate the threshold intensity value of an image. As of version 4.0, ITK has a Thresholding ( ITKThresholding ) module which contains numerous automatic thresholding methods.implements two of these. Topological Stable State Thresholding works well on images with a large number of objects to be counted.\n\n\\par References:\n1) Urish KL, August J, Huard J. \"Unsupervised segmentation for myofiber\ncounting in immunoflourescent images\". Insight Journal. ISC/NA-MIC/MICCAI Workshop on Open-Source Software (2005) Dspace handle: http://hdl.handle.net/1926/48 2) Pikaz A, Averbuch, A. \"Digital image thresholding based on topological\nstable-state\". Pattern Recognition, 29(5): 829-843, 1996.\n\n\\par \nQuestions: email Ken Urish at ken.urish(at)gmail.com Please cc the itk list serve for archival purposes." + "detaileddescription" : "\\par \nThis method is based on Topological Stable State Thresholding to calculate the threshold set point. This method is particularly effective when there are a large number of objects in a microscopy image. Compiling in Debug mode and enable the debug flag for this filter to print debug information to see how the filter focuses in on a threshold value. Please see the Insight Journal's MICCAI 2005 workshop for a complete description. References are below.\n\n\\par Parameters\nThe MinimumObjectSizeInPixels parameter is controlled through the class Get/SetMinimumObjectSizeInPixels() method. Similar to the standard itk::BinaryThresholdImageFilter the Get/SetInside and Get/SetOutside values of the threshold can be set. The GetNumberOfObjects() and GetThresholdValue() methods return the number of objects above the minimum pixel size and the calculated threshold value.\n\n\\par Automatic Thresholding in ITK\nThere are multiple methods to automatically calculate the threshold intensity value of an image. As of version 4.0, ITK has a Thresholding ( ITKThresholding ) module which contains numerous automatic thresholding methods.implements two of these. Topological Stable State Thresholding works well on images with a large number of objects to be counted.\n\n\\par References:\n1) Urish KL, August J, Huard J. \"Unsupervised segmentation for myofiber\ncounting in immunoflourescent images\". Insight Journal. ISC/NA-MIC/MICCAI Workshop on Open-Source Software (2005) Dspace handle: https://hdl.handle.net/1926/48 2) Pikaz A, Averbuch, A. \"Digital image thresholding based on topological\nstable-state\". Pattern Recognition, 29(5): 829-843, 1996.\n\n\\par \nQuestions: email Ken Urish at ken.urish(at)gmail.com Please cc the itk list serve for archival purposes." } diff --git a/Code/BasicFilters/json/TransformToDisplacementFieldFilter.json b/Code/BasicFilters/json/TransformToDisplacementFieldFilter.json index 976369c42..d112286d0 100644 --- a/Code/BasicFilters/json/TransformToDisplacementFieldFilter.json +++ b/Code/BasicFilters/json/TransformToDisplacementFieldFilter.json @@ -85,5 +85,5 @@ } ], "briefdescription" : "Generate a displacement field from a coordinate transform.", - "detaileddescription" : "Output information (spacing, size and direction) for the output image should be set. This information has the normal defaults of unit spacing, zero origin and identity direction. Optionally, the output information can be obtained from a reference image. If the reference image is provided and UseReferenceImage is On, then the spacing, origin and direction of the reference image will be used.\n\nSince this filter produces an image which is a different size than its input, it needs to override several of the methods defined in ProcessObject in order to properly manage the pipeline execution model. In particular, this filter overrides ProcessObject::GenerateOutputInformation() .\n\nThis filter is implemented as a multithreaded filter. It provides a ThreadedGenerateData() method for its implementation.\n\n\\author Marius Staring, Leiden University Medical Center, The Netherlands.\n\nThis class was taken from the Insight Journal paper: http://hdl.handle.net/1926/1387" + "detaileddescription" : "Output information (spacing, size and direction) for the output image should be set. This information has the normal defaults of unit spacing, zero origin and identity direction. Optionally, the output information can be obtained from a reference image. If the reference image is provided and UseReferenceImage is On, then the spacing, origin and direction of the reference image will be used.\n\nSince this filter produces an image which is a different size than its input, it needs to override several of the methods defined in ProcessObject in order to properly manage the pipeline execution model. In particular, this filter overrides ProcessObject::GenerateOutputInformation() .\n\nThis filter is implemented as a multithreaded filter. It provides a ThreadedGenerateData() method for its implementation.\n\n\\author Marius Staring, Leiden University Medical Center, The Netherlands.\n\nThis class was taken from the Insight Journal paper: https://hdl.handle.net/1926/1387" } diff --git a/Code/BasicFilters/json/TriangleThresholdImageFilter.json b/Code/BasicFilters/json/TriangleThresholdImageFilter.json index 6b8949a60..6e8e75acb 100644 --- a/Code/BasicFilters/json/TriangleThresholdImageFilter.json +++ b/Code/BasicFilters/json/TriangleThresholdImageFilter.json @@ -126,5 +126,5 @@ } ], "briefdescription" : "Threshold an image using the Triangle Threshold.", - "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the TriangleThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" + "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the TriangleThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" } diff --git a/Code/BasicFilters/json/ValuedRegionalMaximaImageFilter.json b/Code/BasicFilters/json/ValuedRegionalMaximaImageFilter.json index eb05cfa01..49233f4fc 100644 --- a/Code/BasicFilters/json/ValuedRegionalMaximaImageFilter.json +++ b/Code/BasicFilters/json/ValuedRegionalMaximaImageFilter.json @@ -31,5 +31,5 @@ } ], "briefdescription" : "Transforms the image so that any pixel that is not a regional maxima is set to the minimum value for the pixel type. Pixels that are regional maxima retain their value.", - "detaileddescription" : "Regional maxima are flat zones surrounded by pixels of lower value. A completely flat image will be marked as a regional maxima by this filter.\n\nThis code was contributed in the Insight Journal paper: \"Finding regional extrema - methods and performance\" by Beare R., Lehmann G. http://hdl.handle.net/1926/153 http://www.insight-journal.org/browse/publication/65 \n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\n\\see ValuedRegionalMinimaImageFilter \n\\see \n\\see ValuedRegionalExtremaImageFilter \n\\see \n\\see HMinimaImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li ValuedRegionalMaximaImageFilter" + "detaileddescription" : "Regional maxima are flat zones surrounded by pixels of lower value. A completely flat image will be marked as a regional maxima by this filter.\n\nThis code was contributed in the Insight Journal paper: \"Finding regional extrema - methods and performance\" by Beare R., Lehmann G. https://hdl.handle.net/1926/153 http://www.insight-journal.org/browse/publication/65 \n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\n\\see ValuedRegionalMinimaImageFilter \n\\see \n\\see ValuedRegionalExtremaImageFilter \n\\see \n\\see HMinimaImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li ValuedRegionalMaximaImageFilter" } diff --git a/Code/BasicFilters/json/ValuedRegionalMinimaImageFilter.json b/Code/BasicFilters/json/ValuedRegionalMinimaImageFilter.json index e10c9ca05..ba8739a80 100644 --- a/Code/BasicFilters/json/ValuedRegionalMinimaImageFilter.json +++ b/Code/BasicFilters/json/ValuedRegionalMinimaImageFilter.json @@ -31,5 +31,5 @@ } ], "briefdescription" : "Transforms the image so that any pixel that is not a regional minima is set to the maximum value for the pixel type. Pixels that are regional minima retain their value.", - "detaileddescription" : "Regional minima are flat zones surrounded by pixels of higher value. A completely flat image will be marked as a regional minima by this filter.\n\nThis code was contributed in the Insight Journal paper: \"Finding regional extrema - methods and performance\" by Beare R., Lehmann G. http://hdl.handle.net/1926/153 http://www.insight-journal.org/browse/publication/65 \n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\n\\see ValuedRegionalMaximaImageFilter , ValuedRegionalExtremaImageFilter ,\n\\see \n\\see HMinimaImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li ValuedRegionalMinimaImageFilter" + "detaileddescription" : "Regional minima are flat zones surrounded by pixels of higher value. A completely flat image will be marked as a regional minima by this filter.\n\nThis code was contributed in the Insight Journal paper: \"Finding regional extrema - methods and performance\" by Beare R., Lehmann G. https://hdl.handle.net/1926/153 http://www.insight-journal.org/browse/publication/65 \n\n\\author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia.\n\n\\see ValuedRegionalMaximaImageFilter , ValuedRegionalExtremaImageFilter ,\n\\see \n\\see HMinimaImageFilter \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li ValuedRegionalMinimaImageFilter" } diff --git a/Code/BasicFilters/json/YenThresholdImageFilter.json b/Code/BasicFilters/json/YenThresholdImageFilter.json index 22f810398..9257a829b 100644 --- a/Code/BasicFilters/json/YenThresholdImageFilter.json +++ b/Code/BasicFilters/json/YenThresholdImageFilter.json @@ -126,5 +126,5 @@ } ], "briefdescription" : "Threshold an image using the Yen Threshold.", - "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the YenThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" + "detaileddescription" : "This filter creates a binary thresholded image that separates an image into foreground and background components. The filter computes the threshold using the YenThresholdCalculator and applies that theshold to the input image using the BinaryThresholdImageFilter .\n\n\\author Richard Beare\n\nGaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.\n\nThis implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 \n\n\\see HistogramThresholdImageFilter" } diff --git a/Code/BasicFilters/json/ZeroCrossingImageFilter.json b/Code/BasicFilters/json/ZeroCrossingImageFilter.json index 9d55b8949..c5ccfeeab 100644 --- a/Code/BasicFilters/json/ZeroCrossingImageFilter.json +++ b/Code/BasicFilters/json/ZeroCrossingImageFilter.json @@ -60,5 +60,5 @@ } ], "briefdescription" : "This filter finds the closest pixel to the zero-crossings (sign changes) in a signed itk::Image .", - "detaileddescription" : "Pixels closest to zero-crossings are labeled with a foreground value. All other pixels are marked with a background value. The algorithm works by detecting differences in sign among neighbors using city-block style connectivity (4-neighbors in 2d, 6-neighbors in 3d, etc.).\n\n\\par Inputs and Outputs\nThe input to this filter is an itk::Image of arbitrary dimension. The algorithm assumes a signed data type (zero-crossings are not defined for unsigned data types), and requires that operator>, operator<, operator==, and operator!= are defined.\n\n\\par \nThe output of the filter is a binary, labeled image of user-specified type. By default, zero-crossing pixels are labeled with a default ``foreground'' value of itk::NumericTraits::One , where OutputDataType is the data type of the output image. All other pixels are labeled with a default ``background'' value of itk::NumericTraits::Zero .\n\n\\par Parameters\nThere are two parameters for this filter. ForegroundValue is the value that marks zero-crossing pixels. The BackgroundValue is the value given to all other pixels.\n\n\\see Image \n\\see \n\\see Neighborhood \n\\see \n\\see NeighborhoodOperator \n\\see \n\\see NeighborhoodIterator \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Find zero crossings in a signed image" + "detaileddescription" : "Pixels closest to zero-crossings are labeled with a foreground value. All other pixels are marked with a background value. The algorithm works by detecting differences in sign among neighbors using city-block style connectivity (4-neighbors in 2d, 6-neighbors in 3d, etc.).\n\n\\par Inputs and Outputs\nThe input to this filter is an itk::Image of arbitrary dimension. The algorithm assumes a signed data type (zero-crossings are not defined for unsigned data types), and requires that operator>, operator<, operator==, and operator!= are defined.\n\n\\par \nThe output of the filter is a binary, labeled image of user-specified type. By default, zero-crossing pixels are labeled with a default ``foreground'' value of itk::NumericTraits::OneValue() , where OutputDataType is the data type of the output image. All other pixels are labeled with a default ``background'' value of itk::NumericTraits::ZeroValue() .\n\n\\par Parameters\nThere are two parameters for this filter. ForegroundValue is the value that marks zero-crossing pixels. The BackgroundValue is the value given to all other pixels.\n\n\\see Image \n\\see \n\\see Neighborhood \n\\see \n\\see NeighborhoodOperator \n\\see \n\\see NeighborhoodIterator \n\\par Wiki Examples:\n\n\\li All Examples \n\n\\li Find zero crossings in a signed image" } From bbfed3693e6fc5a1c338bc44a94c080a50a11b2d Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Mon, 20 Jun 2016 10:44:55 +0200 Subject: [PATCH 294/412] TODO: Fix getting transform parameter object from ElastixFilter before it has run resulting in "Illegal instruction: 4" --- Testing/Unit/sitkElastixFilterTests.cxx | 40 ++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/Testing/Unit/sitkElastixFilterTests.cxx b/Testing/Unit/sitkElastixFilterTests.cxx index a141b13dc..0ca0750a4 100644 --- a/Testing/Unit/sitkElastixFilterTests.cxx +++ b/Testing/Unit/sitkElastixFilterTests.cxx @@ -41,7 +41,7 @@ TEST( ElastixFilterTest, DefaultParameterObject2D ) EXPECT_NO_THROW( elastixFilter->Update() ); } -TEST( ElastixFilterTest, UpdateOnDownstreamUpdate ) +TEST( ElastixFilterTest, UpdateOnOutputImageDownstreamUpdate ) { ParameterObject::Pointer parameterObject; EXPECT_NO_THROW( parameterObject = ParameterObject::New() ); @@ -70,6 +70,44 @@ TEST( ElastixFilterTest, UpdateOnDownstreamUpdate ) EXPECT_NO_THROW( writer->Update() ); } +/* +TEST( ElastixFilterTest, UpdateOnTransformParametersDownstreamUpdate ) +{ + ParameterObject::Pointer parameterObject; + EXPECT_NO_THROW( parameterObject = ParameterObject::New() ); + EXPECT_NO_THROW( parameterObject->SetParameterMap( ParameterObject::GetDefaultParameterMap( "rigid" ) ) ); + + typedef itk::Image< float, 2 > ImageType; + typedef itk::ImageFileReader< ImageType > ImageFileReaderType; + typedef itk::ImageFileWriter< ImageType > ImageFileWriterType; + typedef ElastixFilter< ImageType, ImageType > ElastixFilterType; + typedef TransformixFilter< ImageType > TransformixFilterType; + + ImageFileReaderType::Pointer fixedImageReader = ImageFileReaderType::New(); + fixedImageReader->SetFileName( dataFinder.GetFile( "Input/BrainProtonDensitySliceBorder20.png" ) ); + + ImageFileReaderType::Pointer movingImageReader1 = ImageFileReaderType::New(); + movingImageReader1->SetFileName( dataFinder.GetFile( "Input/BrainProtonDensitySliceR10X13Y17.png" ) ); + + ImageFileReaderType::Pointer movingImageReader2 = ImageFileReaderType::New(); + movingImageReader2->SetFileName( dataFinder.GetFile( "Input/BrainProtonDensitySliceR10X13Y17.png" ) ); + + ElastixFilterType::Pointer elastixFilter; + TransformixFilterType::Pointer transformixFilter; + ParameterObject::Pointer transformParameterObject; + + EXPECT_NO_THROW( elastixFilter = ElastixFilterType::New() ); + EXPECT_NO_THROW( elastixFilter->SetFixedImage( fixedImageReader->GetOutput() ) ); + EXPECT_NO_THROW( elastixFilter->SetMovingImage( movingImageReader1->GetOutput() ) ); + EXPECT_NO_THROW( elastixFilter->SetParameterObject( parameterObject ) ); + + // TODO: Fix getting transform parameter object resulting in "Illegal instruction: 4" + EXPECT_NO_THROW( transformixFilter->SetTransformParameterObject( elastixFilter->GetTransformParameterObject() ) ); + EXPECT_NO_THROW( transformixFilter->SetInput( movingImageReader2->GetOutput() )); + EXPECT_NO_THROW( transformixFilter->Update() ); +} +*/ + TEST( ElastixFilterTest, TranslationWithPointSets2D ) { typedef itk::Image< float, 2 > ImageType; From aaf2c1555596492a4c49a01dda31242ef3e9998e Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 20 Jun 2016 10:15:38 -0400 Subject: [PATCH 295/412] Updating Java and Python swig documentation files Change-Id: Id4a37e2e9e5183f6ad76d32b8118ec0825c346d9 --- Wrapping/Java/JavaDoc.i | 1704 ++++++++++++++++++++++++---- Wrapping/Python/PythonDocstrings.i | 1395 +++++++++++++++++++---- 2 files changed, 2647 insertions(+), 452 deletions(-) diff --git a/Wrapping/Java/JavaDoc.i b/Wrapping/Java/JavaDoc.i index dd8f6e137..ec1e66bde 100644 --- a/Wrapping/Java/JavaDoc.i +++ b/Wrapping/Java/JavaDoc.i @@ -1,5 +1,75 @@ +%typemap(javaimports) itk::ComponentByComponentImageFilter "/** + +Apply a filter or a pipeline slice by slice on an image. + +C++ includes: itkComponentByComponentImageFilter.h +*/" + +%javamethodmodifiers itk::ComponentByComponentImageFilter::GetFilter "/** +InputFilterType* itk::ComponentByComponentImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, TInternalInputImage, TInternalOutputImage >::GetFilter() +*/ +public "; + +%javamethodmodifiers itk::ComponentByComponentImageFilter::GetFilter "/** +const InputFilterType* itk::ComponentByComponentImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, TInternalInputImage, TInternalOutputImage >::GetFilter() const +*/ +public "; + +%javamethodmodifiers itk::ComponentByComponentImageFilter::itkGetConstMacro "/** +itk::ComponentByComponentImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, TInternalInputImage, TInternalOutputImage >::itkGetConstMacro(ComponentIndex, unsigned int) + +The index of the slice currently processed by the filter. This is +intended to be used with the IterationEvent sent before the processing +of each object. It contains a relevant value only during the filter +update. + +*/ +public "; + +%javamethodmodifiers itk::ComponentByComponentImageFilter::itkGetModifiableObjectMacro "/** +itk::ComponentByComponentImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, TInternalInputImage, TInternalOutputImage >::itkGetModifiableObjectMacro(InputFilter, InputFilterType) +*/ +public "; + +%javamethodmodifiers itk::ComponentByComponentImageFilter::itkGetModifiableObjectMacro "/** +itk::ComponentByComponentImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, TInternalInputImage, TInternalOutputImage >::itkGetModifiableObjectMacro(OutputFilter, OutputFilterType) +*/ +public "; + +%javamethodmodifiers itk::ComponentByComponentImageFilter::itkNewMacro "/** +itk::ComponentByComponentImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, TInternalInputImage, TInternalOutputImage >::itkNewMacro(Self) + +Standard New method. + +*/ +public "; + +%javamethodmodifiers itk::ComponentByComponentImageFilter::itkTypeMacro "/** +itk::ComponentByComponentImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, TInternalInputImage, TInternalOutputImage >::itkTypeMacro(ComponentByComponentImageFilter, ImageToImageFilter) + +Runtime information support. + +*/ +public "; + +%javamethodmodifiers itk::ComponentByComponentImageFilter::SetFilter "/** +void itk::ComponentByComponentImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, TInternalInputImage, TInternalOutputImage >::SetFilter(InputFilterType *filter) +*/ +public "; + +%javamethodmodifiers itk::ComponentByComponentImageFilter::SetInputFilter "/** +void itk::ComponentByComponentImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, TInternalInputImage, TInternalOutputImage >::SetInputFilter(InputFilterType *filter) +*/ +public "; + +%javamethodmodifiers itk::ComponentByComponentImageFilter::SetOutputFilter "/** +void itk::ComponentByComponentImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, TInternalInputImage, TInternalOutputImage >::SetOutputFilter(OutputFilterType *filter) +*/ +public "; + + %typemap(javaimports) itk::Functor::BitwiseNot "/** Performs the C++ unary bitwise NOT operator. @@ -91,7 +161,7 @@ Runtime information support. public "; %javamethodmodifiers itk::HashImageFilter::MakeOutput "/** -virtual DataObjectPointer itk::HashImageFilter< TImageType >::MakeOutput(DataObjectPointerArraySizeType idx) +virtual DataObjectPointer itk::HashImageFilter< TImageType >::MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE */ public "; @@ -142,12 +212,12 @@ C++ includes: itkSliceImageFilter.h */" %javamethodmodifiers itk::SliceImageFilter::GenerateInputRequestedRegion "/** -virtual void itk::SliceImageFilter< TInputImage, TOutputImage >::GenerateInputRequestedRegion() +virtual void itk::SliceImageFilter< TInputImage, TOutputImage >::GenerateInputRequestedRegion() ITK_OVERRIDE */ public "; %javamethodmodifiers itk::SliceImageFilter::GenerateOutputInformation "/** -virtual void itk::SliceImageFilter< TInputImage, TOutputImage >::GenerateOutputInformation() +virtual void itk::SliceImageFilter< TInputImage, TOutputImage >::GenerateOutputInformation() ITK_OVERRIDE SliceImageFilter produces an image which is a different resolution and with a different pixel spacing than its input image. @@ -259,7 +329,7 @@ public "; Computes the absolute value of each pixel. -vnl_math_abs() is used to perform the computation. +itk::Math::abs() is used to perform the computation. Wiki Examples: @@ -517,6 +587,9 @@ statistics are calculated. By altering alpha, beta and window, a host of equalization and unsharp masking filters is available. +The boundary condition ignores the part of the neighborhood outside +the image, and over-weights the valid part of the neighborhood. + For detail description, reference \"Adaptive Image Contrast Enhancement using Generalizations of Histogram Equalization.\" J.Alex Stark. IEEE Transactions on Image Processing, May 2000. @@ -599,7 +672,7 @@ public "; bool itk::simple::AdaptiveHistogramEqualizationImageFilter::GetUseLookupTable() const Set/Get whether an optimized lookup table for the intensity mapping -function is used. Default is off. +function is used. Default is off.Deprecated */ public "; @@ -641,7 +714,7 @@ public "; Self& itk::simple::AdaptiveHistogramEqualizationImageFilter::SetUseLookupTable(bool UseLookupTable) Set/Get whether an optimized lookup table for the intensity mapping -function is used. Default is off. +function is used. Default is off.Deprecated */ public "; @@ -787,7 +860,7 @@ Alter an image with additive gaussian white noise. Gaetan Lehmann This code was contributed in the Insight Journal paper \"Noise -Simulation\". http://hdl.handle.net/10380/3158 +Simulation\". https://hdl.handle.net/10380/3158 See: itk::simple::AdditiveGaussianNoise for the procedural interface @@ -997,7 +1070,7 @@ labels and assigns them to the first label of the label map. At the end of the execution of this filter, the map will contain a single filter. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -2090,7 +2163,7 @@ pixel of the output matches that of the input. The change in image geometry from a 5x5 image binned by a factor of 2x2.This code was contributed in the Insight Journal paper: \"BinShrink: A multi-resolution filter with cache efficient -averaging\" by Lowekamp B., Chen D. http://hdl.handle.net/10380/3450 +averaging\" by Lowekamp B., Chen D. https://hdl.handle.net/10380/3450 See: itk::simple::BinShrink for the procedural interface @@ -2192,7 +2265,7 @@ The structuring element is assumed to be composed of binary values Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -2364,7 +2437,7 @@ changed to BackgroundValue. The connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours. -http://hdl.handle.net/1926/1352 +https://hdl.handle.net/1926/1352 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -2890,7 +2963,7 @@ and Applications\", Second Edition, Springer, 2003. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -3021,7 +3094,7 @@ Principles and Applications\", Second Edition, Springer, 2003. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -3168,7 +3241,7 @@ have a lower label. The GetOutput() function of this class returns an itk::LabelMap . -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -3245,7 +3318,7 @@ public "; double itk::simple::BinaryImageToLabelMapFilter::GetInputForegroundValue() const Set/Get the value to be consider \"foreground\" in the input image. -Defaults to NumericTraits::max(). +Defaults to NumericTraits::max() . */ public "; @@ -3262,7 +3335,7 @@ public "; double itk::simple::BinaryImageToLabelMapFilter::GetOutputBackgroundValue() const Set/Get the value used as \"background\" in the output image. Defaults -to NumericTraits::NonpositiveMin(). +to NumericTraits::NonpositiveMin() . */ public "; @@ -3282,7 +3355,7 @@ public "; Self& itk::simple::BinaryImageToLabelMapFilter::SetInputForegroundValue(double InputForegroundValue) Set/Get the value to be consider \"foreground\" in the input image. -Defaults to NumericTraits::max(). +Defaults to NumericTraits::max() . */ public "; @@ -3291,7 +3364,7 @@ public "; Self& itk::simple::BinaryImageToLabelMapFilter::SetOutputBackgroundValue(double OutputBackgroundValue) Set/Get the value used as \"background\" in the output image. Defaults -to NumericTraits::NonpositiveMin(). +to NumericTraits::NonpositiveMin() . */ public "; @@ -3706,7 +3779,7 @@ The structuring element is assumed to be composed of binary values > 0 are candidates for affecting the center pixel. This code was contributed in the Insight Journal paper: \"Binary -morphological closing and opening image filters\" by Lehmann G. http://hdl.handle.net/1926/141 http://www.insight-journal.org/browse/publication/58 +morphological closing and opening image filters\" by Lehmann G. https://hdl.handle.net/1926/141 http://www.insight-journal.org/browse/publication/58 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -3879,7 +3952,7 @@ The structuring element is assumed to be composed of binary values > 0 are candidates for affecting the center pixel. This code was contributed in the Insight Journal paper: \"Binary -morphological closing and opening image filters\" by Lehmann G. http://hdl.handle.net/1926/141 http://www.insight-journal.org/browse/publication/58 +morphological closing and opening image filters\" by Lehmann G. https://hdl.handle.net/1926/141 http://www.insight-journal.org/browse/publication/58 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -4041,7 +4114,7 @@ Where \"!=\" is the equality operator in C++. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Wiki Examples: @@ -4158,7 +4231,7 @@ The structuring element is assumed to be composed of binary values Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -4340,7 +4413,7 @@ Binary projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -4494,7 +4567,7 @@ Second Edition, Springer, 2003. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -4646,7 +4719,7 @@ Second Edition, Springer, 2003. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -4984,7 +5057,7 @@ public "; %javamethodmodifiers itk::simple::BinaryThresholdImageFilter::SetOutsideValue "/** Self& itk::simple::BinaryThresholdImageFilter::SetOutsideValue(uint8_t OutsideValue) -Set the \"outside\" pixel value. The default value NumericTraits::Zero . +Set the \"outside\" pixel value. The default value NumericTraits::ZeroValue() . */ public "; @@ -5021,7 +5094,7 @@ BinaryThreshold projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -the original paper can be found at http://hdl.handle.net/1926/164 +the original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -5547,7 +5620,7 @@ approach. This code was contributed in the Insight Journal paper: \"Efficient -implementation of kernel filtering\" by Beare R., Lehmann G http://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 +implementation of kernel filtering\" by Beare R., Lehmann G https://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 Richard Beare @@ -5636,7 +5709,7 @@ approach. This code was contributed in the Insight Journal paper: \"Efficient -implementation of kernel filtering\" by Beare R., Lehmann G http://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 +implementation of kernel filtering\" by Beare R., Lehmann G https://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 Gaetan Lehmann @@ -5993,7 +6066,12 @@ passes as the initial translation to the transform. This second approach assumes that the moments of the anatomical objects are similar for both images and hence the best initial guess for registration is to superimpose both mass centers. Note that this -assumption will probably not hold in multi-modality registration. \\\\sa itk::CenteredTransformInitializer +assumption will probably not hold in multi-modality registration. + + +See: + itk::CenteredTransformInitializer + C++ includes: sitkCenteredTransformInitializerFilter.h */" @@ -6283,7 +6361,7 @@ This filter takes as input a label map and a list of pairs of Label Ids, to produce as output a new label map where the label Ids have been replaced according to the pairs in the list. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -7630,6 +7708,9 @@ to the behaviour of the original connected component image filter which did not produce consecutive labels or impose any particular ordering. +After the filter is executed, ObjectCount holds the number of +connected components. + See: ImageToImageFilter @@ -7708,9 +7789,6 @@ public "; %javamethodmodifiers itk::simple::ConnectedComponentImageFilter::GetObjectCount "/** uint32_t itk::simple::ConnectedComponentImageFilter::GetObjectCount() const -After the filter is executed, holds the number of connected -components. - This is a measurement. Its value is updated in the Execute methods, so the value will only be valid after an execution. @@ -8063,7 +8141,7 @@ This filter ignores the spacing, origin, and orientation of the kernel image and treats them as identical to those in the input image. This code was contributed in the Insight Journal paper: -\"Image Kernel Convolution\" by Tustison N., Gee J. http://hdl.handle.net/1926/1323 http://www.insight-journal.org/browse/publication/208 +\"Image Kernel Convolution\" by Tustison N., Gee J. https://hdl.handle.net/1926/1323 http://www.insight-journal.org/browse/publication/208 Nicholas J. Tustison @@ -9412,7 +9490,8 @@ public "; %javamethodmodifiers itk::simple::DerivativeImageFilter::GetDirection "/** unsigned int itk::simple::DerivativeImageFilter::GetDirection() const -Standard get/set macros for filter parameters. +The output pixel type must be signed. Standard get/set macros for +filter parameters. */ public "; @@ -9428,7 +9507,8 @@ public "; %javamethodmodifiers itk::simple::DerivativeImageFilter::GetOrder "/** unsigned int itk::simple::DerivativeImageFilter::GetOrder() const -Standard get/set macros for filter parameters. +The output pixel type must be signed. Standard get/set macros for +filter parameters. */ public "; @@ -9445,7 +9525,8 @@ public "; %javamethodmodifiers itk::simple::DerivativeImageFilter::SetDirection "/** Self& itk::simple::DerivativeImageFilter::SetDirection(unsigned int Direction) -Standard get/set macros for filter parameters. +The output pixel type must be signed. Standard get/set macros for +filter parameters. */ public "; @@ -9453,7 +9534,8 @@ public "; %javamethodmodifiers itk::simple::DerivativeImageFilter::SetOrder "/** Self& itk::simple::DerivativeImageFilter::SetOrder(unsigned int Order) -Standard get/set macros for filter parameters. +The output pixel type must be signed. Standard get/set macros for +filter parameters. */ public "; @@ -9539,7 +9621,7 @@ Tom Vercauteren, INRIA & Mauna Kea Technologies WARNING: This filter assumes that the fixed image type, moving image type and deformation field type all have the same number of dimensions. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/510 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/510 See: @@ -10104,7 +10186,7 @@ than itk::RecursiveGaussianImageFilter . Ivan Macia, VICOMTech, Spain, http://www.vicomtech.es - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/1290 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/1290 See: @@ -10789,7 +10871,16 @@ public "; %javamethodmodifiers itk::simple::DisplacementFieldTransform::SetDisplacementField "/** Self& itk::simple::DisplacementFieldTransform::SetDisplacementField(Image &) +Consume an image, and set the displacement field. + + parameters +WARNING: +The ownership of the input displacement image is transferred to the +constructed transform object. The input image is modified to be a +default constructed Image object. +Image must be of sitkVectorFloat64 pixel type with the number of components +equal to the image dimension. */ public "; @@ -11255,7 +11346,7 @@ public "; %javamethodmodifiers itk::simple::DoubleThresholdImageFilter::SetOutsideValue "/** Self& itk::simple::DoubleThresholdImageFilter::SetOutsideValue(uint8_t OutsideValue) -Set the \"outside\" pixel value. The default value NumericTraits::Zero . +Set the \"outside\" pixel value. The default value NumericTraits::ZeroValue() . */ public "; @@ -12351,7 +12442,7 @@ This filter ignores the spacing, origin, and orientation of the kernel image and treats them as identical to those in the input image. This code was adapted from the Insight Journal contribution: -\"FFT Based Convolution\" by Gaetan Lehmann http://hdl.handle.net/10380/3154 +\"FFT Based Convolution\" by Gaetan Lehmann https://hdl.handle.net/10380/3154 See: @@ -12590,6 +12681,126 @@ Destructor public "; +%typemap(javaimports) itk::simple::FFTPadImageFilter "/** + +Pad an image to make it suitable for an FFT transformation. + + +FFT filters usually requires a specific image size. The size is +decomposed in several prime factors, and the filter only supports +prime factors up to a maximum value. This filter automatically finds +the greatest prime factor required by the available implementation and +pads the input appropriately. + +This code was adapted from the Insight Journal contribution: + +\"FFT Based Convolution\" by Gaetan Lehmann https://hdl.handle.net/10380/3154 + + +Gaetan Lehmann + +See: + FFTShiftImageFilter + + itk::simple::FFTPad for the procedural interface + + itk::FFTPadImageFilter for the Doxygen on the original ITK class. + + +C++ includes: sitkFFTPadImageFilter.h +*/" + +%javamethodmodifiers itk::simple::FFTPadImageFilter::Execute "/** +Image itk::simple::FFTPadImageFilter::Execute(const Image &image1) + +Execute the filter on the input image + +*/ +public "; + +%javamethodmodifiers itk::simple::FFTPadImageFilter::Execute "/** +Image itk::simple::FFTPadImageFilter::Execute(const Image &image1, FFTPadImageFilter::BoundaryConditionType +boundaryCondition, int sizeGreatestPrimeFactor) + +Execute the filter on the input image with the given parameters + +*/ +public "; + +%javamethodmodifiers itk::simple::FFTPadImageFilter::FFTPadImageFilter "/** +itk::simple::FFTPadImageFilter::FFTPadImageFilter() + +Default Constructor that takes no arguments and initializes default +parameters + +*/ +public "; + +%javamethodmodifiers itk::simple::FFTPadImageFilter::GetBoundaryCondition "/** +BoundaryConditionType itk::simple::FFTPadImageFilter::GetBoundaryCondition() const +*/ +public "; + +%javamethodmodifiers itk::simple::FFTPadImageFilter::GetName "/** +std::string itk::simple::FFTPadImageFilter::GetName() const + +Name of this class + +*/ +public "; + +%javamethodmodifiers itk::simple::FFTPadImageFilter::GetSizeGreatestPrimeFactor "/** +int itk::simple::FFTPadImageFilter::GetSizeGreatestPrimeFactor() const + +Set/Get the greatest prime factor allowed on the size of the padded +image. The filter increase the size of the image to reach a size with +the greatest prime factor smaller or equal to the specified value. The +default value is 13, which is the greatest prime number for which the +FFT are precomputed in FFTW, and thus gives very good performance. A +greatest prime factor of 2 produce a size which is a power of 2, and +thus is suitable for vnl base fft filters. A greatest prime factor of +1 or less - typically 0 - disable the extra padding. + +*/ +public "; + +%javamethodmodifiers itk::simple::FFTPadImageFilter::SetBoundaryCondition "/** +Self& itk::simple::FFTPadImageFilter::SetBoundaryCondition(BoundaryConditionType BoundaryCondition) +*/ +public "; + +%javamethodmodifiers itk::simple::FFTPadImageFilter::SetSizeGreatestPrimeFactor "/** +Self& itk::simple::FFTPadImageFilter::SetSizeGreatestPrimeFactor(int SizeGreatestPrimeFactor) + +Set/Get the greatest prime factor allowed on the size of the padded +image. The filter increase the size of the image to reach a size with +the greatest prime factor smaller or equal to the specified value. The +default value is 13, which is the greatest prime number for which the +FFT are precomputed in FFTW, and thus gives very good performance. A +greatest prime factor of 2 produce a size which is a power of 2, and +thus is suitable for vnl base fft filters. A greatest prime factor of +1 or less - typically 0 - disable the extra padding. + +*/ +public "; + +%javamethodmodifiers itk::simple::FFTPadImageFilter::ToString "/** +std::string itk::simple::FFTPadImageFilter::ToString() const + +Print ourselves out + +*/ +public "; + +%javamethodmodifiers itk::simple::FFTPadImageFilter::~FFTPadImageFilter "/** +itk::simple::FFTPadImageFilter::~FFTPadImageFilter() + +Destructor + +*/ +public "; + + %typemap(javaimports) itk::simple::FFTShiftImageFilter "/** Shift the zero-frequency components of a Fourier transfrom to the @@ -12605,7 +12816,7 @@ image. For images with an odd-sized dimension, applying this filter twice will not produce the same image as the original one without using SetInverse(true) on one (and only one) of the two filters. -http://hdl.handle.net/1926/321 +https://hdl.handle.net/1926/321 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -12716,7 +12927,7 @@ Medians aren't separable, but if you want a large robust smoother to be relatively quick then it is worthwhile pretending that they are. This code was contributed in the Insight Journal paper: \"Efficient -implementation of kernel filtering\" by Beare R., Lehmann G http://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 +implementation of kernel filtering\" by Beare R., Lehmann G https://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 Richard Beare @@ -13457,7 +13668,7 @@ for each iteration is computed in DemonsRegistrationFunction . Tom Vercauteren, INRIA & Mauna Kea Technologies - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/510 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/510 WARNING: @@ -14099,7 +14310,7 @@ the remaining N dimensions. Orientation can be manipulated via the Transform cla The output image may be of any dimension. -This implementation was contributed as a paper to the Insight Journal http://hdl.handle.net/1926/500 +This implementation was contributed as a paper to the Insight Journal https://hdl.handle.net/1926/500 See: itk::simple::GaborImageSource for the procedural interface @@ -17150,7 +17361,7 @@ The output image may be of any dimension. Tustison N., Avants B., Gee J. University of Pennsylvania - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/475 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/475 See: itk::simple::GridImageSource for the procedural interface @@ -18034,8 +18245,6 @@ both images have the same number of dimensions. See: DirectedHausdorffDistanceImageFilter - itk::simple::HausdorffDistance for the procedural interface - itk::HausdorffDistanceImageFilter for the Doxygen on the original ITK class. @@ -18282,7 +18491,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -19183,6 +19392,22 @@ See: itk::LBFGSBOptimizerv4 +*/ +public "; + +%javamethodmodifiers itk::simple::ImageRegistrationMethod::SetOptimizerAsPowell "/** +Self& itk::simple::ImageRegistrationMethod::SetOptimizerAsPowell(unsigned int numberOfIterations=100, unsigned int +maximumLineIterations=100, double stepLength=1, double +stepTolerance=1e-6, double valueTolerance=1e-6) + +Powell optimization using Brent line search. + + + +See: + itk::PowellOptimizerv4 + + */ public "; @@ -19363,7 +19588,7 @@ Writer series of image from a SimpleITK image. See: -itk::simple::WriterImage for the procedural interface + itk::simple::WriteImage for the procedural interface C++ includes: sitkImageSeriesWriter.h @@ -19410,7 +19635,10 @@ image. This filter is intended to interface SimpleITK to other image processing libraries and applications that may have their own -representation of an image class. +representation of an image class. It creates a SimpleITK image which +shares the bulk data buffer as what is set. SimpleITK will not +responsible to delete the buffer afterwards, and it buffer must remain +valid while in use. See: @@ -19710,7 +19938,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -20646,7 +20874,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -21452,7 +21680,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -21642,7 +21870,7 @@ the same in the input and in the output image. The connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours. -http://hdl.handle.net/1926/1352 +https://hdl.handle.net/1926/1352 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -21781,7 +22009,7 @@ the same in the input and the output image. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -21821,7 +22049,7 @@ public "; double itk::simple::LabelImageToLabelMapFilter::GetBackgroundValue() const Set/Get the value used as \"background\" in the output image. Defaults -to NumericTraits::NonpositiveMin(). +to NumericTraits::NonpositiveMin() . */ public "; @@ -21847,7 +22075,7 @@ public "; Self& itk::simple::LabelImageToLabelMapFilter::SetBackgroundValue(double BackgroundValue) Set/Get the value used as \"background\" in the output image. Defaults -to NumericTraits::NonpositiveMin(). +to NumericTraits::NonpositiveMin() . */ public "; @@ -21869,6 +22097,537 @@ Destructor public "; +%typemap(javaimports) itk::simple::LabelIntensityStatisticsImageFilter "/** + +a convenient class to convert a label image to a label map and valuate +the statistics attributes at once + + + +Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA +de Jouy-en-Josas, France. + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + + +See: + StatisticsLabelObject , LabelStatisticsOpeningImageFilter , LabelStatisticsOpeningImageFilter + + itk::LabelImageToStatisticsLabelMapFilter for the Doxygen on the original ITK class. + + +C++ includes: sitkLabelIntensityStatisticsImageFilter.h +*/" + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::ComputeFeretDiameterOff "/** +Self& itk::simple::LabelIntensityStatisticsImageFilter::ComputeFeretDiameterOff() +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::ComputeFeretDiameterOn "/** +Self& itk::simple::LabelIntensityStatisticsImageFilter::ComputeFeretDiameterOn() + +Set the value of ComputeFeretDiameter to true or false respectfully. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::ComputePerimeterOff "/** +Self& itk::simple::LabelIntensityStatisticsImageFilter::ComputePerimeterOff() +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::ComputePerimeterOn "/** +Self& itk::simple::LabelIntensityStatisticsImageFilter::ComputePerimeterOn() + +Set the value of ComputePerimeter to true or false respectfully. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::Execute "/** +Image itk::simple::LabelIntensityStatisticsImageFilter::Execute(const Image &image, const Image &featureImage) + +Execute the filter on the input image + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::Execute "/** +Image itk::simple::LabelIntensityStatisticsImageFilter::Execute(const Image &image, const Image &featureImage, double +backgroundValue, bool computeFeretDiameter, bool computePerimeter, +uint32_t numberOfBins) + +Execute the filter on the input image with the given parameters + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetBackgroundValue "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetBackgroundValue() const + +Set/Get the value used as \"background\" in the output image. Defaults +to NumericTraits::NonpositiveMin() . + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetBoundingBox "/** +std::vector itk::simple::LabelIntensityStatisticsImageFilter::GetBoundingBox(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetCenterOfGravity "/** +std::vector itk::simple::LabelIntensityStatisticsImageFilter::GetCenterOfGravity(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetCentroid "/** +std::vector itk::simple::LabelIntensityStatisticsImageFilter::GetCentroid(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetComputeFeretDiameter "/** +bool itk::simple::LabelIntensityStatisticsImageFilter::GetComputeFeretDiameter() const + +Set/Get whether the maximum Feret diameter should be computed or not. +The defaut value is false, because of the high computation time +required. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetComputePerimeter "/** +bool itk::simple::LabelIntensityStatisticsImageFilter::GetComputePerimeter() const + +Set/Get whether the perimeter should be computed or not. The defaut +value is false, because of the high computation time required. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetElongation "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetElongation(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetEquivalentEllipsoidDiameter "/** +std::vector itk::simple::LabelIntensityStatisticsImageFilter::GetEquivalentEllipsoidDiameter(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetEquivalentSphericalPerimeter "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetEquivalentSphericalPerimeter(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetEquivalentSphericalRadius "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetEquivalentSphericalRadius(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetFeretDiameter "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetFeretDiameter(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetFlatness "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetFlatness(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetKurtosis "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetKurtosis(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetLabels "/** +std::vector itk::simple::LabelIntensityStatisticsImageFilter::GetLabels() const + +This is a measurement. Its value is updated in the Execute methods, so +the value will only be valid after an execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetMaximum "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetMaximum(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetMaximumIndex "/** +std::vector itk::simple::LabelIntensityStatisticsImageFilter::GetMaximumIndex(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetMean "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetMean(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetMedian "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetMedian(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetMinimum "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetMinimum(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetMinimumIndex "/** +std::vector itk::simple::LabelIntensityStatisticsImageFilter::GetMinimumIndex(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetName "/** +std::string itk::simple::LabelIntensityStatisticsImageFilter::GetName() const + +Name of this class + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetNumberOfBins "/** +uint32_t itk::simple::LabelIntensityStatisticsImageFilter::GetNumberOfBins() const + +Set/Get the number of bins in the histogram. Note that the histogram +is used to compute the median value, and that this option may have an +effect on the value of the median. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetNumberOfLabels "/** +uint64_t itk::simple::LabelIntensityStatisticsImageFilter::GetNumberOfLabels() + +Return the number of labels after execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetNumberOfPixels "/** +uint64_t itk::simple::LabelIntensityStatisticsImageFilter::GetNumberOfPixels(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetNumberOfPixelsOnBorder "/** +uint64_t itk::simple::LabelIntensityStatisticsImageFilter::GetNumberOfPixelsOnBorder(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetPerimeter "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetPerimeter(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetPerimeterOnBorder "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetPerimeterOnBorder(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetPerimeterOnBorderRatio "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetPerimeterOnBorderRatio(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetPhysicalSize "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetPhysicalSize(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetPrincipalAxes "/** +std::vector itk::simple::LabelIntensityStatisticsImageFilter::GetPrincipalAxes(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetPrincipalMoments "/** +std::vector itk::simple::LabelIntensityStatisticsImageFilter::GetPrincipalMoments(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetRoundness "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetRoundness(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetSkewness "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetSkewness(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetStandardDeviation "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetStandardDeviation(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetSum "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetSum(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetVariance "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetVariance(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetWeightedElongation "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetWeightedElongation(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetWeightedFlatness "/** +double itk::simple::LabelIntensityStatisticsImageFilter::GetWeightedFlatness(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetWeightedPrincipalAxes "/** +std::vector itk::simple::LabelIntensityStatisticsImageFilter::GetWeightedPrincipalAxes(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::GetWeightedPrincipalMoments "/** +std::vector itk::simple::LabelIntensityStatisticsImageFilter::GetWeightedPrincipalMoments(int64_t label) const + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::HasLabel "/** +double itk::simple::LabelIntensityStatisticsImageFilter::HasLabel(int64_t label) + +Does the specified label exist? Can only be called after a call a call +to Update(). + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::LabelIntensityStatisticsImageFilter "/** +itk::simple::LabelIntensityStatisticsImageFilter::LabelIntensityStatisticsImageFilter() + +Default Constructor that takes no arguments and initializes default +parameters + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::SetBackgroundValue "/** +Self& itk::simple::LabelIntensityStatisticsImageFilter::SetBackgroundValue(double BackgroundValue) + +Set/Get the value used as \"background\" in the output image. Defaults +to NumericTraits::NonpositiveMin() . + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::SetComputeFeretDiameter "/** +Self& itk::simple::LabelIntensityStatisticsImageFilter::SetComputeFeretDiameter(bool ComputeFeretDiameter) + +Set/Get whether the maximum Feret diameter should be computed or not. +The defaut value is false, because of the high computation time +required. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::SetComputePerimeter "/** +Self& itk::simple::LabelIntensityStatisticsImageFilter::SetComputePerimeter(bool ComputePerimeter) + +Set/Get whether the perimeter should be computed or not. The defaut +value is false, because of the high computation time required. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::SetNumberOfBins "/** +Self& itk::simple::LabelIntensityStatisticsImageFilter::SetNumberOfBins(uint32_t NumberOfBins) + +Set/Get the number of bins in the histogram. Note that the histogram +is used to compute the median value, and that this option may have an +effect on the value of the median. + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::ToString "/** +std::string itk::simple::LabelIntensityStatisticsImageFilter::ToString() const + +Print ourselves out + +*/ +public "; + +%javamethodmodifiers itk::simple::LabelIntensityStatisticsImageFilter::~LabelIntensityStatisticsImageFilter "/** +itk::simple::LabelIntensityStatisticsImageFilter::~LabelIntensityStatisticsImageFilter() + +Destructor + +*/ +public "; + + %typemap(javaimports) itk::simple::LabelMapContourOverlayImageFilter "/** Apply a colormap to the contours (outlines) of each object in a label @@ -21886,7 +22645,7 @@ produce a gray pixel with the same intensity than the input one. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -22079,7 +22838,7 @@ Negated equals true. In Both cases, the label is set with SetLabel() . Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -22128,7 +22887,7 @@ public "; double itk::simple::LabelMapMaskImageFilter::GetBackgroundValue() const Set/Get the value used as \"background\" in the output image. Defaults -to NumericTraits::Zero . +to NumericTraits::ZeroValue() . */ public "; @@ -22202,7 +22961,7 @@ public "; Self& itk::simple::LabelMapMaskImageFilter::SetBackgroundValue(double BackgroundValue) Set/Get the value used as \"background\" in the output image. Defaults -to NumericTraits::Zero . +to NumericTraits::ZeroValue() . */ public "; @@ -22283,7 +23042,7 @@ produce a gray pixel with the same intensity than the input one. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -22375,7 +23134,7 @@ foreground. The background values of the original binary image can be restored by passing this image to the filter with the SetBackgroundImage() method. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -22488,7 +23247,7 @@ LabelMapToBinaryImageFilter to a label image. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -22558,7 +23317,7 @@ Convert a LabelMap to a colored image. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -22622,7 +23381,7 @@ of two images. Background is assumed to be 0. This code was contributed in the Insight Journal paper: \"Introducing Dice, Jaccard, and Other Label Overlap Measures To ITK\" by Nicholas -J. Tustison, James C. Gee http://hdl.handle.net/10380/3141 http://www.insight-journal.org/browse/publication/707 +J. Tustison, James C. Gee https://hdl.handle.net/10380/3141 http://www.insight-journal.org/browse/publication/707 Nicholas J. Tustison @@ -22630,8 +23389,6 @@ Nicholas J. Tustison See: LabelOverlapMeasuresImageFilter - itk::simple::LabelOverlapMeasures for the procedural interface - itk::LabelOverlapMeasuresImageFilter for the Doxygen on the original ITK class. @@ -22763,7 +23520,7 @@ intensity than the input one. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This class was contributed to the Insight Journal http://hdl.handle.net/1926/172 + This class was contributed to the Insight Journal https://hdl.handle.net/1926/172 See: @@ -22879,7 +23636,7 @@ valuates the shape attribute at once. This implementation was taken from the Insight Journal paper: -http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -23282,11 +24039,7 @@ public "; %javamethodmodifiers itk::simple::LabelStatisticsImageFilter::GetBoundingBox "/** std::vector itk::simple::LabelStatisticsImageFilter::GetBoundingBox(int64_t label) const -Return the computed bounding box for a label. Defined by the closed -interval of indexes, with a lower index followed by the upper for each -dimension. i.e. [0,255,0,255]. The bounding box always has a positive -size. - +Return the computed bounding box for a label. This is an active measurement. It may be accessed while the filter is being executing in command call-backs and can be accessed after @@ -23487,7 +24240,7 @@ background label is produced. This code was contributed in the Insight Journal paper: \"The watershed transform in ITK - discussion and new developments\" by -Beare R., Lehmann G. http://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 +Beare R., Lehmann G. https://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -23585,7 +24338,7 @@ keep is selected according to their label. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -23695,8 +24448,7 @@ INPUTS All input volumes to this filter must be segmentations of an image, that is, they must have discrete pixel values where each value represents a different segmented object. - Input volumes must all contain the same size RequestedRegions. Not -all input images must contain all possible labels, but all label + Input volumes must all contain the same size RequestedRegions. Not all input images must contain all possible labels, but all label values must have the same meaning in all images. OUTPUTS @@ -23853,6 +24605,177 @@ Destructor public "; +%typemap(javaimports) itk::simple::LandmarkBasedTransformInitializerFilter "/** + +This class computes the transform that aligns the fixed and moving +images given a set of pair landmarks. The class is templated over the Transform type as well as fixed image and moving image types. The transform +computed gives the best fit transform that maps the fixed and moving +images in a least squares sense. The indices are taken to correspond, +so point 1 in the first set will get mapped close to point 1 in the +second set, etc. + +Currently, the following transforms are supported by the class: VersorRigid3DTransform Rigid2DTransform AffineTransform BSplineTransform + +An equal number of fixed and moving landmarks need to be specified +using SetFixedLandmarks() and SetMovingLandmarks() . Any number of landmarks may be specified. In the case of using +Affine or BSpline transforms, each landmark pair can contribute in the +final transform based on its defined weight. Number of weights should +be equal to the number of landmarks and can be specified using SetLandmarkWeight() . By defaults are weights are set to one. Call InitializeTransform() +to initialize the transform. + +The class is based in part on Hybrid/vtkLandmarkTransform originally +implemented in python by David G. Gobbi. + +The solution is based on Berthold K. P. Horn (1987), \"Closed-form +solution of absolute orientation using unit quaternions,\" http://people.csail.mit.edu/bkph/papers/Absolute_Orientation.pdf + +The Affine Transform initializer is based on an algorithm by H Spaeth, and is described in +the Insight Journal Article \"Affine Transformation for Landmark Based +Registration Initializer in ITK\" by Kim E.Y., Johnson H., Williams N. +available at http://midasjournal.com/browse/publication/825 + +Wiki Examples: + +All Examples + +Rigidly register one image to another using manually specified +landmarks +See: + itk::simple::LandmarkBasedTransformInitializerFilter for the procedural interface + + itk::LandmarkBasedTransformInitializer for the Doxygen on the original ITK class. + + + +C++ includes: sitkLandmarkBasedTransformInitializerFilter.h +*/" + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::Execute "/** +Transform itk::simple::LandmarkBasedTransformInitializerFilter::Execute(const Transform &transform) + +Execute the filter on the input image + +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::Execute "/** +Transform itk::simple::LandmarkBasedTransformInitializerFilter::Execute(const Transform &transform, const std::vector< double > +&fixedLandmarks, const std::vector< double > &movingLandmarks, const +std::vector< double > &landmarkWeight, const Image &referenceImage, +unsigned int numberOfControlPoints) + +Execute the filter on the input image with the given parameters + +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::GetBSplineNumberOfControlPoints "/** +unsigned int itk::simple::LandmarkBasedTransformInitializerFilter::GetBSplineNumberOfControlPoints() const + +Set/Get the number of control points + +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::GetFixedLandmarks "/** +std::vector itk::simple::LandmarkBasedTransformInitializerFilter::GetFixedLandmarks() const +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::GetLandmarkWeight "/** +std::vector itk::simple::LandmarkBasedTransformInitializerFilter::GetLandmarkWeight() const +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::GetMovingLandmarks "/** +std::vector itk::simple::LandmarkBasedTransformInitializerFilter::GetMovingLandmarks() const + +Get the shrink factors. + +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::GetName "/** +std::string itk::simple::LandmarkBasedTransformInitializerFilter::GetName() const + +Name of this class + +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::GetReferenceImage "/** +Image itk::simple::LandmarkBasedTransformInitializerFilter::GetReferenceImage() const +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::LandmarkBasedTransformInitializerFilter "/** +itk::simple::LandmarkBasedTransformInitializerFilter::LandmarkBasedTransformInitializerFilter() + +Default Constructor that takes no arguments and initializes default +parameters + +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::SetBSplineNumberOfControlPoints "/** +Self& itk::simple::LandmarkBasedTransformInitializerFilter::SetBSplineNumberOfControlPoints(unsigned int BSplineNumberOfControlPoints) + +Set/Get the number of control points + +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::SetFixedLandmarks "/** +Self& itk::simple::LandmarkBasedTransformInitializerFilter::SetFixedLandmarks(const std::vector< double > &FixedLandmarks) + +Set the Fixed landmark point containers + +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::SetLandmarkWeight "/** +Self& itk::simple::LandmarkBasedTransformInitializerFilter::SetLandmarkWeight(const std::vector< double > &LandmarkWeight) + +Set the landmark weight point containers Weight includes diagonal +elements of weight matrix + +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::SetMovingLandmarks "/** +Self& itk::simple::LandmarkBasedTransformInitializerFilter::SetMovingLandmarks(const std::vector< double > &MovingLandmarks) + +Set the Moving landmark point containers + +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::SetReferenceImage "/** +Self& itk::simple::LandmarkBasedTransformInitializerFilter::SetReferenceImage(const Image &ReferenceImage) + +Set the reference image to define the parametric domain for the +BSpline transform + +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::ToString "/** +std::string itk::simple::LandmarkBasedTransformInitializerFilter::ToString() const + +Print ourselves out + +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializerFilter::~LandmarkBasedTransformInitializerFilter "/** +itk::simple::LandmarkBasedTransformInitializerFilter::~LandmarkBasedTransformInitializerFilter() + +Destructor + +*/ +public "; + + %typemap(javaimports) itk::simple::LandweberDeconvolutionImageFilter "/** Deconvolve an image using the Landweber deconvolution algorithm. @@ -23875,7 +24798,7 @@ see ProjectedLandweberDeconvolutionImageFilter . This code was adapted from the Insight Journal contribution: \"Deconvolution: infrastructure and reference algorithms\" by Gaetan -Lehmann http://hdl.handle.net/10380/3207 +Lehmann https://hdl.handle.net/10380/3207 Gaetan Lehmann, Biologie du Developpement et de la Reproduction, INRA @@ -24930,7 +25853,7 @@ Deformably register two images using level set motion. LevelSetMotionFilter implements a deformable registration algorithm that aligns a fixed and a moving image under level set motion. The -equations of motion are similar to those of the DemonsRegistrationFilter. The main differences are: (1) Gradients of the moving image are +equations of motion are similar to those of the DemonsRegistrationFilter . The main differences are: (1) Gradients of the moving image are calculated on a smoothed image while intensity difference are measured on the original images (2) Magnitude of the motion vector is a function of the differences in intensity between the fixed and moving @@ -24978,9 +25901,9 @@ for each iteration is computed in LevelSetMotionFunction. WARNING: This filter assumes that the fixed image type, moving image type and deformation field type all have the same number of dimensions. - Ref: B.C. Vemuri, J. Ye, Y. Chen, C.M. Leonard. \" Imageregistration + Ref: B.C. Vemuri, J. Ye, Y. Chen, C.M. Leonard. \" Image registration via level-set motion: applications to atlas-based segmentation\". -Medical ImageAnalysis. Vol. 7. pp. 1-20. 2003. +Medical Image Analysis. Vol. 7. pp. 1-20. 2003. See: @@ -25194,13 +26117,13 @@ Set/Get the standard deviation used for smoothing the moving image prior to calculating gradients. The standard deviation is measured in physical units (for instance mm). Note that this smoothing value is not to be confused with the -PDEDeformableRegistrationFilter::SetStandardDeviations()method. The -method in PDEDeformableRegistrationFilteris for setting the smoothing -parameters for regularizing the deformation field between interations. -Those smoothing parameters are set in pixel units not physical units. -Deformation field smoothing is not done by default in -LevelSetMotionRegistration. This smoothing parameter is to condition -the gradient calculation and parameter is specified in physical units. +PDEDeformableRegistrationFilter::SetStandardDeviations() method. The +method in PDEDeformableRegistrationFilter is for setting the smoothing parameters for regularizing the +deformation field between interations. Those smoothing parameters are +set in pixel units not physical units. Deformation field smoothing is +not done by default in LevelSetMotionRegistration. This smoothing +parameter is to condition the gradient calculation and parameter is +specified in physical units. */ public "; @@ -25377,7 +26300,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -26032,8 +26955,8 @@ C++ includes: sitkMaskedFFTNormalizedCorrelationImageFilter.h */" %javamethodmodifiers itk::simple::MaskedFFTNormalizedCorrelationImageFilter::Execute "/** -Image itk::simple::MaskedFFTNormalizedCorrelationImageFilter::Execute(const Image &image1, const Image &image2, const Image &image3, const -Image &image4) +Image itk::simple::MaskedFFTNormalizedCorrelationImageFilter::Execute(const Image &fixedImage, const Image &movingImage, const Image +&fixedImageMask, const Image &movingImageMask) Execute the filter on the input image @@ -26041,8 +26964,9 @@ Execute the filter on the input image public "; %javamethodmodifiers itk::simple::MaskedFFTNormalizedCorrelationImageFilter::Execute "/** -Image itk::simple::MaskedFFTNormalizedCorrelationImageFilter::Execute(const Image &image1, const Image &image2, const Image &image3, const -Image &image4, uint64_t requiredNumberOfOverlappingPixels, float +Image itk::simple::MaskedFFTNormalizedCorrelationImageFilter::Execute(const Image &fixedImage, const Image &movingImage, const Image +&fixedImageMask, const Image &movingImageMask, uint64_t +requiredNumberOfOverlappingPixels, float requiredFractionOfOverlappingPixels) Execute the filter on the input image with the given parameters @@ -26131,7 +27055,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -26396,7 +27320,7 @@ Maximum projection. This class was contributed to the insight journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la reproduction, inra @@ -26602,7 +27526,7 @@ Mean projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -26814,7 +27738,7 @@ Median projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -26924,7 +27848,7 @@ objects with the same label are merged. PACK (2): MergeLabelMapFilter relabel al occur. STRICT (3): MergeLabelMapFilter keeps the labels unchanged and raises an exception if the same label is found in several images. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -27299,8 +28223,6 @@ pipeline. The implementation uses the StatisticsImageFilter . See: StatisticsImageFilter - itk::simple::MinimumMaximum for the procedural interface - itk::MinimumMaximumImageFilter for the Doxygen on the original ITK class. @@ -27377,7 +28299,7 @@ Minimum projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -27668,7 +28590,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -27996,7 +28918,7 @@ Principles and Applications\", Second Edition, Springer, 2003. This code was contributed in the Insight Journal paper: \"The watershed transform in ITK - discussion and new developments\" by -Beare R., Lehmann G. http://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 +Beare R., Lehmann G. https://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -28153,7 +29075,7 @@ Principles and Applications\", Second Edition, Springer, 2003. This code was contributed in the Insight Journal paper: \"The watershed transform in ITK - discussion and new developments\" by -Beare R., Lehmann G. http://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 +Beare R., Lehmann G. https://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -28299,6 +29221,298 @@ Destructor public "; +%typemap(javaimports) itk::simple::MultiLabelSTAPLEImageFilter "/** + +This filter performs a pixelwise combination of an arbitrary number of +input images, where each of them represents a segmentation of the same +scene (i.e., image). + + +The labelings in the images are weighted relative to each other based +on their \"performance\" as estimated by an expectation-maximization +algorithm. In the process, a ground truth segmentation is estimated, +and the estimated performances of the individual segmentations are +relative to this estimated ground truth. + +The algorithm is based on the binary STAPLE algorithm by Warfield et +al. as published originally in + +S. Warfield, K. Zou, W. Wells, \"Validation of image segmentation and +expert quality with an expectation-maximization algorithm\" in MICCAI +2002: Fifth International Conference on Medical Image Computing and Computer-Assisted Intervention, Springer-Verlag, +Heidelberg, Germany, 2002, pp. 298-306 + +The multi-label algorithm implemented here is described in detail in + +T. Rohlfing, D. B. Russakoff, and C. R. Maurer, Jr., \"Performance- +based classifier combination in atlas-based image segmentation using +expectation-maximization parameter estimation,\" IEEE Transactions on +Medical Imaging, vol. 23, pp. 983-994, Aug. 2004. + +INPUTS +All input volumes to this filter must be segmentations of an image, +that is, they must have discrete pixel values where each value +represents a different segmented object. + Input volumes must all contain the same size RequestedRegions. Not all input images must contain all possible labels, but all label +values must have the same meaning in all images. + +The filter can optionally be provided with estimates for the a priori +class probabilities through the SetPriorProbabilities function. If no +estimate is provided, one is automatically generated by analyzing the +relative frequencies of the labels in the input images. + +OUTPUTS +The filter produces a single output volume. Each output pixel contains +the label that has the highest probability of being the correct label, +based on the performance models of the individual segmentations. If +the maximum probaility is not unique, i.e., if more than one label +have a maximum probability, then an \"undecided\" label is assigned to +that output pixel. + By default, the label used for undecided pixels is the maximum label +value used in the input images plus one. Since it is possible for an +image with 8 bit pixel values to use all 256 possible label values, it +is permissible to combine 8 bit (i.e., byte) images into a 16 bit +(i.e., short) output image. + +In addition to the combined image, the estimated confusion matrices +for each of the input segmentations can be obtained through the +GetConfusionMatrix member function. + +PARAMETERS +The label used for \"undecided\" labels can be set using +SetLabelForUndecidedPixels. This functionality can be unset by calling +UnsetLabelForUndecidedPixels. + A termination threshold for the EM iteration can be defined by +calling SetTerminationUpdateThreshold. The iteration terminates once +no single parameter of any confusion matrix changes by less than this +threshold. Alternatively, a maximum number of iterations can be +specified by calling SetMaximumNumberOfIterations. The algorithm may +still terminate after a smaller number of iterations if the +termination threshold criterion is satisfied. + +EVENTS +This filter invokes IterationEvent() at each iteration of the E-M +algorithm. Setting the AbortGenerateData() flag will cause the +algorithm to halt after the current iteration and produce results just +as if it had converged. The algorithm makes no attempt to report its +progress since the number of iterations needed cannot be known in +advance. + +Torsten Rohlfing, SRI International, Neuroscience Program + +See: + itk::simple::MultiLabelSTAPLE for the procedural interface + + +C++ includes: sitkMultiLabelSTAPLEImageFilter.h +*/" + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::Execute "/** +Image itk::simple::MultiLabelSTAPLEImageFilter::Execute(const std::vector< Image > &images) + +Execute the filter on the input images + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::Execute "/** +Image itk::simple::MultiLabelSTAPLEImageFilter::Execute(const Image &image1) +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::Execute "/** +Image itk::simple::MultiLabelSTAPLEImageFilter::Execute(const Image &image1, const Image &image2) +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::Execute "/** +Image itk::simple::MultiLabelSTAPLEImageFilter::Execute(const Image &image1, const Image &image2, const Image &image3) +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::Execute "/** +Image itk::simple::MultiLabelSTAPLEImageFilter::Execute(const Image &image1, const Image &image2, const Image &image3, const +Image &image4) +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::Execute "/** +Image itk::simple::MultiLabelSTAPLEImageFilter::Execute(const Image &image1, const Image &image2, const Image &image3, const +Image &image4, const Image &image5) +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::Execute "/** +Image itk::simple::MultiLabelSTAPLEImageFilter::Execute(const std::vector< Image > &images, uint64_t labelForUndecidedPixels, +float terminationUpdateThreshold, unsigned int +maximumNumberOfIterations, std::vector< float > priorProbabilities) + +Execute the filter on the input images with the given parameters + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::Execute "/** +Image itk::simple::MultiLabelSTAPLEImageFilter::Execute(const Image &image1, uint64_t labelForUndecidedPixels, float +terminationUpdateThreshold, unsigned int maximumNumberOfIterations, +std::vector< float > priorProbabilities) +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::Execute "/** +Image itk::simple::MultiLabelSTAPLEImageFilter::Execute(const Image &image1, const Image &image2, uint64_t +labelForUndecidedPixels, float terminationUpdateThreshold, unsigned +int maximumNumberOfIterations, std::vector< float > +priorProbabilities) +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::Execute "/** +Image itk::simple::MultiLabelSTAPLEImageFilter::Execute(const Image &image1, const Image &image2, const Image &image3, +uint64_t labelForUndecidedPixels, float terminationUpdateThreshold, +unsigned int maximumNumberOfIterations, std::vector< float > +priorProbabilities) +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::Execute "/** +Image itk::simple::MultiLabelSTAPLEImageFilter::Execute(const Image &image1, const Image &image2, const Image &image3, const +Image &image4, uint64_t labelForUndecidedPixels, float +terminationUpdateThreshold, unsigned int maximumNumberOfIterations, +std::vector< float > priorProbabilities) +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::Execute "/** +Image itk::simple::MultiLabelSTAPLEImageFilter::Execute(const Image &image1, const Image &image2, const Image &image3, const +Image &image4, const Image &image5, uint64_t labelForUndecidedPixels, +float terminationUpdateThreshold, unsigned int +maximumNumberOfIterations, std::vector< float > priorProbabilities) +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::GetConfusionMatrix "/** +std::vector itk::simple::MultiLabelSTAPLEImageFilter::GetConfusionMatrix(unsigned int input) const + +Get confusion matrix for the i-th input segmentation. + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::GetLabelForUndecidedPixels "/** +uint64_t itk::simple::MultiLabelSTAPLEImageFilter::GetLabelForUndecidedPixels() const + + Get label value used for undecided pixels. + +After updating the filter, this function returns the actual label +value used for undecided pixels in the current output. Note that this +value is overwritten when SetLabelForUndecidedPixels is called and the +new value only becomes effective upon the next filter update. + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::GetMaximumNumberOfIterations "/** +unsigned int itk::simple::MultiLabelSTAPLEImageFilter::GetMaximumNumberOfIterations() const + +Set maximum number of iterations. + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::GetName "/** +std::string itk::simple::MultiLabelSTAPLEImageFilter::GetName() const + +Name of this class + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::GetPriorProbabilities "/** +std::vector itk::simple::MultiLabelSTAPLEImageFilter::GetPriorProbabilities() const + + Get prior class probabilities. + +After updating the filter, this function returns the actual prior +class probabilities. If these were not previously set by a call to +SetPriorProbabilities, then they are estimated from the input +segmentations and the result is available through this function. + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::GetTerminationUpdateThreshold "/** +float itk::simple::MultiLabelSTAPLEImageFilter::GetTerminationUpdateThreshold() const + +Set termination threshold based on confusion matrix parameter updates. + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::MultiLabelSTAPLEImageFilter "/** +itk::simple::MultiLabelSTAPLEImageFilter::MultiLabelSTAPLEImageFilter() + +Default Constructor that takes no arguments and initializes default +parameters + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::SetLabelForUndecidedPixels "/** +Self& itk::simple::MultiLabelSTAPLEImageFilter::SetLabelForUndecidedPixels(uint64_t LabelForUndecidedPixels) + +Set label value for undecided pixels. + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::SetMaximumNumberOfIterations "/** +Self& itk::simple::MultiLabelSTAPLEImageFilter::SetMaximumNumberOfIterations(unsigned int MaximumNumberOfIterations) + +Set maximum number of iterations. + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::SetPriorProbabilities "/** +Self& itk::simple::MultiLabelSTAPLEImageFilter::SetPriorProbabilities(std::vector< float > PriorProbabilities) + + Set manual estimates for the a priori class probabilities.The size +of the array must be greater than the value of the largest label. The index into the array corresponds to the label +value in the segmented image for the class. + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::SetTerminationUpdateThreshold "/** +Self& itk::simple::MultiLabelSTAPLEImageFilter::SetTerminationUpdateThreshold(float TerminationUpdateThreshold) + +Set termination threshold based on confusion matrix parameter updates. + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::ToString "/** +std::string itk::simple::MultiLabelSTAPLEImageFilter::ToString() const + +Print ourselves out + +*/ +public "; + +%javamethodmodifiers itk::simple::MultiLabelSTAPLEImageFilter::~MultiLabelSTAPLEImageFilter "/** +itk::simple::MultiLabelSTAPLEImageFilter::~MultiLabelSTAPLEImageFilter() + +Destructor + +*/ +public "; + + %typemap(javaimports) itk::simple::MultiplyImageFilter "/** Pixel-wise multiplication of two images. @@ -28411,8 +29625,10 @@ a downsampled version of the original image. A binary mask or a weighted image can be supplied. If a binary mask is specified, those voxels in the input image which correspond to the -voxels in the mask image with a value equal to m_MaskLabel, are used -to estimate the bias field. If a confidence image is specified, the +voxels in the mask image are used to estimate the bias field. If a +UseMaskLabel value is set to true, only voxels in the MaskImage that +match the MaskLabel will be used; otherwise, all non-zero voxels in +the MaskImage will be masked. If a confidence image is specified, the input voxels are weighted in the b-spline fitting routine according to the confidence voxel values. @@ -28430,7 +29646,7 @@ results with a B-spline scalar field estimate of the bias field. Nicholas J. Tustison Contributed by Nicholas J. Tustison, James C. Gee in the Insight -Journal paper: http://hdl.handle.net/10380/3053 +Journal paper: https://hdl.handle.net/10380/3053 REFERENCE J.G. Sled, A.P. Zijdenbos and A.C. Evans. \"A Nonparametric Method @@ -29255,7 +30471,7 @@ This transform is especially useful for normalizing a convolution kernel. This code was contributed in the Insight Journal paper: \"FFT based -convolution\" by Lehmann G. http://hdl.handle.net/10380/3154 +convolution\" by Lehmann G. https://hdl.handle.net/10380/3154 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -29391,7 +30607,8 @@ C++ includes: sitkNormalizedCorrelationImageFilter.h */" %javamethodmodifiers itk::simple::NormalizedCorrelationImageFilter::Execute "/** -Image itk::simple::NormalizedCorrelationImageFilter::Execute(const Image &image1, const Image &image2, const Image &image3) +Image itk::simple::NormalizedCorrelationImageFilter::Execute(const Image &image, const Image &maskImage, const Image +&templateImage) Execute the filter on the input image @@ -30125,7 +31342,7 @@ Richard Beare Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 Wiki Examples: @@ -31706,7 +32923,7 @@ images formed by counting photons, for example. This code was adapted from the Insight Journal contribution: \"Deconvolution: infrastructure and reference algorithms\" by Gaetan -Lehmann http://hdl.handle.net/10380/3207 +Lehmann https://hdl.handle.net/10380/3207 Gaetan Lehmann, Biologie du Developpement et de la Reproduction, INRA @@ -31889,7 +33106,7 @@ The structuring element is assumed to be composed of binary values > 0 are candidates for affecting the center pixel. This code was contributed in the Insight Journal paper: \"Efficient -implementation of kernel filtering\" by Beare R., Lehmann G http://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 +implementation of kernel filtering\" by Beare R., Lehmann G https://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 Richard Beare @@ -32426,8 +33643,8 @@ with the Gaussian kernel. This class implements the recursive filtering method proposed by R.Deriche in IEEE-PAMI Vol.12, No.1, January 1990, pp 78-87, \"Fast Algorithms for Low-Level Vision\" -Details of the implementation are described in the technical report: -R. Deriche, \"Recursively Implementing The Gaussian and Its +Details of the implementation are described in the technical report: R. +Deriche, \"Recursively Implementing The Gaussian and Its Derivatives\", INRIA, 1993, ftp://ftp.inria.fr/INRIA/tech-reports/RR/RR-1893.ps.gz Further improvements of the algorithm are described in: G. Farneback & @@ -32751,7 +33968,7 @@ a maxima or not. The desired behavior can be selected with the SetFlatIsMaxima() Gaetan Lehmann This class was contributed to the Insight Journal by author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de -Jouy-en-Josas, France. The paper can be found at http://hdl.handle.net/1926/153 +Jouy-en-Josas, France. The paper can be found at https://hdl.handle.net/1926/153 See: @@ -32943,7 +34160,7 @@ a minima or not. The SetFlatIsMinima() method let the user choose which behavior This class was contribtued to the Insight Journal by Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA -de Jouy-en-Josas, France. http://hdl.handle.net/1926/153 +de Jouy-en-Josas, France. https://hdl.handle.net/1926/153 RegionalMaximaImageFilter MathematicalMorphologyImageFilters @@ -33263,7 +34480,7 @@ attempts to reorganize the labels consecutively. The user can assign an arbitrary value to the background; the filter will assign the labels consecutively by skipping the background value. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. @@ -33366,7 +34583,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -33936,7 +35153,7 @@ independent of the other pixels. This code was adapted from the Insight Journal contribution: \"Deconvolution: infrastructure and reference algorithms\" by Gaetan -Lehmann http://hdl.handle.net/10380/3207 +Lehmann https://hdl.handle.net/10380/3207 Gaetan Lehmann, Biologie du Developpement et de la Reproduction, INRA @@ -34403,7 +35620,7 @@ pixel are equally distributed. Gaetan Lehmann This code was contributed in the Insight Journal paper \"Noise -Simulation\". http://hdl.handle.net/10380/3158 +Simulation\". https://hdl.handle.net/10380/3158 See: itk::simple::SaltAndPepperNoise for the procedural interface @@ -34496,14 +35713,14 @@ Vision, pages 141-151, 1999. Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. This code was taken from the Insight Journal paper:\"Cell Tracking -using Coupled Active Surfaces for Nuclei and Membranes\" http://www.insight-journal.org/browse/publication/642 http://hdl.handle.net/10380/3055 +using Coupled Active Surfaces for Nuclei and Membranes\" http://www.insight-journal.org/browse/publication/642 https://hdl.handle.net/10380/3055 That is based on the papers:\"Level Set Segmentation: Active Contours -without edge\" http://www.insight-journal.org/browse/publication/322 http://hdl.handle.net/1926/1532 +without edge\" http://www.insight-journal.org/browse/publication/322 https://hdl.handle.net/1926/1532 and -\"Level set segmentation using coupled active surfaces\" http://www.insight-journal.org/browse/publication/323 http://hdl.handle.net/1926/1533 +\"Level set segmentation using coupled active surfaces\" http://www.insight-journal.org/browse/publication/323 https://hdl.handle.net/1926/1533 Wiki Examples: @@ -35023,7 +36240,7 @@ mapped to the entire range of colors. This code was contributed in the Insight Journal paper: \"Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK\" by -Tustison N., Zhang H., Lehmann G., Yushkevich P., Gee J. http://hdl.handle.net/1926/1452 http://www.insight-journal.org/browse/publication/285 +Tustison N., Zhang H., Lehmann G., Yushkevich P., Gee J. https://hdl.handle.net/1926/1452 http://www.insight-journal.org/browse/publication/285 See: @@ -35441,7 +36658,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -35952,7 +37169,7 @@ The shot noise follows a Poisson distribution. Gaetan Lehmann This code was contributed in the Insight Journal paper \"Noise -Simulation\". http://hdl.handle.net/10380/3158 +Simulation\". https://hdl.handle.net/10380/3158 See: itk::simple::ShotNoise for the procedural interface @@ -36892,9 +38109,9 @@ unmodified. This filter is templated over the two input image type. It assume both image have the same number of dimensions. -See: - itk::simple::SimilarityIndex for the procedural interface + +See: itk::SimilarityIndexImageFilter for the Doxygen on the original ITK class. @@ -37520,7 +38737,7 @@ intensity. Gaetan Lehmann This code was contributed in the Insight Journal paper \"Noise -Simulation\". http://hdl.handle.net/10380/3158 +Simulation\". https://hdl.handle.net/10380/3158 See: itk::simple::SpeckleNoise for the procedural interface @@ -37741,8 +38958,7 @@ compute the difference of the two pixel values compute the square of the difference -cast the double value resulting from sqr() to the pixel type of the -output image +cast the double value resulting from sqr() to the pixel type of the output image store the casted value into the output image. The filter expect all images to have the same dimension (e.g. all 2D, @@ -37824,7 +39040,7 @@ Mean projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -38158,7 +39374,7 @@ Sum projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -38976,7 +40192,8 @@ public "; %javamethodmodifiers itk::simple::ThresholdImageFilter::SetOutsideValue "/** Self& itk::simple::ThresholdImageFilter::SetOutsideValue(double OutsideValue) -Set the \"outside\" pixel value. The default value NumericTraits::Zero . +The pixel type must support comparison operators. Set the \"outside\" +pixel value. The default value NumericTraits::ZeroValue() . */ public "; @@ -39046,7 +40263,7 @@ counted. References: 1) Urish KL, August J, Huard J. \"Unsupervised segmentation for myofiber counting in immunoflourescent images\". Insight Journal. ISC -/NA-MIC/MICCAI Workshop on Open-Source Software (2005) Dspace handle: http://hdl.handle.net/1926/48 2) Pikaz A, Averbuch, A. \"Digital image thresholding based on +/NA-MIC/MICCAI Workshop on Open-Source Software (2005) Dspace handle: https://hdl.handle.net/1926/48 2) Pikaz A, Averbuch, A. \"Digital image thresholding based on topological stable-state\". Pattern Recognition, 29(5): 829-843, 1996. Questions: email Ken Urish at ken.urish(at)gmail.com Please cc the itk @@ -39096,11 +40313,12 @@ public "; %javamethodmodifiers itk::simple::ThresholdMaximumConnectedComponentsImageFilter::GetMinimumObjectSizeInPixels "/** uint32_t itk::simple::ThresholdMaximumConnectedComponentsImageFilter::GetMinimumObjectSizeInPixels() const -Set the minimum pixel area used to count objects on the image. Thus, -only objects that have a pixel area greater than the minimum pixel -area will be counted as an object in the optimization portion of this -filter. Essentially, it eliminates noise from being counted as an -object. The default value is zero. +The pixel type must support comparison operators. Set the minimum +pixel area used to count objects on the image. Thus, only objects that +have a pixel area greater than the minimum pixel area will be counted +as an object in the optimization portion of this filter. Essentially, +it eliminates noise from being counted as an object. The default value +is zero. */ public "; @@ -39161,11 +40379,12 @@ public "; %javamethodmodifiers itk::simple::ThresholdMaximumConnectedComponentsImageFilter::SetMinimumObjectSizeInPixels "/** Self& itk::simple::ThresholdMaximumConnectedComponentsImageFilter::SetMinimumObjectSizeInPixels(uint32_t MinimumObjectSizeInPixels) -Set the minimum pixel area used to count objects on the image. Thus, -only objects that have a pixel area greater than the minimum pixel -area will be counted as an object in the optimization portion of this -filter. Essentially, it eliminates noise from being counted as an -object. The default value is zero. +The pixel type must support comparison operators. Set the minimum +pixel area used to count objects on the image. Thus, only objects that +have a pixel area greater than the minimum pixel area will be counted +as an object in the optimization portion of this filter. Essentially, +it eliminates noise from being counted as an object. The default value +is zero. */ public "; @@ -39958,7 +41177,7 @@ ThreadedGenerateData() method for its implementation. Marius Staring, Leiden University Medical Center, The Netherlands. - This class was taken from the Insight Journal paper: http://hdl.handle.net/1926/1387 + This class was taken from the Insight Journal paper: https://hdl.handle.net/1926/1387 See: itk::simple::TransformToDisplacementFieldFilter for the procedural interface @@ -40166,7 +41385,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -40411,7 +41630,7 @@ completely flat image will be marked as a regional maxima by this filter. This code was contributed in the Insight Journal paper: \"Finding -regional extrema - methods and performance\" by Beare R., Lehmann G. http://hdl.handle.net/1926/153 http://www.insight-journal.org/browse/publication/65 +regional extrema - methods and performance\" by Beare R., Lehmann G. https://hdl.handle.net/1926/153 http://www.insight-journal.org/browse/publication/65 Richard Beare. Department of Medicine, Monash University, Melbourne, @@ -40534,7 +41753,7 @@ completely flat image will be marked as a regional minima by this filter. This code was contributed in the Insight Journal paper: \"Finding -regional extrema - methods and performance\" by Beare R., Lehmann G. http://hdl.handle.net/1926/153 http://www.insight-journal.org/browse/publication/65 +regional extrema - methods and performance\" by Beare R., Lehmann G. https://hdl.handle.net/1926/153 http://www.insight-journal.org/browse/publication/65 Richard Beare. Department of Medicine, Monash University, Melbourne, @@ -42622,7 +43841,7 @@ Richard Beare Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -42986,8 +44205,8 @@ The input to this filter is an itk::Image of arbitrary dimension. The algorithm that operator>, operator<, operator==, and operator!= are defined. The output of the filter is a binary, labeled image of user-specified -type. By default, zero-crossing pixels are labeled with a default foreground'' value of itk::NumericTraits::One , where OutputDataType is the data type of the -output image. All other pixels are labeled with a defaultbackground'' value of itk::NumericTraits::Zero . +type. By default, zero-crossing pixels are labeled with a default foreground'' value of itk::NumericTraits::OneValue() , where OutputDataType is the data type +of the output image. All other pixels are labeled with a defaultbackground'' value of itk::NumericTraits::ZeroValue() . Parameters There are two parameters for this filter. ForegroundValue is the value that marks zero-crossing pixels. The BackgroundValue is the value @@ -45083,6 +46302,24 @@ See: itk::simple::FFTNormalizedCorrelationImageFilter for the object oriented interface +*/ +public "; + +%javamethodmodifiers itk::simple::FFTPad "/** +Image itk::simple::FFTPad(const Image &image1, FFTPadImageFilter::BoundaryConditionType boundar +yCondition=itk::simple::FFTPadImageFilter::ZERO_FLUX_NEUMANN_PAD, int +sizeGreatestPrimeFactor=5) + +Pad an image to make it suitable for an FFT transformation. + + +This function directly calls the execute method of FFTPadImageFilter in order to support a procedural API + + +See: + itk::simple::FFTPadImageFilter for the object oriented interface + + */ public "; @@ -45221,6 +46458,29 @@ const std::string SITKCommon_EXPORT itk::simple::GetPixelIDValueAsString(PixelID */ public "; +%javamethodmodifiers itk::simple::GetPixelIDValueFromString "/** +PixelIDValueType SITKCommon_EXPORT itk::simple::GetPixelIDValueFromString(const std::string &enumString) + +Function mapping enumeration names in std::string to values. + + +This function is intended for use by the R bindings. R stores the +enumeration values using the names : \"sitkUnkown\", \"sitkUInt8\", +etc from PixelIDValueEnum above. This function is used to provide the +integer values using calls like: + +val = GetPixelIDValueFromString(\"sitkInt32\") + +If the pixel type has not been instantiated then the sitkUnknown value +(-1) will be returned. If the pixel type string is not recognised +(i.e. is not in the set of tested names) then the return value is -99. +The idea is to provide a warning (via the R package) if this function +needs to be updated to match changes to PixelIDValueEnum - i.e. if a +new pixel type is added. + +*/ +public "; + %javamethodmodifiers itk::simple::GetVectorImageFromImage "/** SITKCommon_HIDDEN itk::VectorImage< TPixelType, NImageDimension >::Pointer itk::simple::GetVectorImageFromImage(itk::Image< itk::Vector< TPixelType, NLength >, NImageDimension > *img, bool transferOwnership=false) @@ -45614,23 +46874,6 @@ function=HashImageFilter::SHA1) */ public "; -%javamethodmodifiers itk::simple::HausdorffDistance "/** -Image itk::simple::HausdorffDistance(const Image &image1, const Image &image2) - -Computes the Hausdorff distance between the set of non-zero pixels of -two images. - - -This function directly calls the execute method of HausdorffDistanceImageFilter in order to support a procedural API - - -See: - itk::simple::HausdorffDistanceImageFilter for the object oriented interface - - -*/ -public "; - %javamethodmodifiers itk::simple::HConcave "/** Image itk::simple::HConcave(const Image &image1, double height=2.0, bool fullyConnected=false) @@ -46212,23 +47455,6 @@ See: itk::simple::LabelMapToRGBImageFilter for the object oriented interface -*/ -public "; - -%javamethodmodifiers itk::simple::LabelOverlapMeasures "/** -Image itk::simple::LabelOverlapMeasures(const Image &image1, const Image &image2) - -Computes overlap measures between the set same set of labels of pixels -of two images. Background is assumed to be 0. - - -This function directly calls the execute method of LabelOverlapMeasuresImageFilter in order to support a procedural API - - -See: - itk::simple::LabelOverlapMeasuresImageFilter for the object oriented interface - - */ public "; @@ -46279,6 +47505,26 @@ See: itk::simple::LabelUniqueLabelMapFilter for the object oriented interface +*/ +public "; + +%javamethodmodifiers itk::simple::LandmarkBasedTransformInitializer "/** +Transform itk::simple::LandmarkBasedTransformInitializer(const Transform &transform, const std::vector< double > +&fixedLandmarks=std::vector< double >(), const std::vector< double > +&movingLandmarks=std::vector< double >(), const std::vector< double > +&landmarkWeight=std::vector< double >(), const Image +&referenceImage=Image(), unsigned int numberOfControlPoints=4u) + +itk::simple::LandmarkBasedTransformInitializerFilter Procedural Interface + + +This function directly calls the execute method of LandmarkBasedTransformInitializerFilter in order to support a procedural API + + +See: + itk::simple::LandmarkBasedTransformInitializerFilter for the object oriented interface + + */ public "; @@ -46536,8 +47782,9 @@ See: public "; %javamethodmodifiers itk::simple::MaskedFFTNormalizedCorrelation "/** -Image itk::simple::MaskedFFTNormalizedCorrelation(const Image &image1, const Image &image2, const Image &image3, const -Image &image4, uint64_t requiredNumberOfOverlappingPixels=0u, float +Image itk::simple::MaskedFFTNormalizedCorrelation(const Image &fixedImage, const Image &movingImage, const Image +&fixedImageMask, const Image &movingImageMask, uint64_t +requiredNumberOfOverlappingPixels=0u, float requiredFractionOfOverlappingPixels=0.0) Calculate masked normalized cross correlation using FFTs. @@ -46728,22 +47975,6 @@ Image itk::simple::Minimum(double constant, const Image &image2) */ public "; -%javamethodmodifiers itk::simple::MinimumMaximum "/** -Image itk::simple::MinimumMaximum(const Image &image1) - -Computes the minimum and the maximum intensity values of an image. - - -This function directly calls the execute method of MinimumMaximumImageFilter in order to support a procedural API - - -See: - itk::simple::MinimumMaximumImageFilter for the object oriented interface - - -*/ -public "; - %javamethodmodifiers itk::simple::MinimumProjection "/** Image itk::simple::MinimumProjection(const Image &image1, unsigned int projectionDimension=0u) @@ -46997,7 +48228,8 @@ See: public "; %javamethodmodifiers itk::simple::NormalizedCorrelation "/** -Image itk::simple::NormalizedCorrelation(const Image &image1, const Image &image2, const Image &image3) +Image itk::simple::NormalizedCorrelation(const Image &image, const Image &maskImage, const Image +&templateImage) Computes the normalized correlation of an image and a template. @@ -47751,7 +48983,8 @@ See: public "; %javamethodmodifiers itk::simple::Show "/** -void SITKIO_EXPORT itk::simple::Show(const Image &image, const std::string title=\"\") +void SITKIO_EXPORT itk::simple::Show(const Image &image, const std::string &title=\"\", const bool +debugOn=false) Display an image using ImageJ @@ -47772,10 +49005,14 @@ The user can also select applications specifically for color images or environment variables. SITK_SHOW_COMMAND, SITK_SHOW_COLOR_COMMAND and SITK_SHOW_3D_COMMAND -allow the following tokens in their strings.\\\\li \\\\c \"%a\" for the ImageJ application \\\\li \\\\c \"%f\" -for SimpleITK's temporary image file +allow the following tokens in their strings. + -For example, the default SITK_SHOW_COMMAND string on Linux systems is: +\"%a\" for the ImageJ application + +\"%f\" for SimpleITK's temporary image file + For example, the default SITK_SHOW_COMMAND string on Linux systems +is: After token substitution it may become: @@ -47794,11 +49031,18 @@ Composite command to display the image in color. If the \"%f\" token is not found in the command string, the temporary file name is automatically appended to the command argument list. -By default, for a 64-bit build of SimpleITK on Macs, sitkShow searches -for ImageJ64.app. For a 32-bit Mac build, sitkShow searches for -ImageJ.app. If the user prefers a different version of ImageJ (or a -different image viewer altogether), it can be specified using the -SITK_SHOW_COMMAND environment variable. +When invoked, Show searches for Fiji first, and then ImageJ. Fiji is +the most update-to-date version of ImageJ and includes a lot of +plugins which facilitate scientific image analysis. By default, for a +64-bit build of SimpleITK on Macs, sitkShow searches for ImageJ64.app. +For a 32-bit Mac build, sitkShow searches for ImageJ.app. If the user +prefers a different version of ImageJ (or a different image viewer +altogether), it can be specified using the SITK_SHOW_COMMAND +environment variable. + +The boolean parameter debugOn prints the search path Show uses to find +ImageJ, the full path to the ImageJ it found, and the full command +line used to invoke ImageJ. */ public "; @@ -47869,23 +49113,6 @@ See: itk::simple::SignedMaurerDistanceMapImageFilter for the object oriented interface -*/ -public "; - -%javamethodmodifiers itk::simple::SimilarityIndex "/** -Image itk::simple::SimilarityIndex(const Image &image1, const Image &image2) - -Measures the similarity between the set of non-zero pixels of two -images. - - -This function directly calls the execute method of SimilarityIndexImageFilter in order to support a procedural API - - -See: - itk::simple::SimilarityIndexImageFilter for the object oriented interface - - */ public "; @@ -47970,6 +49197,11 @@ generated. */ public "; +%javamethodmodifiers itk::simple::sitkSTLVectorToITKPointVector "/** +TITKPointVector SITKCommon_HIDDEN itk::simple::sitkSTLVectorToITKPointVector(const std::vector< TType > &in) +*/ +public "; + %javamethodmodifiers itk::simple::Slice "/** Image itk::simple::Slice(const Image &image1, const std::vector< int32_t > &start=std::vector< int32_t >(3, 0), const std::vector< int32_t > &stop=std::vector< diff --git a/Wrapping/Python/PythonDocstrings.i b/Wrapping/Python/PythonDocstrings.i index c5a29e079..c8da50afb 100644 --- a/Wrapping/Python/PythonDocstrings.i +++ b/Wrapping/Python/PythonDocstrings.i @@ -1,5 +1,55 @@ +%feature("docstring") itk::ComponentByComponentImageFilter " + +Apply a filter or a pipeline slice by slice on an image. + +C++ includes: itkComponentByComponentImageFilter.h +"; + +%feature("docstring") itk::ComponentByComponentImageFilter::GetFilter " +"; + +%feature("docstring") itk::ComponentByComponentImageFilter::GetFilter " +"; + +%feature("docstring") itk::ComponentByComponentImageFilter::itkGetConstMacro " + +The index of the slice currently processed by the filter. This is +intended to be used with the IterationEvent sent before the processing +of each object. It contains a relevant value only during the filter +update. + +"; + +%feature("docstring") itk::ComponentByComponentImageFilter::itkGetModifiableObjectMacro " +"; + +%feature("docstring") itk::ComponentByComponentImageFilter::itkGetModifiableObjectMacro " +"; + +%feature("docstring") itk::ComponentByComponentImageFilter::itkNewMacro " + +Standard New method. + +"; + +%feature("docstring") itk::ComponentByComponentImageFilter::itkTypeMacro " + +Runtime information support. + +"; + +%feature("docstring") itk::ComponentByComponentImageFilter::SetFilter " +"; + +%feature("docstring") itk::ComponentByComponentImageFilter::SetInputFilter " +"; + +%feature("docstring") itk::ComponentByComponentImageFilter::SetOutputFilter " +"; + + %feature("docstring") itk::Functor::BitwiseNot " Performs the C++ unary bitwise NOT operator. @@ -205,7 +255,7 @@ C++ includes: itkTransformIOFactoryRegisterManager.h Computes the absolute value of each pixel. -vnl_math_abs() is used to perform the computation. +itk::Math::abs() is used to perform the computation. Wiki Examples: @@ -429,6 +479,9 @@ statistics are calculated. By altering alpha, beta and window, a host of equalization and unsharp masking filters is available. +The boundary condition ignores the part of the neighborhood outside +the image, and over-weights the valid part of the neighborhood. + For detail description, reference \"Adaptive Image Contrast Enhancement using Generalizations of Histogram Equalization.\" J.Alex Stark. IEEE Transactions on Image Processing, May 2000. @@ -495,7 +548,7 @@ Name of this class %feature("docstring") itk::simple::AdaptiveHistogramEqualizationImageFilter::GetUseLookupTable " Set/Get whether an optimized lookup table for the intensity mapping -function is used. Default is off. +function is used. Default is off.Deprecated "; @@ -527,7 +580,7 @@ Set the values of the Radius vector all to value %feature("docstring") itk::simple::AdaptiveHistogramEqualizationImageFilter::SetUseLookupTable " Set/Get whether an optimized lookup table for the intensity mapping -function is used. Default is off. +function is used. Default is off.Deprecated "; @@ -650,7 +703,7 @@ Alter an image with additive gaussian white noise. Gaetan Lehmann This code was contributed in the Insight Journal paper \"Noise -Simulation\". http://hdl.handle.net/10380/3158 +Simulation\". https://hdl.handle.net/10380/3158 See: itk::simple::AdditiveGaussianNoise for the procedural interface @@ -801,7 +854,7 @@ labels and assigns them to the first label of the label map. At the end of the execution of this filter, the map will contain a single filter. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -1717,7 +1770,7 @@ pixel of the output matches that of the input. The change in image geometry from a 5x5 image binned by a factor of 2x2.This code was contributed in the Insight Journal paper: \"BinShrink: A multi-resolution filter with cache efficient -averaging\" by Lowekamp B., Chen D. http://hdl.handle.net/10380/3450 +averaging\" by Lowekamp B., Chen D. https://hdl.handle.net/10380/3450 See: itk::simple::BinShrink for the procedural interface @@ -1800,7 +1853,7 @@ The structuring element is assumed to be composed of binary values Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -1936,7 +1989,7 @@ changed to BackgroundValue. The connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours. -http://hdl.handle.net/1926/1352 +https://hdl.handle.net/1926/1352 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -2351,7 +2404,7 @@ and Applications\", Second Edition, Springer, 2003. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -2458,7 +2511,7 @@ Principles and Applications\", Second Edition, Springer, 2003. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -2576,7 +2629,7 @@ have a lower label. The GetOutput() function of this class returns an itk::LabelMap . -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -2639,7 +2692,7 @@ FullyConnectedOn. %feature("docstring") itk::simple::BinaryImageToLabelMapFilter::GetInputForegroundValue " Set/Get the value to be consider \"foreground\" in the input image. -Defaults to NumericTraits::max(). +Defaults to NumericTraits::max() . "; @@ -2652,7 +2705,7 @@ Name of this class %feature("docstring") itk::simple::BinaryImageToLabelMapFilter::GetOutputBackgroundValue " Set/Get the value used as \"background\" in the output image. Defaults -to NumericTraits::NonpositiveMin(). +to NumericTraits::NonpositiveMin() . "; @@ -2668,14 +2721,14 @@ FullyConnectedOn. %feature("docstring") itk::simple::BinaryImageToLabelMapFilter::SetInputForegroundValue " Set/Get the value to be consider \"foreground\" in the input image. -Defaults to NumericTraits::max(). +Defaults to NumericTraits::max() . "; %feature("docstring") itk::simple::BinaryImageToLabelMapFilter::SetOutputBackgroundValue " Set/Get the value used as \"background\" in the output image. Defaults -to NumericTraits::NonpositiveMin(). +to NumericTraits::NonpositiveMin() . "; @@ -3019,7 +3072,7 @@ The structuring element is assumed to be composed of binary values > 0 are candidates for affecting the center pixel. This code was contributed in the Insight Journal paper: \"Binary -morphological closing and opening image filters\" by Lehmann G. http://hdl.handle.net/1926/141 http://www.insight-journal.org/browse/publication/58 +morphological closing and opening image filters\" by Lehmann G. https://hdl.handle.net/1926/141 http://www.insight-journal.org/browse/publication/58 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -3156,7 +3209,7 @@ The structuring element is assumed to be composed of binary values > 0 are candidates for affecting the center pixel. This code was contributed in the Insight Journal paper: \"Binary -morphological closing and opening image filters\" by Lehmann G. http://hdl.handle.net/1926/141 http://www.insight-journal.org/browse/publication/58 +morphological closing and opening image filters\" by Lehmann G. https://hdl.handle.net/1926/141 http://www.insight-journal.org/browse/publication/58 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -3286,7 +3339,7 @@ Where \"!=\" is the equality operator in C++. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Wiki Examples: @@ -3383,7 +3436,7 @@ The structuring element is assumed to be composed of binary values Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -3524,7 +3577,7 @@ Binary projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -3653,7 +3706,7 @@ Second Edition, Springer, 2003. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -3776,7 +3829,7 @@ Second Edition, Springer, 2003. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -4053,7 +4106,7 @@ Set the \"inside\" pixel value. The default value NumericTraits %feature("docstring") itk::simple::BinaryThresholdImageFilter::SetOutsideValue " -Set the \"outside\" pixel value. The default value NumericTraits::Zero . +Set the \"outside\" pixel value. The default value NumericTraits::ZeroValue() . "; @@ -4083,7 +4136,7 @@ BinaryThreshold projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -the original paper can be found at http://hdl.handle.net/1926/164 +the original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -4512,7 +4565,7 @@ approach. This code was contributed in the Insight Journal paper: \"Efficient -implementation of kernel filtering\" by Beare R., Lehmann G http://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 +implementation of kernel filtering\" by Beare R., Lehmann G https://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 Richard Beare @@ -4583,7 +4636,7 @@ approach. This code was contributed in the Insight Journal paper: \"Efficient -implementation of kernel filtering\" by Beare R., Lehmann G http://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 +implementation of kernel filtering\" by Beare R., Lehmann G https://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 Gaetan Lehmann @@ -4874,7 +4927,12 @@ passes as the initial translation to the transform. This second approach assumes that the moments of the anatomical objects are similar for both images and hence the best initial guess for registration is to superimpose both mass centers. Note that this -assumption will probably not hold in multi-modality registration. \\\\sa itk::CenteredTransformInitializer +assumption will probably not hold in multi-modality registration. + + +See: + itk::CenteredTransformInitializer + C++ includes: sitkCenteredTransformInitializerFilter.h "; @@ -5103,7 +5161,7 @@ This filter takes as input a label map and a list of pairs of Label Ids, to produce as output a new label map where the label Ids have been replaced according to the pairs in the list. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -6183,6 +6241,9 @@ to the behaviour of the original connected component image filter which did not produce consecutive labels or impose any particular ordering. +After the filter is executed, ObjectCount holds the number of +connected components. + See: ImageToImageFilter @@ -6246,9 +6307,6 @@ Name of this class %feature("docstring") itk::simple::ConnectedComponentImageFilter::GetObjectCount " -After the filter is executed, holds the number of connected -components. - This is a measurement. Its value is updated in the Execute methods, so the value will only be valid after an execution. @@ -6528,7 +6586,7 @@ This filter ignores the spacing, origin, and orientation of the kernel image and treats them as identical to those in the input image. This code was contributed in the Insight Journal paper: -\"Image Kernel Convolution\" by Tustison N., Gee J. http://hdl.handle.net/1926/1323 http://www.insight-journal.org/browse/publication/208 +\"Image Kernel Convolution\" by Tustison N., Gee J. https://hdl.handle.net/1926/1323 http://www.insight-journal.org/browse/publication/208 Nicholas J. Tustison @@ -7600,7 +7658,8 @@ Execute the filter on the input image with the given parameters %feature("docstring") itk::simple::DerivativeImageFilter::GetDirection " -Standard get/set macros for filter parameters. +The output pixel type must be signed. Standard get/set macros for +filter parameters. "; @@ -7612,7 +7671,8 @@ Name of this class %feature("docstring") itk::simple::DerivativeImageFilter::GetOrder " -Standard get/set macros for filter parameters. +The output pixel type must be signed. Standard get/set macros for +filter parameters. "; @@ -7625,13 +7685,15 @@ image in its calculations %feature("docstring") itk::simple::DerivativeImageFilter::SetDirection " -Standard get/set macros for filter parameters. +The output pixel type must be signed. Standard get/set macros for +filter parameters. "; %feature("docstring") itk::simple::DerivativeImageFilter::SetOrder " -Standard get/set macros for filter parameters. +The output pixel type must be signed. Standard get/set macros for +filter parameters. "; @@ -7706,7 +7768,7 @@ Tom Vercauteren, INRIA & Mauna Kea Technologies WARNING: This filter assumes that the fixed image type, moving image type and deformation field type all have the same number of dimensions. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/510 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/510 See: @@ -8129,7 +8191,7 @@ than itk::RecursiveGaussianImageFilter . Ivan Macia, VICOMTech, Spain, http://www.vicomtech.es - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/1290 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/1290 See: @@ -8691,7 +8753,16 @@ Name of this class %feature("docstring") itk::simple::DisplacementFieldTransform::SetDisplacementField " +Consume an image, and set the displacement field. + + parameters +WARNING: +The ownership of the input displacement image is transferred to the +constructed transform object. The input image is modified to be a +default constructed Image object. +Image must be of sitkVectorFloat64 pixel type with the number of components +equal to the image dimension. "; @@ -9067,7 +9138,7 @@ Set the \"inside\" pixel value. The default value NumericTraits %feature("docstring") itk::simple::DoubleThresholdImageFilter::SetOutsideValue " -Set the \"outside\" pixel value. The default value NumericTraits::Zero . +Set the \"outside\" pixel value. The default value NumericTraits::ZeroValue() . "; @@ -9938,7 +10009,7 @@ This filter ignores the spacing, origin, and orientation of the kernel image and treats them as identical to those in the input image. This code was adapted from the Insight Journal contribution: -\"FFT Based Convolution\" by Gaetan Lehmann http://hdl.handle.net/10380/3154 +\"FFT Based Convolution\" by Gaetan Lehmann https://hdl.handle.net/10380/3154 See: @@ -10130,6 +10201,105 @@ Destructor "; +%feature("docstring") itk::simple::FFTPadImageFilter " + +Pad an image to make it suitable for an FFT transformation. + + +FFT filters usually requires a specific image size. The size is +decomposed in several prime factors, and the filter only supports +prime factors up to a maximum value. This filter automatically finds +the greatest prime factor required by the available implementation and +pads the input appropriately. + +This code was adapted from the Insight Journal contribution: + +\"FFT Based Convolution\" by Gaetan Lehmann https://hdl.handle.net/10380/3154 + + +Gaetan Lehmann + +See: + FFTShiftImageFilter + + itk::simple::FFTPad for the procedural interface + + itk::FFTPadImageFilter for the Doxygen on the original ITK class. + + +C++ includes: sitkFFTPadImageFilter.h +"; + +%feature("docstring") itk::simple::FFTPadImageFilter::Execute " + +Execute the filter on the input image + +"; + +%feature("docstring") itk::simple::FFTPadImageFilter::Execute " + +Execute the filter on the input image with the given parameters + +"; + +%feature("docstring") itk::simple::FFTPadImageFilter::FFTPadImageFilter " + +Default Constructor that takes no arguments and initializes default +parameters + +"; + +%feature("docstring") itk::simple::FFTPadImageFilter::GetBoundaryCondition " +"; + +%feature("docstring") itk::simple::FFTPadImageFilter::GetName " + +Name of this class + +"; + +%feature("docstring") itk::simple::FFTPadImageFilter::GetSizeGreatestPrimeFactor " + +Set/Get the greatest prime factor allowed on the size of the padded +image. The filter increase the size of the image to reach a size with +the greatest prime factor smaller or equal to the specified value. The +default value is 13, which is the greatest prime number for which the +FFT are precomputed in FFTW, and thus gives very good performance. A +greatest prime factor of 2 produce a size which is a power of 2, and +thus is suitable for vnl base fft filters. A greatest prime factor of +1 or less - typically 0 - disable the extra padding. + +"; + +%feature("docstring") itk::simple::FFTPadImageFilter::SetBoundaryCondition " +"; + +%feature("docstring") itk::simple::FFTPadImageFilter::SetSizeGreatestPrimeFactor " + +Set/Get the greatest prime factor allowed on the size of the padded +image. The filter increase the size of the image to reach a size with +the greatest prime factor smaller or equal to the specified value. The +default value is 13, which is the greatest prime number for which the +FFT are precomputed in FFTW, and thus gives very good performance. A +greatest prime factor of 2 produce a size which is a power of 2, and +thus is suitable for vnl base fft filters. A greatest prime factor of +1 or less - typically 0 - disable the extra padding. + +"; + +%feature("docstring") itk::simple::FFTPadImageFilter::ToString " + +Print ourselves out + +"; + +%feature("docstring") itk::simple::FFTPadImageFilter::~FFTPadImageFilter " + +Destructor + +"; + + %feature("docstring") itk::simple::FFTShiftImageFilter " Shift the zero-frequency components of a Fourier transfrom to the @@ -10145,7 +10315,7 @@ image. For images with an odd-sized dimension, applying this filter twice will not produce the same image as the original one without using SetInverse(true) on one (and only one) of the two filters. -http://hdl.handle.net/1926/321 +https://hdl.handle.net/1926/321 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -10236,7 +10406,7 @@ Medians aren't separable, but if you want a large robust smoother to be relatively quick then it is worthwhile pretending that they are. This code was contributed in the Insight Journal paper: \"Efficient -implementation of kernel filtering\" by Beare R., Lehmann G http://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 +implementation of kernel filtering\" by Beare R., Lehmann G https://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 Richard Beare @@ -10844,7 +11014,7 @@ for each iteration is computed in DemonsRegistrationFunction . Tom Vercauteren, INRIA & Mauna Kea Technologies - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/510 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/510 WARNING: @@ -11337,7 +11507,7 @@ the remaining N dimensions. Orientation can be manipulated via the Transform cla The output image may be of any dimension. -This implementation was contributed as a paper to the Insight Journal http://hdl.handle.net/1926/500 +This implementation was contributed as a paper to the Insight Journal https://hdl.handle.net/1926/500 See: itk::simple::GaborImageSource for the procedural interface @@ -13757,7 +13927,7 @@ The output image may be of any dimension. Tustison N., Avants B., Gee J. University of Pennsylvania - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/475 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/475 See: itk::simple::GridImageSource for the procedural interface @@ -14467,8 +14637,6 @@ both images have the same number of dimensions. See: DirectedHausdorffDistanceImageFilter - itk::simple::HausdorffDistance for the procedural interface - itk::HausdorffDistanceImageFilter for the Doxygen on the original ITK class. @@ -14671,7 +14839,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -15372,6 +15540,18 @@ See: itk::LBFGSBOptimizerv4 +"; + +%feature("docstring") itk::simple::ImageRegistrationMethod::SetOptimizerAsPowell " + +Powell optimization using Brent line search. + + + +See: + itk::PowellOptimizerv4 + + "; %feature("docstring") itk::simple::ImageRegistrationMethod::SetOptimizerAsRegularStepGradientDescent " @@ -15516,7 +15696,7 @@ Writer series of image from a SimpleITK image. See: -itk::simple::WriterImage for the procedural interface + itk::simple::WriteImage for the procedural interface C++ includes: sitkImageSeriesWriter.h @@ -15552,7 +15732,10 @@ image. This filter is intended to interface SimpleITK to other image processing libraries and applications that may have their own -representation of an image class. +representation of an image class. It creates a SimpleITK image which +shares the bulk data buffer as what is set. SimpleITK will not +responsible to delete the buffer afterwards, and it buffer must remain +valid while in use. See: @@ -15779,7 +15962,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -16517,7 +16700,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -17138,7 +17321,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -17283,7 +17466,7 @@ the same in the input and in the output image. The connectivity can be changed to minimum or maximum connectivity with SetFullyConnected() . Full connectivity produces thicker contours. -http://hdl.handle.net/1926/1352 +https://hdl.handle.net/1926/1352 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -17398,7 +17581,7 @@ the same in the input and the output image. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -17433,7 +17616,7 @@ Execute the filter on the input image with the given parameters %feature("docstring") itk::simple::LabelImageToLabelMapFilter::GetBackgroundValue " Set/Get the value used as \"background\" in the output image. Defaults -to NumericTraits::NonpositiveMin(). +to NumericTraits::NonpositiveMin() . "; @@ -17453,7 +17636,7 @@ parameters %feature("docstring") itk::simple::LabelImageToLabelMapFilter::SetBackgroundValue " Set/Get the value used as \"background\" in the output image. Defaults -to NumericTraits::NonpositiveMin(). +to NumericTraits::NonpositiveMin() . "; @@ -17470,6 +17653,427 @@ Destructor "; +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter " + +a convenient class to convert a label image to a label map and valuate +the statistics attributes at once + + + +Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA +de Jouy-en-Josas, France. + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + + +See: + StatisticsLabelObject , LabelStatisticsOpeningImageFilter , LabelStatisticsOpeningImageFilter + + itk::LabelImageToStatisticsLabelMapFilter for the Doxygen on the original ITK class. + + +C++ includes: sitkLabelIntensityStatisticsImageFilter.h +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::ComputeFeretDiameterOff " +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::ComputeFeretDiameterOn " + +Set the value of ComputeFeretDiameter to true or false respectfully. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::ComputePerimeterOff " +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::ComputePerimeterOn " + +Set the value of ComputePerimeter to true or false respectfully. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::Execute " + +Execute the filter on the input image + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::Execute " + +Execute the filter on the input image with the given parameters + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetBackgroundValue " + +Set/Get the value used as \"background\" in the output image. Defaults +to NumericTraits::NonpositiveMin() . + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetBoundingBox " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetCenterOfGravity " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetCentroid " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetComputeFeretDiameter " + +Set/Get whether the maximum Feret diameter should be computed or not. +The defaut value is false, because of the high computation time +required. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetComputePerimeter " + +Set/Get whether the perimeter should be computed or not. The defaut +value is false, because of the high computation time required. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetElongation " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetEquivalentEllipsoidDiameter " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetEquivalentSphericalPerimeter " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetEquivalentSphericalRadius " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetFeretDiameter " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetFlatness " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetKurtosis " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetLabels " + +This is a measurement. Its value is updated in the Execute methods, so +the value will only be valid after an execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetMaximum " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetMaximumIndex " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetMean " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetMedian " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetMinimum " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetMinimumIndex " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetName " + +Name of this class + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetNumberOfBins " + +Set/Get the number of bins in the histogram. Note that the histogram +is used to compute the median value, and that this option may have an +effect on the value of the median. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetNumberOfLabels " + +Return the number of labels after execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetNumberOfPixels " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetNumberOfPixelsOnBorder " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetPerimeter " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetPerimeterOnBorder " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetPerimeterOnBorderRatio " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetPhysicalSize " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetPrincipalAxes " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetPrincipalMoments " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetRoundness " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetSkewness " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetStandardDeviation " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetSum " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetVariance " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetWeightedElongation " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetWeightedFlatness " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetWeightedPrincipalAxes " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::GetWeightedPrincipalMoments " + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::HasLabel " + +Does the specified label exist? Can only be called after a call a call +to Update(). + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::LabelIntensityStatisticsImageFilter " + +Default Constructor that takes no arguments and initializes default +parameters + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::SetBackgroundValue " + +Set/Get the value used as \"background\" in the output image. Defaults +to NumericTraits::NonpositiveMin() . + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::SetComputeFeretDiameter " + +Set/Get whether the maximum Feret diameter should be computed or not. +The defaut value is false, because of the high computation time +required. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::SetComputePerimeter " + +Set/Get whether the perimeter should be computed or not. The defaut +value is false, because of the high computation time required. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::SetNumberOfBins " + +Set/Get the number of bins in the histogram. Note that the histogram +is used to compute the median value, and that this option may have an +effect on the value of the median. + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::ToString " + +Print ourselves out + +"; + +%feature("docstring") itk::simple::LabelIntensityStatisticsImageFilter::~LabelIntensityStatisticsImageFilter " + +Destructor + +"; + + %feature("docstring") itk::simple::LabelMapContourOverlayImageFilter " Apply a colormap to the contours (outlines) of each object in a label @@ -17487,7 +18091,7 @@ produce a gray pixel with the same intensity than the input one. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -17638,7 +18242,7 @@ Negated equals true. In Both cases, the label is set with SetLabel() . Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -17676,7 +18280,7 @@ Execute the filter on the input image with the given parameters %feature("docstring") itk::simple::LabelMapMaskImageFilter::GetBackgroundValue " Set/Get the value used as \"background\" in the output image. Defaults -to NumericTraits::Zero . +to NumericTraits::ZeroValue() . "; @@ -17732,7 +18336,7 @@ Set the value of Negated to true or false respectfully. %feature("docstring") itk::simple::LabelMapMaskImageFilter::SetBackgroundValue " Set/Get the value used as \"background\" in the output image. Defaults -to NumericTraits::Zero . +to NumericTraits::ZeroValue() . "; @@ -17798,7 +18402,7 @@ produce a gray pixel with the same intensity than the input one. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -17874,7 +18478,7 @@ foreground. The background values of the original binary image can be restored by passing this image to the filter with the SetBackgroundImage() method. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -17967,7 +18571,7 @@ LabelMapToBinaryImageFilter to a label image. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -18027,7 +18631,7 @@ Convert a LabelMap to a colored image. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -18081,7 +18685,7 @@ of two images. Background is assumed to be 0. This code was contributed in the Insight Journal paper: \"Introducing Dice, Jaccard, and Other Label Overlap Measures To ITK\" by Nicholas -J. Tustison, James C. Gee http://hdl.handle.net/10380/3141 http://www.insight-journal.org/browse/publication/707 +J. Tustison, James C. Gee https://hdl.handle.net/10380/3141 http://www.insight-journal.org/browse/publication/707 Nicholas J. Tustison @@ -18089,8 +18693,6 @@ Nicholas J. Tustison See: LabelOverlapMeasuresImageFilter - itk::simple::LabelOverlapMeasures for the procedural interface - itk::LabelOverlapMeasuresImageFilter for the Doxygen on the original ITK class. @@ -18198,7 +18800,7 @@ intensity than the input one. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This class was contributed to the Insight Journal http://hdl.handle.net/1926/172 + This class was contributed to the Insight Journal https://hdl.handle.net/1926/172 See: @@ -18293,7 +18895,7 @@ valuates the shape attribute at once. This implementation was taken from the Insight Journal paper: -http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -18618,11 +19220,7 @@ Execute the filter on the input image with the given parameters %feature("docstring") itk::simple::LabelStatisticsImageFilter::GetBoundingBox " -Return the computed bounding box for a label. Defined by the closed -interval of indexes, with a lower index followed by the upper for each -dimension. i.e. [0,255,0,255]. The bounding box always has a positive -size. - +Return the computed bounding box for a label. This is an active measurement. It may be accessed while the filter is being executing in command call-backs and can be accessed after @@ -18784,7 +19382,7 @@ background label is produced. This code was contributed in the Insight Journal paper: \"The watershed transform in ITK - discussion and new developments\" by -Beare R., Lehmann G. http://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 +Beare R., Lehmann G. https://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -18866,7 +19464,7 @@ keep is selected according to their label. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. - This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 + This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 See: @@ -18956,8 +19554,7 @@ INPUTS All input volumes to this filter must be segmentations of an image, that is, they must have discrete pixel values where each value represents a different segmented object. - Input volumes must all contain the same size RequestedRegions. Not -all input images must contain all possible labels, but all label + Input volumes must all contain the same size RequestedRegions. Not all input images must contain all possible labels, but all label values must have the same meaning in all images. OUTPUTS @@ -19072,6 +19669,142 @@ Destructor "; +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter " + +This class computes the transform that aligns the fixed and moving +images given a set of pair landmarks. The class is templated over the Transform type as well as fixed image and moving image types. The transform +computed gives the best fit transform that maps the fixed and moving +images in a least squares sense. The indices are taken to correspond, +so point 1 in the first set will get mapped close to point 1 in the +second set, etc. + +Currently, the following transforms are supported by the class: VersorRigid3DTransform Rigid2DTransform AffineTransform BSplineTransform + +An equal number of fixed and moving landmarks need to be specified +using SetFixedLandmarks() and SetMovingLandmarks() . Any number of landmarks may be specified. In the case of using +Affine or BSpline transforms, each landmark pair can contribute in the +final transform based on its defined weight. Number of weights should +be equal to the number of landmarks and can be specified using SetLandmarkWeight() . By defaults are weights are set to one. Call InitializeTransform() +to initialize the transform. + +The class is based in part on Hybrid/vtkLandmarkTransform originally +implemented in python by David G. Gobbi. + +The solution is based on Berthold K. P. Horn (1987), \"Closed-form +solution of absolute orientation using unit quaternions,\" http://people.csail.mit.edu/bkph/papers/Absolute_Orientation.pdf + +The Affine Transform initializer is based on an algorithm by H Spaeth, and is described in +the Insight Journal Article \"Affine Transformation for Landmark Based +Registration Initializer in ITK\" by Kim E.Y., Johnson H., Williams N. +available at http://midasjournal.com/browse/publication/825 + +Wiki Examples: + +All Examples + +Rigidly register one image to another using manually specified +landmarks +See: + itk::simple::LandmarkBasedTransformInitializerFilter for the procedural interface + + itk::LandmarkBasedTransformInitializer for the Doxygen on the original ITK class. + + + +C++ includes: sitkLandmarkBasedTransformInitializerFilter.h +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::Execute " + +Execute the filter on the input image + +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::Execute " + +Execute the filter on the input image with the given parameters + +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::GetBSplineNumberOfControlPoints " + +Set/Get the number of control points + +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::GetFixedLandmarks " +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::GetLandmarkWeight " +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::GetMovingLandmarks " + +Get the shrink factors. + +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::GetName " + +Name of this class + +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::GetReferenceImage " +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::LandmarkBasedTransformInitializerFilter " + +Default Constructor that takes no arguments and initializes default +parameters + +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::SetBSplineNumberOfControlPoints " + +Set/Get the number of control points + +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::SetFixedLandmarks " + +Set the Fixed landmark point containers + +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::SetLandmarkWeight " + +Set the landmark weight point containers Weight includes diagonal +elements of weight matrix + +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::SetMovingLandmarks " + +Set the Moving landmark point containers + +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::SetReferenceImage " + +Set the reference image to define the parametric domain for the +BSpline transform + +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::ToString " + +Print ourselves out + +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializerFilter::~LandmarkBasedTransformInitializerFilter " + +Destructor + +"; + + %feature("docstring") itk::simple::LandweberDeconvolutionImageFilter " Deconvolve an image using the Landweber deconvolution algorithm. @@ -19094,7 +19827,7 @@ see ProjectedLandweberDeconvolutionImageFilter . This code was adapted from the Insight Journal contribution: \"Deconvolution: infrastructure and reference algorithms\" by Gaetan -Lehmann http://hdl.handle.net/10380/3207 +Lehmann https://hdl.handle.net/10380/3207 Gaetan Lehmann, Biologie du Developpement et de la Reproduction, INRA @@ -19940,7 +20673,7 @@ Deformably register two images using level set motion. LevelSetMotionFilter implements a deformable registration algorithm that aligns a fixed and a moving image under level set motion. The -equations of motion are similar to those of the DemonsRegistrationFilter. The main differences are: (1) Gradients of the moving image are +equations of motion are similar to those of the DemonsRegistrationFilter . The main differences are: (1) Gradients of the moving image are calculated on a smoothed image while intensity difference are measured on the original images (2) Magnitude of the motion vector is a function of the differences in intensity between the fixed and moving @@ -19988,9 +20721,9 @@ for each iteration is computed in LevelSetMotionFunction. WARNING: This filter assumes that the fixed image type, moving image type and deformation field type all have the same number of dimensions. - Ref: B.C. Vemuri, J. Ye, Y. Chen, C.M. Leonard. \" Imageregistration + Ref: B.C. Vemuri, J. Ye, Y. Chen, C.M. Leonard. \" Image registration via level-set motion: applications to atlas-based segmentation\". -Medical ImageAnalysis. Vol. 7. pp. 1-20. 2003. +Medical Image Analysis. Vol. 7. pp. 1-20. 2003. See: @@ -20152,13 +20885,13 @@ Set/Get the standard deviation used for smoothing the moving image prior to calculating gradients. The standard deviation is measured in physical units (for instance mm). Note that this smoothing value is not to be confused with the -PDEDeformableRegistrationFilter::SetStandardDeviations()method. The -method in PDEDeformableRegistrationFilteris for setting the smoothing -parameters for regularizing the deformation field between interations. -Those smoothing parameters are set in pixel units not physical units. -Deformation field smoothing is not done by default in -LevelSetMotionRegistration. This smoothing parameter is to condition -the gradient calculation and parameter is specified in physical units. +PDEDeformableRegistrationFilter::SetStandardDeviations() method. The +method in PDEDeformableRegistrationFilter is for setting the smoothing parameters for regularizing the +deformation field between interations. Those smoothing parameters are +set in pixel units not physical units. Deformation field smoothing is +not done by default in LevelSetMotionRegistration. This smoothing +parameter is to condition the gradient calculation and parameter is +specified in physical units. "; @@ -20294,7 +21027,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -20920,7 +21653,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -21126,7 +21859,7 @@ Maximum projection. This class was contributed to the insight journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la reproduction, inra @@ -21298,7 +22031,7 @@ Mean projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -21476,7 +22209,7 @@ Median projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -21570,7 +22303,7 @@ objects with the same label are merged. PACK (2): MergeLabelMapFilter relabel al occur. STRICT (3): MergeLabelMapFilter keeps the labels unchanged and raises an exception if the same label is found in several images. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -21862,8 +22595,6 @@ pipeline. The implementation uses the StatisticsImageFilter . See: StatisticsImageFilter - itk::simple::MinimumMaximum for the procedural interface - itk::MinimumMaximumImageFilter for the Doxygen on the original ITK class. @@ -21926,7 +22657,7 @@ Minimum projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -22166,7 +22897,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -22427,7 +23158,7 @@ Principles and Applications\", Second Edition, Springer, 2003. This code was contributed in the Insight Journal paper: \"The watershed transform in ITK - discussion and new developments\" by -Beare R., Lehmann G. http://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 +Beare R., Lehmann G. https://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -22555,7 +23286,7 @@ Principles and Applications\", Second Edition, Springer, 2003. This code was contributed in the Insight Journal paper: \"The watershed transform in ITK - discussion and new developments\" by -Beare R., Lehmann G. http://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 +Beare R., Lehmann G. https://hdl.handle.net/1926/202 http://www.insight-journal.org/browse/publication/92 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -22668,6 +23399,230 @@ Destructor "; +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter " + +This filter performs a pixelwise combination of an arbitrary number of +input images, where each of them represents a segmentation of the same +scene (i.e., image). + + +The labelings in the images are weighted relative to each other based +on their \"performance\" as estimated by an expectation-maximization +algorithm. In the process, a ground truth segmentation is estimated, +and the estimated performances of the individual segmentations are +relative to this estimated ground truth. + +The algorithm is based on the binary STAPLE algorithm by Warfield et +al. as published originally in + +S. Warfield, K. Zou, W. Wells, \"Validation of image segmentation and +expert quality with an expectation-maximization algorithm\" in MICCAI +2002: Fifth International Conference on Medical Image Computing and Computer-Assisted Intervention, Springer-Verlag, +Heidelberg, Germany, 2002, pp. 298-306 + +The multi-label algorithm implemented here is described in detail in + +T. Rohlfing, D. B. Russakoff, and C. R. Maurer, Jr., \"Performance- +based classifier combination in atlas-based image segmentation using +expectation-maximization parameter estimation,\" IEEE Transactions on +Medical Imaging, vol. 23, pp. 983-994, Aug. 2004. + +INPUTS +All input volumes to this filter must be segmentations of an image, +that is, they must have discrete pixel values where each value +represents a different segmented object. + Input volumes must all contain the same size RequestedRegions. Not all input images must contain all possible labels, but all label +values must have the same meaning in all images. + +The filter can optionally be provided with estimates for the a priori +class probabilities through the SetPriorProbabilities function. If no +estimate is provided, one is automatically generated by analyzing the +relative frequencies of the labels in the input images. + +OUTPUTS +The filter produces a single output volume. Each output pixel contains +the label that has the highest probability of being the correct label, +based on the performance models of the individual segmentations. If +the maximum probaility is not unique, i.e., if more than one label +have a maximum probability, then an \"undecided\" label is assigned to +that output pixel. + By default, the label used for undecided pixels is the maximum label +value used in the input images plus one. Since it is possible for an +image with 8 bit pixel values to use all 256 possible label values, it +is permissible to combine 8 bit (i.e., byte) images into a 16 bit +(i.e., short) output image. + +In addition to the combined image, the estimated confusion matrices +for each of the input segmentations can be obtained through the +GetConfusionMatrix member function. + +PARAMETERS +The label used for \"undecided\" labels can be set using +SetLabelForUndecidedPixels. This functionality can be unset by calling +UnsetLabelForUndecidedPixels. + A termination threshold for the EM iteration can be defined by +calling SetTerminationUpdateThreshold. The iteration terminates once +no single parameter of any confusion matrix changes by less than this +threshold. Alternatively, a maximum number of iterations can be +specified by calling SetMaximumNumberOfIterations. The algorithm may +still terminate after a smaller number of iterations if the +termination threshold criterion is satisfied. + +EVENTS +This filter invokes IterationEvent() at each iteration of the E-M +algorithm. Setting the AbortGenerateData() flag will cause the +algorithm to halt after the current iteration and produce results just +as if it had converged. The algorithm makes no attempt to report its +progress since the number of iterations needed cannot be known in +advance. + +Torsten Rohlfing, SRI International, Neuroscience Program + +See: + itk::simple::MultiLabelSTAPLE for the procedural interface + + +C++ includes: sitkMultiLabelSTAPLEImageFilter.h +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::Execute " + +Execute the filter on the input images + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::Execute " +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::Execute " +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::Execute " +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::Execute " +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::Execute " +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::Execute " + +Execute the filter on the input images with the given parameters + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::Execute " +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::Execute " +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::Execute " +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::Execute " +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::Execute " +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::GetConfusionMatrix " + +Get confusion matrix for the i-th input segmentation. + +This is an active measurement. It may be accessed while the filter is +being executing in command call-backs and can be accessed after +execution. + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::GetLabelForUndecidedPixels " + + Get label value used for undecided pixels. + +After updating the filter, this function returns the actual label +value used for undecided pixels in the current output. Note that this +value is overwritten when SetLabelForUndecidedPixels is called and the +new value only becomes effective upon the next filter update. + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::GetMaximumNumberOfIterations " + +Set maximum number of iterations. + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::GetName " + +Name of this class + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::GetPriorProbabilities " + + Get prior class probabilities. + +After updating the filter, this function returns the actual prior +class probabilities. If these were not previously set by a call to +SetPriorProbabilities, then they are estimated from the input +segmentations and the result is available through this function. + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::GetTerminationUpdateThreshold " + +Set termination threshold based on confusion matrix parameter updates. + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::MultiLabelSTAPLEImageFilter " + +Default Constructor that takes no arguments and initializes default +parameters + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::SetLabelForUndecidedPixels " + +Set label value for undecided pixels. + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::SetMaximumNumberOfIterations " + +Set maximum number of iterations. + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::SetPriorProbabilities " + + Set manual estimates for the a priori class probabilities.The size +of the array must be greater than the value of the largest label. The index into the array corresponds to the label +value in the segmented image for the class. + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::SetTerminationUpdateThreshold " + +Set termination threshold based on confusion matrix parameter updates. + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::ToString " + +Print ourselves out + +"; + +%feature("docstring") itk::simple::MultiLabelSTAPLEImageFilter::~MultiLabelSTAPLEImageFilter " + +Destructor + +"; + + %feature("docstring") itk::simple::MultiplyImageFilter " Pixel-wise multiplication of two images. @@ -22766,8 +23721,10 @@ a downsampled version of the original image. A binary mask or a weighted image can be supplied. If a binary mask is specified, those voxels in the input image which correspond to the -voxels in the mask image with a value equal to m_MaskLabel, are used -to estimate the bias field. If a confidence image is specified, the +voxels in the mask image are used to estimate the bias field. If a +UseMaskLabel value is set to true, only voxels in the MaskImage that +match the MaskLabel will be used; otherwise, all non-zero voxels in +the MaskImage will be masked. If a confidence image is specified, the input voxels are weighted in the b-spline fitting routine according to the confidence voxel values. @@ -22785,7 +23742,7 @@ results with a B-spline scalar field estimate of the bias field. Nicholas J. Tustison Contributed by Nicholas J. Tustison, James C. Gee in the Insight -Journal paper: http://hdl.handle.net/10380/3053 +Journal paper: https://hdl.handle.net/10380/3053 REFERENCE J.G. Sled, A.P. Zijdenbos and A.C. Evans. \"A Nonparametric Method @@ -23450,7 +24407,7 @@ This transform is especially useful for normalizing a convolution kernel. This code was contributed in the Insight Journal paper: \"FFT based -convolution\" by Lehmann G. http://hdl.handle.net/10380/3154 +convolution\" by Lehmann G. https://hdl.handle.net/10380/3154 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -24164,7 +25121,7 @@ Richard Beare Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 Wiki Examples: @@ -25325,7 +26282,7 @@ images formed by counting photons, for example. This code was adapted from the Insight Journal contribution: \"Deconvolution: infrastructure and reference algorithms\" by Gaetan -Lehmann http://hdl.handle.net/10380/3207 +Lehmann https://hdl.handle.net/10380/3207 Gaetan Lehmann, Biologie du Developpement et de la Reproduction, INRA @@ -25467,7 +26424,7 @@ The structuring element is assumed to be composed of binary values > 0 are candidates for affecting the center pixel. This code was contributed in the Insight Journal paper: \"Efficient -implementation of kernel filtering\" by Beare R., Lehmann G http://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 +implementation of kernel filtering\" by Beare R., Lehmann G https://hdl.handle.net/1926/555 http://www.insight-journal.org/browse/publication/160 Richard Beare @@ -25903,8 +26860,8 @@ with the Gaussian kernel. This class implements the recursive filtering method proposed by R.Deriche in IEEE-PAMI Vol.12, No.1, January 1990, pp 78-87, \"Fast Algorithms for Low-Level Vision\" -Details of the implementation are described in the technical report: -R. Deriche, \"Recursively Implementing The Gaussian and Its +Details of the implementation are described in the technical report: R. +Deriche, \"Recursively Implementing The Gaussian and Its Derivatives\", INRIA, 1993, ftp://ftp.inria.fr/INRIA/tech-reports/RR/RR-1893.ps.gz Further improvements of the algorithm are described in: G. Farneback & @@ -26174,7 +27131,7 @@ a maxima or not. The desired behavior can be selected with the SetFlatIsMaxima() Gaetan Lehmann This class was contributed to the Insight Journal by author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de -Jouy-en-Josas, France. The paper can be found at http://hdl.handle.net/1926/153 +Jouy-en-Josas, France. The paper can be found at https://hdl.handle.net/1926/153 See: @@ -26329,7 +27286,7 @@ a minima or not. The SetFlatIsMinima() method let the user choose which behavior This class was contribtued to the Insight Journal by Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA -de Jouy-en-Josas, France. http://hdl.handle.net/1926/153 +de Jouy-en-Josas, France. https://hdl.handle.net/1926/153 RegionalMaximaImageFilter MathematicalMorphologyImageFilters @@ -26596,7 +27553,7 @@ attempts to reorganize the labels consecutively. The user can assign an arbitrary value to the background; the filter will assign the labels consecutively by skipping the background value. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/1926/584 or http://www.insight-journal.org/browse/publication/176 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. @@ -26679,7 +27636,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -27134,7 +28091,7 @@ independent of the other pixels. This code was adapted from the Insight Journal contribution: \"Deconvolution: infrastructure and reference algorithms\" by Gaetan -Lehmann http://hdl.handle.net/10380/3207 +Lehmann https://hdl.handle.net/10380/3207 Gaetan Lehmann, Biologie du Developpement et de la Reproduction, INRA @@ -27503,7 +28460,7 @@ pixel are equally distributed. Gaetan Lehmann This code was contributed in the Insight Journal paper \"Noise -Simulation\". http://hdl.handle.net/10380/3158 +Simulation\". https://hdl.handle.net/10380/3158 See: itk::simple::SaltAndPepperNoise for the procedural interface @@ -27576,14 +28533,14 @@ Vision, pages 141-151, 1999. Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. This code was taken from the Insight Journal paper:\"Cell Tracking -using Coupled Active Surfaces for Nuclei and Membranes\" http://www.insight-journal.org/browse/publication/642 http://hdl.handle.net/10380/3055 +using Coupled Active Surfaces for Nuclei and Membranes\" http://www.insight-journal.org/browse/publication/642 https://hdl.handle.net/10380/3055 That is based on the papers:\"Level Set Segmentation: Active Contours -without edge\" http://www.insight-journal.org/browse/publication/322 http://hdl.handle.net/1926/1532 +without edge\" http://www.insight-journal.org/browse/publication/322 https://hdl.handle.net/1926/1532 and -\"Level set segmentation using coupled active surfaces\" http://www.insight-journal.org/browse/publication/323 http://hdl.handle.net/1926/1533 +\"Level set segmentation using coupled active surfaces\" http://www.insight-journal.org/browse/publication/323 https://hdl.handle.net/1926/1533 Wiki Examples: @@ -27978,7 +28935,7 @@ mapped to the entire range of colors. This code was contributed in the Insight Journal paper: \"Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK\" by -Tustison N., Zhang H., Lehmann G., Yushkevich P., Gee J. http://hdl.handle.net/1926/1452 http://www.insight-journal.org/browse/publication/285 +Tustison N., Zhang H., Lehmann G., Yushkevich P., Gee J. https://hdl.handle.net/1926/1452 http://www.insight-journal.org/browse/publication/285 See: @@ -28275,7 +29232,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -28679,7 +29636,7 @@ The shot noise follows a Poisson distribution. Gaetan Lehmann This code was contributed in the Insight Journal paper \"Noise -Simulation\". http://hdl.handle.net/10380/3158 +Simulation\". https://hdl.handle.net/10380/3158 See: itk::simple::ShotNoise for the procedural interface @@ -29403,9 +30360,9 @@ unmodified. This filter is templated over the two input image type. It assume both image have the same number of dimensions. -See: - itk::simple::SimilarityIndex for the procedural interface + +See: itk::SimilarityIndexImageFilter for the Doxygen on the original ITK class. @@ -29912,7 +30869,7 @@ intensity. Gaetan Lehmann This code was contributed in the Insight Journal paper \"Noise -Simulation\". http://hdl.handle.net/10380/3158 +Simulation\". https://hdl.handle.net/10380/3158 See: itk::simple::SpeckleNoise for the procedural interface @@ -30093,8 +31050,7 @@ compute the difference of the two pixel values compute the square of the difference -cast the double value resulting from sqr() to the pixel type of the -output image +cast the double value resulting from sqr() to the pixel type of the output image store the casted value into the output image. The filter expect all images to have the same dimension (e.g. all 2D, @@ -30162,7 +31118,7 @@ Mean projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -30444,7 +31400,7 @@ Sum projection. This class was contributed to the Insight Journal by Gaetan Lehmann. -The original paper can be found at http://hdl.handle.net/1926/164 +The original paper can be found at https://hdl.handle.net/1926/164 Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA @@ -31101,7 +32057,8 @@ Set/Get methods to set the lower threshold %feature("docstring") itk::simple::ThresholdImageFilter::SetOutsideValue " -Set the \"outside\" pixel value. The default value NumericTraits::Zero . +The pixel type must support comparison operators. Set the \"outside\" +pixel value. The default value NumericTraits::ZeroValue() . "; @@ -31162,7 +32119,7 @@ counted. References: 1) Urish KL, August J, Huard J. \"Unsupervised segmentation for myofiber counting in immunoflourescent images\". Insight Journal. ISC -/NA-MIC/MICCAI Workshop on Open-Source Software (2005) Dspace handle: http://hdl.handle.net/1926/48 2) Pikaz A, Averbuch, A. \"Digital image thresholding based on +/NA-MIC/MICCAI Workshop on Open-Source Software (2005) Dspace handle: https://hdl.handle.net/1926/48 2) Pikaz A, Averbuch, A. \"Digital image thresholding based on topological stable-state\". Pattern Recognition, 29(5): 829-843, 1996. Questions: email Ken Urish at ken.urish(at)gmail.com Please cc the itk @@ -31204,11 +32161,12 @@ intensity. %feature("docstring") itk::simple::ThresholdMaximumConnectedComponentsImageFilter::GetMinimumObjectSizeInPixels " -Set the minimum pixel area used to count objects on the image. Thus, -only objects that have a pixel area greater than the minimum pixel -area will be counted as an object in the optimization portion of this -filter. Essentially, it eliminates noise from being counted as an -object. The default value is zero. +The pixel type must support comparison operators. Set the minimum +pixel area used to count objects on the image. Thus, only objects that +have a pixel area greater than the minimum pixel area will be counted +as an object in the optimization portion of this filter. Essentially, +it eliminates noise from being counted as an object. The default value +is zero. "; @@ -31259,11 +32217,12 @@ intensity. %feature("docstring") itk::simple::ThresholdMaximumConnectedComponentsImageFilter::SetMinimumObjectSizeInPixels " -Set the minimum pixel area used to count objects on the image. Thus, -only objects that have a pixel area greater than the minimum pixel -area will be counted as an object in the optimization portion of this -filter. Essentially, it eliminates noise from being counted as an -object. The default value is zero. +The pixel type must support comparison operators. Set the minimum +pixel area used to count objects on the image. Thus, only objects that +have a pixel area greater than the minimum pixel area will be counted +as an object in the optimization portion of this filter. Essentially, +it eliminates noise from being counted as an object. The default value +is zero. "; @@ -31873,7 +32832,7 @@ ThreadedGenerateData() method for its implementation. Marius Staring, Leiden University Medical Center, The Netherlands. - This class was taken from the Insight Journal paper: http://hdl.handle.net/1926/1387 + This class was taken from the Insight Journal paper: https://hdl.handle.net/1926/1387 See: itk::simple::TransformToDisplacementFieldFilter for the procedural interface @@ -32033,7 +32992,7 @@ Australia. Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -32223,7 +33182,7 @@ completely flat image will be marked as a regional maxima by this filter. This code was contributed in the Insight Journal paper: \"Finding -regional extrema - methods and performance\" by Beare R., Lehmann G. http://hdl.handle.net/1926/153 http://www.insight-journal.org/browse/publication/65 +regional extrema - methods and performance\" by Beare R., Lehmann G. https://hdl.handle.net/1926/153 http://www.insight-journal.org/browse/publication/65 Richard Beare. Department of Medicine, Monash University, Melbourne, @@ -32324,7 +33283,7 @@ completely flat image will be marked as a regional minima by this filter. This code was contributed in the Insight Journal paper: \"Finding -regional extrema - methods and performance\" by Beare R., Lehmann G. http://hdl.handle.net/1926/153 http://www.insight-journal.org/browse/publication/65 +regional extrema - methods and performance\" by Beare R., Lehmann G. https://hdl.handle.net/1926/153 http://www.insight-journal.org/browse/publication/65 Richard Beare. Department of Medicine, Monash University, Melbourne, @@ -33981,7 +34940,7 @@ Richard Beare Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. -This implementation was taken from the Insight Journal paper: http://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 +This implementation was taken from the Insight Journal paper: https://hdl.handle.net/10380/3279 or http://www.insight-journal.org/browse/publication/811 See: @@ -34271,8 +35230,8 @@ The input to this filter is an itk::Image of arbitrary dimension. The algorithm that operator>, operator<, operator==, and operator!= are defined. The output of the filter is a binary, labeled image of user-specified -type. By default, zero-crossing pixels are labeled with a default foreground'' value of itk::NumericTraits::One , where OutputDataType is the data type of the -output image. All other pixels are labeled with a defaultbackground'' value of itk::NumericTraits::Zero . +type. By default, zero-crossing pixels are labeled with a default foreground'' value of itk::NumericTraits::OneValue() , where OutputDataType is the data type +of the output image. All other pixels are labeled with a defaultbackground'' value of itk::NumericTraits::ZeroValue() . Parameters There are two parameters for this filter. ForegroundValue is the value that marks zero-crossing pixels. The BackgroundValue is the value @@ -35952,6 +36911,20 @@ See: itk::simple::FFTNormalizedCorrelationImageFilter for the object oriented interface +"; + +%feature("docstring") itk::simple::FFTPad " + +Pad an image to make it suitable for an FFT transformation. + + +This function directly calls the execute method of FFTPadImageFilter in order to support a procedural API + + +See: + itk::simple::FFTPadImageFilter for the object oriented interface + + "; %feature("docstring") itk::simple::FFTShift " @@ -36052,6 +37025,27 @@ A utility method to help convert between itk image types efficiently. %feature("docstring") itk::simple::GetPixelIDValueAsString " "; +%feature("docstring") itk::simple::GetPixelIDValueFromString " + +Function mapping enumeration names in std::string to values. + + +This function is intended for use by the R bindings. R stores the +enumeration values using the names : \"sitkUnkown\", \"sitkUInt8\", +etc from PixelIDValueEnum above. This function is used to provide the +integer values using calls like: + +val = GetPixelIDValueFromString(\"sitkInt32\") + +If the pixel type has not been instantiated then the sitkUnknown value +(-1) will be returned. If the pixel type string is not recognised +(i.e. is not in the set of tested names) then the return value is -99. +The idea is to provide a warning (via the R package) if this function +needs to be updated to match changes to PixelIDValueEnum - i.e. if a +new pixel type is added. + +"; + %feature("docstring") itk::simple::GetVectorImageFromImage " "; @@ -36353,21 +37347,6 @@ See: %feature("docstring") itk::simple::Hash " "; -%feature("docstring") itk::simple::HausdorffDistance " - -Computes the Hausdorff distance between the set of non-zero pixels of -two images. - - -This function directly calls the execute method of HausdorffDistanceImageFilter in order to support a procedural API - - -See: - itk::simple::HausdorffDistanceImageFilter for the object oriented interface - - -"; - %feature("docstring") itk::simple::HConcave " Identify local minima whose depth below the baseline is greater than @@ -36779,21 +37758,6 @@ See: itk::simple::LabelMapToRGBImageFilter for the object oriented interface -"; - -%feature("docstring") itk::simple::LabelOverlapMeasures " - -Computes overlap measures between the set same set of labels of pixels -of two images. Background is assumed to be 0. - - -This function directly calls the execute method of LabelOverlapMeasuresImageFilter in order to support a procedural API - - -See: - itk::simple::LabelOverlapMeasuresImageFilter for the object oriented interface - - "; %feature("docstring") itk::simple::LabelOverlay " @@ -36837,6 +37801,20 @@ See: itk::simple::LabelUniqueLabelMapFilter for the object oriented interface +"; + +%feature("docstring") itk::simple::LandmarkBasedTransformInitializer " + +itk::simple::LandmarkBasedTransformInitializerFilter Procedural Interface + + +This function directly calls the execute method of LandmarkBasedTransformInitializerFilter in order to support a procedural API + + +See: + itk::simple::LandmarkBasedTransformInitializerFilter for the object oriented interface + + "; %feature("docstring") itk::simple::LandweberDeconvolution " @@ -37190,20 +38168,6 @@ See: %feature("docstring") itk::simple::Minimum " "; -%feature("docstring") itk::simple::MinimumMaximum " - -Computes the minimum and the maximum intensity values of an image. - - -This function directly calls the execute method of MinimumMaximumImageFilter in order to support a procedural API - - -See: - itk::simple::MinimumMaximumImageFilter for the object oriented interface - - -"; - %feature("docstring") itk::simple::MinimumProjection " Minimum projection. @@ -37992,10 +38956,14 @@ The user can also select applications specifically for color images or environment variables. SITK_SHOW_COMMAND, SITK_SHOW_COLOR_COMMAND and SITK_SHOW_3D_COMMAND -allow the following tokens in their strings.\\\\li \\\\c \"%a\" for the ImageJ application \\\\li \\\\c \"%f\" -for SimpleITK's temporary image file +allow the following tokens in their strings. + -For example, the default SITK_SHOW_COMMAND string on Linux systems is: +\"%a\" for the ImageJ application + +\"%f\" for SimpleITK's temporary image file + For example, the default SITK_SHOW_COMMAND string on Linux systems +is: After token substitution it may become: @@ -38014,11 +38982,18 @@ Composite command to display the image in color. If the \"%f\" token is not found in the command string, the temporary file name is automatically appended to the command argument list. -By default, for a 64-bit build of SimpleITK on Macs, sitkShow searches -for ImageJ64.app. For a 32-bit Mac build, sitkShow searches for -ImageJ.app. If the user prefers a different version of ImageJ (or a -different image viewer altogether), it can be specified using the -SITK_SHOW_COMMAND environment variable. +When invoked, Show searches for Fiji first, and then ImageJ. Fiji is +the most update-to-date version of ImageJ and includes a lot of +plugins which facilitate scientific image analysis. By default, for a +64-bit build of SimpleITK on Macs, sitkShow searches for ImageJ64.app. +For a 32-bit Mac build, sitkShow searches for ImageJ.app. If the user +prefers a different version of ImageJ (or a different image viewer +altogether), it can be specified using the SITK_SHOW_COMMAND +environment variable. + +The boolean parameter debugOn prints the search path Show uses to find +ImageJ, the full path to the ImageJ it found, and the full command +line used to invoke ImageJ. "; @@ -38077,21 +39052,6 @@ See: itk::simple::SignedMaurerDistanceMapImageFilter for the object oriented interface -"; - -%feature("docstring") itk::simple::SimilarityIndex " - -Measures the similarity between the set of non-zero pixels of two -images. - - -This function directly calls the execute method of SimilarityIndexImageFilter in order to support a procedural API - - -See: - itk::simple::SimilarityIndexImageFilter for the object oriented interface - - "; %feature("docstring") itk::simple::SimpleContourExtractor " @@ -38156,6 +39116,9 @@ generated. "; +%feature("docstring") itk::simple::sitkSTLVectorToITKPointVector " +"; + %feature("docstring") itk::simple::Slice " itk::simple::SliceImageFilter Procedural Interface From 5e71d7cf9e2e2bdec109dd7f10ba3547c38bfa10 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 23 Jun 2016 10:46:34 -0400 Subject: [PATCH 296/412] Updating ITK version along 4.10 release branch This contains a patch for ITK for HaungThreshold and the NumericTraits linking issue. --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 53eb66216..b0c7f97b1 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -40,7 +40,7 @@ if("${git_protocol}" STREQUAL "git") endif() # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG v4.10.0 ) +set(ITK_TAG_COMMAND GIT_TAG b14b3488bd926c835a03ab12a5663bfc7eca3a92 ) # just after 4.10.0 release if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From ff2e9db85677bca75af2fd39bcd45ff40afc4e71 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 24 Jun 2016 10:53:14 -0400 Subject: [PATCH 297/412] Update testing functions with properties and generator expressions Prefer the use of CMake properties to set environment variables of command line options. Prefer the use of CMake Generator expressions to obtain the path to target libraries and executable. Change-Id: I4bdd44de12fad2b5cf29130198ee62759dde32f7 --- CMake/sitkAddTest.cmake | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index 192d49562..00e36c4fd 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -59,10 +59,12 @@ function(sitk_add_python_test name) sitk_add_test(NAME Python.${name} COMMAND "${ITK_TEST_DRIVER}" - --add-before-env SITK_NOSHOW "YES" ${command} ${ARGN} ) + set_property(TEST Python.${name} + PROPERTY ENVIRONMENT SITK_NOSHOW=YES + ) if (NOT SITK_PYTHON_USE_VIRTUALENV) set_property(TEST Python.${name} PROPERTY ENVIRONMENT PYTHONPATH=${SimpleITK_BINARY_DIR}/Wrapping @@ -116,11 +118,13 @@ function(sitk_add_ruby_test name) sitk_add_test(NAME Ruby.${name} COMMAND "${ITK_TEST_DRIVER}" - --add-before-env RUBYLIB "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/$" - --add-before-env RUBYLIB "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}" ${command} ${ARGN} ) + + set_property(TEST Ruby.${name} + PROPERTY ENVIRONMENT RUBYLIB=$ + ) endfunction() @@ -162,12 +166,11 @@ function(sitk_add_java_test name java_file) get_filename_component( _java_class ${java_file} NAME_WE ) set( _java_file_class "${_java_class}.class" ) + set( _JAVA_LIBRARY_PATH "$") if(WIN32) - set( _JAVA_LIBRARY_PATH "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/$" ) set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}$${CMAKE_CURRENT_BINARY_DIR}" ) else(WIN32) - set( _JAVA_LIBRARY_PATH "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}" ) set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}:${CMAKE_CURRENT_BINARY_DIR}" ) endif(WIN32) From cd52b9de1b5d8d513cd04a4ab50ddea7914c8593 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 24 Jun 2016 11:13:22 -0400 Subject: [PATCH 298/412] Moving Java test to global namespace removed the old org.simple.itk namespace in the generated tests. Change-Id: I04169cf4bd99c9d4a54b49a27bdeedba46ba28dd --- Testing/Unit/CMakeLists.txt | 6 +++--- Testing/Unit/JavaImageFilterTestTemplate.java.in | 1 - Testing/Unit/sitkImageFilterTestTemplate.cxx.in | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index ad4e733f4..c017fb058 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -44,7 +44,7 @@ file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/LuaTests) file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/TclTests) file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/RTests) file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/RubyTests) -file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/JavaTests/org/itk/simple/testing) +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/JavaTests) file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/CSharpTests) # Adjust Python to run in the virtualenv @@ -179,12 +179,12 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) # Java Tests if ( WRAP_JAVA ) - set(OUTPUT_TEST_FILENAME "${SimpleITK_BINARY_DIR}/Testing/Unit/JavaTests/org/itk/simple/testing/${FILTERNAME}Test.java") + set(OUTPUT_TEST_FILENAME "${SimpleITK_BINARY_DIR}/Testing/Unit/JavaTests/${FILTERNAME}Test.java") add_custom_command ( OUTPUT "${OUTPUT_TEST_FILENAME}" COMMAND ${CMAKE_COMMAND} -E remove -f "${OUTPUT_TEST_FILENAME}" COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Java ${template_include_dir} TestTemplate.java.in "${OUTPUT_TEST_FILENAME}" - COMMAND ${Java_JAVAC_EXECUTABLE} -classpath ${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE} ${SimpleITK_BINARY_DIR}/Testing/Unit/JavaTests/org/itk/simple/testing/${FILTERNAME}Test.java + COMMAND ${Java_JAVAC_EXECUTABLE} -classpath ${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE} ${SimpleITK_BINARY_DIR}/Testing/Unit/JavaTests/${FILTERNAME}Test.java DEPENDS ${filter_json_file} ${JAVA_TEMPLATE_FILES} ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} org_itk_simple_jar ) add_test( NAME Java.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=Java.${FILTERNAME} ) diff --git a/Testing/Unit/JavaImageFilterTestTemplate.java.in b/Testing/Unit/JavaImageFilterTestTemplate.java.in index ce576df53..7e23bc183 100644 --- a/Testing/Unit/JavaImageFilterTestTemplate.java.in +++ b/Testing/Unit/JavaImageFilterTestTemplate.java.in @@ -22,7 +22,6 @@ * Please look at JavaImageFilterTestTemplate.java.in to make changes. */ -package org.itk.simple.testing; import java.math.BigInteger; // This is Java code to test ${name} import org.itk.simple.*; diff --git a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in index 726db1329..7adff8167 100644 --- a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in +++ b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in @@ -686,7 +686,7 @@ TEST_F(Java,${name}) { std::string Classpath = dataFinder.GetBuildDirectory() + "/Testing/Unit/JavaTests" + dataFinder.GetPathSeparator() + dataFinder.GetBuildDirectory() + "/Wrapping/Java/simpleitk-" + itk::simple::Version::VersionString() + ".jar"; std::string JavaPath = dataFinder.GetLibraryDirectory(); - std::string Script = "org.itk.simple.testing.${name}Test"; + std::string Script = "${name}Test"; $(foreach tests { /* ${description} */ From 7dacab8d33ca41717d19fafca0af99ad9886f27c Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 24 Jun 2016 14:50:52 -0400 Subject: [PATCH 299/412] Fix bug of missing JAR_FILE variable Change-Id: I1822a98f4add76e618f7a8077e60e03701341f8f --- CMake/sitkAddTest.cmake | 1 + 1 file changed, 1 insertion(+) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index 00e36c4fd..d95165e24 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -165,6 +165,7 @@ function(sitk_add_java_test name java_file) # the root is with out extension or path, it is also assumed to the the name of the main class get_filename_component( _java_class ${java_file} NAME_WE ) set( _java_file_class "${_java_class}.class" ) + set(JAR_FILE "simpleitk-${SimpleITK_VERSION}.jar") # from target? set( _JAVA_LIBRARY_PATH "$") if(WIN32) From 1ee2a0c8a737828086f34b13c15c776031965648 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 24 Jun 2016 16:04:33 -0400 Subject: [PATCH 300/412] Remove C++ based driver for languages tests Removing the languages tests which were being called by generated C++ code from the sitkImageFilterTestTemplate --- CMake/sitkAddTest.cmake | 43 +- Testing/Unit/CMakeLists.txt | 41 +- .../Unit/sitkImageFilterTestTemplate.cxx.in | 482 ------------------ 3 files changed, 38 insertions(+), 528 deletions(-) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index d95165e24..0f65a1ddd 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -165,28 +165,35 @@ function(sitk_add_java_test name java_file) # the root is with out extension or path, it is also assumed to the the name of the main class get_filename_component( _java_class ${java_file} NAME_WE ) set( _java_file_class "${_java_class}.class" ) + set( _class_path "${CMAKE_CURRENT_BINARY_DIR}" ) set(JAR_FILE "simpleitk-${SimpleITK_VERSION}.jar") # from target? set( _JAVA_LIBRARY_PATH "$") if(WIN32) - set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}$${CMAKE_CURRENT_BINARY_DIR}" ) - - else(WIN32) - set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}:${CMAKE_CURRENT_BINARY_DIR}" ) - endif(WIN32) - - add_custom_command( - OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${_java_file_class}" - COMMAND "${Java_JAVAC_EXECUTABLE}" - ARGS -classpath "${_JAVA_CLASSPATH}" - -d "${CMAKE_CURRENT_BINARY_DIR}" - "${java_file}" - DEPENDS ${java_file} ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} org_itk_simple_jar - COMMENT "Building ${CMAKE_CURRENT_BINARY_DIR}/${_java_file_class}" - ) - add_custom_target( ${_java_class}Java ALL - DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/${_java_file_class}" - SOURCES ${java_file}) + set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}$${_class_path}" ) + else() + set( _JAVA_CLASSPATH "${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE}:${_class_path}" ) + endif() + + if (NOT TARGET ${_java_class}Java) + + add_custom_command( + OUTPUT "${_class_path}/${_java_file_class}" + COMMAND "${CMAKE_COMMAND}" + ARGS -E remove -f "${_class_path}/${_java_file_class}" + COMMAND "${Java_JAVAC_EXECUTABLE}" + ARGS -classpath "${_JAVA_CLASSPATH}" + -d "${_class_path}" + "${java_file}" + DEPENDS ${java_file} ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} org_itk_simple_jar + COMMENT "Building ${_class_path}/${_java_file_class}" + ) + add_custom_target( ${_java_class}Java ALL + DEPENDS "${_class_path}/${_java_file_class}" + SOURCES ${java_file} + ) + endif() + sitk_add_test(NAME Java.${name} COMMAND "${ITK_TEST_DRIVER}" diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index c017fb058..c57b240e8 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -47,11 +47,15 @@ file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/RubyTests) file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/JavaTests) file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/CSharpTests) +# Test data directory +set(TEST_HARNESS_TEMP_DIRECTORY ${SimpleITK_BINARY_DIR}/Testing/Temporary) +set(TEST_HARNESS_DATA_DIRECTORY ${SimpleITK_BINARY_DIR}/ExternalData/Testing/Data) + +set( ITK_TEST_DRIVER "itkTestDriver" ) + # Adjust Python to run in the virtualenv set( PythonVirtualenvHome ${SimpleITK_BINARY_DIR}/Testing/Installation/PythonVirtualenv ) -set(JAR_FILE "simpleitk-${SimpleITK_VERSION}.jar") - add_executable(SimpleITKUnitTestDriver0 SimpleITKUnitTestDriver.cxx ${SimpleITKUnitTestSource}) target_link_libraries ( SimpleITKUnitTestDriver0 ${GTEST_LIBRARIES} SimpleITKUnitTestBase ${SimpleITK_LIBRARIES} ) @@ -75,6 +79,7 @@ file ( GLOB CSHARP_TEMPLATE_FILES "*Template*.cs.in" ) # # Break all these source files into a bunch of separate executables # base on every n files in the list. +message( STATUS "Generating tests...") set ( _stride 50 ) set ( _exec_i 1 ) # exec 0 is the manual tests set ( _i 0 ) @@ -125,7 +130,6 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Lua ${template_include_dir} TestTemplate.lua.in "${OUTPUT_TEST_FILENAME}" DEPENDS ${filter_json_file} ${LUA_TEMPLATE_FILES} ) - add_test( NAME Lua.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=Lua.${FILTERNAME} ) set ( WRAPPED_GENERATED_TEST_SOURCE ${WRAPPED_GENERATED_TEST_SOURCE} ${OUTPUT_TEST_FILENAME}) endif() @@ -137,7 +141,6 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Python ${template_include_dir} TestTemplate.py.in "${OUTPUT_TEST_FILENAME}" DEPENDS ${filter_json_file} ${PYTHON_TEMPLATE_FILES} ) - add_test( NAME Python.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=Python.${FILTERNAME} ) set ( WRAPPED_GENERATED_TEST_SOURCE ${WRAPPED_GENERATED_TEST_SOURCE} ${OUTPUT_TEST_FILENAME}) endif() @@ -149,7 +152,6 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Tcl ${template_include_dir} TestTemplate.tcl.in "${OUTPUT_TEST_FILENAME}" DEPENDS ${filter_json_file} ${TCL_TEMPLATE_FILES} ) - add_test( NAME Tcl.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=Tcl.${FILTERNAME} ) set ( WRAPPED_GENERATED_TEST_SOURCE ${WRAPPED_GENERATED_TEST_SOURCE} ${OUTPUT_TEST_FILENAME}) endif() @@ -161,7 +163,6 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/R ${template_include_dir} TestTemplate.R.in "${OUTPUT_TEST_FILENAME}" DEPENDS ${filter_json_file} ${R_TEMPLATE_FILES} ) - add_test( NAME R.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=R.${FILTERNAME} ) set ( WRAPPED_GENERATED_TEST_SOURCE ${WRAPPED_GENERATED_TEST_SOURCE} ${OUTPUT_TEST_FILENAME}) endif() @@ -173,7 +174,6 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Ruby ${template_include_dir} TestTemplate.rb.in "${OUTPUT_TEST_FILENAME}" DEPENDS ${filter_json_file} ${RUBY_TEMPLATE_FILES} ) - add_test( NAME Ruby.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=Ruby.${FILTERNAME} ) set ( WRAPPED_GENERATED_TEST_SOURCE ${WRAPPED_GENERATED_TEST_SOURCE} ${OUTPUT_TEST_FILENAME}) endif() @@ -184,32 +184,19 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) OUTPUT "${OUTPUT_TEST_FILENAME}" COMMAND ${CMAKE_COMMAND} -E remove -f "${OUTPUT_TEST_FILENAME}" COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/Java ${template_include_dir} TestTemplate.java.in "${OUTPUT_TEST_FILENAME}" - COMMAND ${Java_JAVAC_EXECUTABLE} -classpath ${SimpleITK_BINARY_DIR}/Wrapping/Java/${JAR_FILE} ${SimpleITK_BINARY_DIR}/Testing/Unit/JavaTests/${FILTERNAME}Test.java - DEPENDS ${filter_json_file} ${JAVA_TEMPLATE_FILES} ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} org_itk_simple_jar - ) - add_test( NAME Java.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=Java.${FILTERNAME} ) + DEPENDS ${filter_json_file} ${JAVA_TEMPLATE_FILES} ${SWIG_MODULE_SimpleITKJava_TARGET_NAME} ) set ( WRAPPED_GENERATED_TEST_SOURCE ${WRAPPED_GENERATED_TEST_SOURCE} ${OUTPUT_TEST_FILENAME}) endif() # C# Tests if ( WRAP_CSHARP ) - set( OUTPUT_TEST_FILENAME "${SimpleITK_BINARY_DIR}/Testing/Unit/CSharpTests/Test${FILTERNAME}.cs" ) - if ( WIN32 ) - string( REPLACE "/" "\\" OUTPUT_TEST_FILENAME_SAFE ${OUTPUT_TEST_FILENAME} ) - else ( UNIX ) - string( REPLACE "\\" "/" OUTPUT_TEST_FILENAME_SAFE ${OUTPUT_TEST_FILENAME} ) - endif ( WIN32 ) + set( OUTPUT_TEST_FILENAME "${SimpleITK_BINARY_DIR}/Testing/Unit/CSharpTests/${FILTERNAME}Test.cs" ) add_custom_command ( OUTPUT "${OUTPUT_TEST_FILENAME}" COMMAND ${CMAKE_COMMAND} -E remove -f "${OUTPUT_TEST_FILENAME}" COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/CSharp ${template_include_dir} TestTemplate.cs.in "${OUTPUT_TEST_FILENAME}" - COMMAND ${CSHARP_COMPILER} - /t:exe /platform:${CSHARP_PLATFORM} - /lib:${CSHARP_BINARY_DIRECTORY} /reference:System.dll /reference:SimpleITKCSharpManaged.dll - /out:${CSHARP_BINARY_DIRECTORY}/Test${FILTERNAME}.exe ${OUTPUT_TEST_FILENAME_SAFE} - DEPENDS ${filter_json_file} ${CSHARP_TEMPLATE_FILES} SimpleITKCSharpManaged + DEPENDS ${filter_json_file} ${CSHARP_TEMPLATE_FILES} ) - add_test( NAME CSharp.${FILTERNAME} COMMAND SimpleITKUnitTestDriver${_exec_i} --gtest_filter=CSharp.${FILTERNAME} ) set ( WRAPPED_GENERATED_TEST_SOURCE ${WRAPPED_GENERATED_TEST_SOURCE} ${OUTPUT_TEST_FILENAME}) endif() endif() # if template_name @@ -217,13 +204,11 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) endforeach() +message( STATUS "Generating tests...Done") + add_executable(SimpleITKUnitTestDriver${_exec_i} SimpleITKUnitTestDriver.cxx ${GENERATED_TEST_SOURCE}) target_link_libraries ( SimpleITKUnitTestDriver${_exec_i} ${GTEST_LIBRARIES} SimpleITKUnitTestBase ${SimpleITK_LIBRARIES} ) -# Test data directory -set(TEST_HARNESS_TEMP_DIRECTORY ${SimpleITK_BINARY_DIR}/Testing/Temporary) -set(TEST_HARNESS_DATA_DIRECTORY ${SimpleITK_BINARY_DIR}/ExternalData/Testing/Data) - # Set some variables configure_file(${CMAKE_CURRENT_SOURCE_DIR}/SimpleITKTestHarnessPaths.h.in ${CMAKE_CURRENT_BINARY_DIR}/SimpleITKTestHarnessPaths.h ESCAPE_QUOTES) @@ -266,6 +251,6 @@ gtest_add_tests(SimpleITKUnitTestDriver0 ${SimpleITKUnitTestSource}) # ####################################################### -set( ITK_TEST_DRIVER "itkTestDriver" ) include(${CMAKE_CURRENT_SOURCE_DIR}/AdditionalTests.cmake) + diff --git a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in index 7adff8167..b9dc21f66 100644 --- a/Testing/Unit/sitkImageFilterTestTemplate.cxx.in +++ b/Testing/Unit/sitkImageFilterTestTemplate.cxx.in @@ -402,485 +402,3 @@ end)) } // END FOR EACH TEST ) - - -#if defined(WRAP_LUA) - -TEST_F(Lua,${name}) { - $(if #tests == 0 then - OUT=[[ - FAIL() << "Filter ${name} has no tests defined"; - ]] - end) - - std::string Script = dataFinder.GetBuildDirectory() + "/Testing/Unit/LuaTests/${name}Test.lua"; - $(foreach tests - { - /* ${description} */ - std::vector CommandLine; - std::string outputFileName = dataFinder.GetOutputFile ( "Lua-${name}-${tag}.nrrd" ); - // Make sure the output is deleted - if ( itksys::SystemTools::FileExists ( outputFileName.c_str() ) ) { - ASSERT_TRUE ( itksys::SystemTools::RemoveFile ( outputFileName.c_str() ) ) << "Deleting file " << outputFileName; - } - CommandLine = dataFinder.GetLuaExecutable(); - CommandLine.push_back ( Script ); - CommandLine.push_back ( "${tag}" ); -$(for inum=1,#inputs do - OUT=OUT..[[ - CommandLine.push_back( dataFinder.GetFile ("]]..inputs[inum]..[[") ); -]] end) - CommandLine.push_back ( outputFileName ); - EXPECT_EQ( 0, RunExecutable ( CommandLine, true ) ) << "non-zero returned from process"; - - $(if not no_return_image then - OUT=[[ - ASSERT_TRUE ( dataFinder.FileExists ( outputFileName ) ); - itk::simple::ImageFileReader reader; - itk::simple::HashImageFilter hasher; - itk::simple::Image output( 0, 0, itk::simple::sitkUInt8 ); - - output = reader.SetFileName ( outputFileName ).Execute(); - ASSERT_TRUE ( output.GetITKBase() != NULL ) << "Loaded output image"; - ]] - end) - - $(if md5hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${md5hash}",MD5,output,"Output MD5 hash failed"); - ]] - end) - $(if sha1hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${sha1hash}",SHA1,output,"Output SHA1 hash failed"); - ]] - end) - $(if tolerance then - OUT = [[ - IMAGECOMPAREWITHTOLERANCE_WITH_TESTCASE ( output, "BasicFilters", "${tag}", ${tolerance} ); - ]] - end) - } - ) -} -#endif - -#if defined(WRAP_PYTHON) - -TEST_F(Python,${name}) { - $(if #tests == 0 then - OUT=[[ - FAIL() << "Filter ${name} has no tests defined"; - ]] - end) - - #ifndef SITK_PYTHON_USE_VIRTUALENV - // Set-up the R enviroment to include the SimpleITK R library in the - // build directory. - SetEnvironment ( "PYTHONPATH", dataFinder.GetBuildDirectory()+"/Wrapping" ); - #endif - - - std::string Script = dataFinder.GetBuildDirectory() + "/Testing/Unit/PythonTests/${name}Test.py"; - $(foreach tests - { - /* ${description} */ - std::vector CommandLine; - std::string outputFileName = dataFinder.GetOutputFile ( "Python-${name}-${tag}.nrrd" ); - // Make sure the output is deleted - if ( itksys::SystemTools::FileExists ( outputFileName.c_str() ) ) { - ASSERT_TRUE ( itksys::SystemTools::RemoveFile ( outputFileName.c_str() ) ) << "Deleting file " << outputFileName; - } - CommandLine = dataFinder.GetPythonExecutable(); - CommandLine.push_back ( Script ); - CommandLine.push_back ( "${tag}" ); -$(for inum=1,#inputs do - OUT=OUT..[[ - CommandLine.push_back( dataFinder.GetFile ("]]..inputs[inum]..[[") ); -]] end) - CommandLine.push_back ( outputFileName ); - EXPECT_EQ( 0, RunExecutable ( CommandLine, true ) ) << "non-zero returned from process"; - - $(if not no_return_image then - OUT=[[ - ASSERT_TRUE ( dataFinder.FileExists ( outputFileName ) ); - itk::simple::ImageFileReader reader; - itk::simple::HashImageFilter hasher; - itk::simple::Image output( 0, 0, itk::simple::sitkUInt8 ); - - output = reader.SetFileName ( outputFileName ).Execute(); - ASSERT_TRUE ( output.GetITKBase() != NULL ) << "Loaded output image"; -]] - end) - - $(if md5hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${md5hash}",MD5,output,"Output MD5 hash failed"); - ]] - end) - $(if sha1hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${sha1hash}",SHA1,output,"Output SHA1 hash failed"); - ]] - end) - $(if tolerance then - OUT = [[ - IMAGECOMPAREWITHTOLERANCE_WITH_TESTCASE ( output, "BasicFilters", "${tag}", ${tolerance} ); - ]] - end) - } - ) -} -#endif - -#if defined(WRAP_TCL) - -TEST_F(Tcl,${name}) { - $(if #tests == 0 then - OUT=[[ - FAIL() << "Filter ${name} has no tests defined"; - ]] - end) - - std::string Script = dataFinder.GetBuildDirectory() + "/Testing/Unit/TclTests/${name}Test.tcl"; - $(foreach tests - { - /* ${description} */ - std::vector CommandLine; - std::string outputFileName = dataFinder.GetOutputFile ( "Tcl-${name}-${tag}.nrrd" ); - // Make sure the output is deleted - if ( itksys::SystemTools::FileExists ( outputFileName.c_str() ) ) { - ASSERT_TRUE ( itksys::SystemTools::RemoveFile ( outputFileName.c_str() ) ) << "Deleting file " << outputFileName; - } - CommandLine = dataFinder.GetTclExecutable ( ); - CommandLine.push_back ( Script ); - CommandLine.push_back ( "${tag}" ); -$(for inum=1,#inputs do - OUT=OUT..[[ - CommandLine.push_back( dataFinder.GetFile ("]]..inputs[inum]..[[") ); -]] end) - CommandLine.push_back ( outputFileName ); - EXPECT_EQ( 0, RunExecutable ( CommandLine, true ) ) << "non-zero returned from process"; - - $(if not no_return_image then - OUT=[[ - ASSERT_TRUE ( dataFinder.FileExists ( outputFileName ) ); - itk::simple::ImageFileReader reader; - itk::simple::HashImageFilter hasher; - itk::simple::Image output( 0, 0, itk::simple::sitkUInt8 ); - - output = reader.SetFileName ( outputFileName ).Execute(); - ASSERT_TRUE ( output.GetITKBase() != NULL ) << "Loaded output image"; - ]] - end) - - $(if md5hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${md5hash}",MD5,output,"Output MD5 hash failed"); - ]] - end) - $(if sha1hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${sha1hash}",SHA1,output,"Output SHA1 hash failed"); - ]] - end) - $(if tolerance then - OUT = [[ - IMAGECOMPAREWITHTOLERANCE_WITH_TESTCASE ( output, "BasicFilters", "${tag}", ${tolerance} ); - ]] - end) - } - ) -} -#endif - -#if defined(WRAP_R) - -TEST_F(R,${name}) { - $(if #tests == 0 then - OUT=[[ - FAIL() << "Filter ${name} has no tests defined"; - ]] - end) - - // Set-up the R enviroment to include the SimpleITK R library in the - // build directory. - SetEnvironment ( "R_LIBS", dataFinder.GetBuildDirectory()+"/Wrapping/R/R_libs" ); - - - std::string Script = dataFinder.GetBuildDirectory() + "/Testing/Unit/RTests/${name}Test.R"; - $(foreach tests - { - - /* ${description} */ - std::vector CommandLine; - std::string outputFileName = dataFinder.GetOutputFile ( "R-${name}-${tag}.nrrd" ); - // Make sure the output is deleted - if ( itksys::SystemTools::FileExists ( outputFileName.c_str() ) ) { - ASSERT_TRUE ( itksys::SystemTools::RemoveFile ( outputFileName.c_str() ) ) << "Deleting file " << outputFileName; - } - CommandLine = dataFinder.GetRExecutable(); - CommandLine.push_back ( "--slave" ); - CommandLine.push_back ( "--vanilla" ); - CommandLine.push_back ( std::string("--file=")+Script ); - CommandLine.push_back ( "--args" ); - CommandLine.push_back ( "${tag}" ); -$(for inum=1,#inputs do - OUT=OUT..[[ - CommandLine.push_back( dataFinder.GetFile ("]]..inputs[inum]..[[") ); -]] end) - CommandLine.push_back ( outputFileName ); - EXPECT_EQ( 0, RunExecutable ( CommandLine, true ) ) << "non-zero returned from process"; - - $(if not no_return_image then - OUT=[[ - ASSERT_TRUE ( dataFinder.FileExists ( outputFileName ) ); - itk::simple::ImageFileReader reader; - itk::simple::HashImageFilter hasher; - itk::simple::Image output( 0, 0, itk::simple::sitkUInt8 ); - output = reader.SetFileName ( outputFileName ).Execute(); - ASSERT_TRUE ( output.GetITKBase() != NULL ) << "Loaded output image"; -]] - end) - - $(if md5hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${md5hash}",MD5,output,"Output MD5 hash failed"); - ]] - end) - $(if sha1hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${sha1hash}",SHA1,output,"Output SHA1 hash failed"); - ]] - end) - $(if tolerance then - OUT = [[ - IMAGECOMPAREWITHTOLERANCE_WITH_TESTCASE ( output, "BasicFilters", "${tag}", ${tolerance} ); - ]] - end) - } - - ) -} -#endif - - - -#if defined(WRAP_JAVA) - -TEST_F(Java,${name}) { - $(if #tests == 0 then - OUT=[[ - FAIL() << "Filter ${name} has no tests defined"; - ]] - end) - - std::string Classpath = dataFinder.GetBuildDirectory() + "/Testing/Unit/JavaTests" - + dataFinder.GetPathSeparator() + dataFinder.GetBuildDirectory() + "/Wrapping/Java/simpleitk-" + itk::simple::Version::VersionString() + ".jar"; - std::string JavaPath = dataFinder.GetLibraryDirectory(); - std::string Script = "${name}Test"; - $(foreach tests - { - /* ${description} */ - std::vector CommandLine; - std::string outputFileName = dataFinder.GetOutputFile ( "Java-${name}-${tag}.nrrd" ); - // Make sure the output is deleted - if ( itksys::SystemTools::FileExists ( outputFileName.c_str() ) ) { - ASSERT_TRUE ( itksys::SystemTools::RemoveFile ( outputFileName.c_str() ) ) << "Deleting file " << outputFileName; - } - CommandLine = dataFinder.GetJavaExecutable(); - CommandLine.push_back ( "-classpath" ); - CommandLine.push_back ( Classpath ); - CommandLine.push_back ( "-Djava.library.path=" + JavaPath ); - CommandLine.push_back ( Script ); - CommandLine.push_back ( "${tag}" ); -$(for inum=1,#inputs do - OUT=OUT..[[ - CommandLine.push_back( dataFinder.GetFile ("]]..inputs[inum]..[[") ); -]] end) - CommandLine.push_back ( outputFileName ); - EXPECT_EQ( 0, RunExecutable ( CommandLine, true ) ) << "non-zero returned from process"; - - $(if not no_return_image then - OUT=[[ - ASSERT_TRUE ( dataFinder.FileExists ( outputFileName ) ); - itk::simple::ImageFileReader reader; - itk::simple::HashImageFilter hasher; - itk::simple::Image output( 0, 0, itk::simple::sitkUInt8 ); - output = reader.SetFileName ( outputFileName ).Execute(); - ASSERT_TRUE ( output.GetITKBase() != NULL ) << "Loaded output image"; -]] - end) - - $(if md5hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${md5hash}",MD5,output,"Output MD5 hash failed"); - ]] - end) - $(if sha1hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${sha1hash}",SHA1,output,"Output SHA1 hash failed"); - ]] - end) - $(if tolerance then - OUT = [[ - IMAGECOMPAREWITHTOLERANCE_WITH_TESTCASE ( output, "BasicFilters", "${tag}", ${tolerance} ); - ]] - end) - } - ) -} -#endif - -#if defined(WRAP_RUBY) - -TEST_F(Ruby,${name}) { - $(if #tests == 0 then - OUT=[[ - FAIL() << "Filter ${name} has no tests defined"; - ]] - end) - - // Set our Ruby path - SetEnvironment ( "RUBYLIB", dataFinder.GetLibraryDirectory() ); - - std::string Script = dataFinder.GetBuildDirectory() + "/Testing/Unit/RubyTests/${name}Test.rb"; - $(foreach tests - { - /* ${description} */ - std::vector CommandLine; - std::string outputFileName = dataFinder.GetOutputFile ( "Ruby-${name}-${tag}.nrrd" ); - // Make sure the output is deleted - if ( itksys::SystemTools::FileExists ( outputFileName.c_str() ) ) { - ASSERT_TRUE ( itksys::SystemTools::RemoveFile ( outputFileName.c_str() ) ) << "Deleting file " << outputFileName; - } - CommandLine = dataFinder.GetRubyExecutable(); - CommandLine.push_back ( Script ); - CommandLine.push_back ( "${tag}" ); -$(for inum=1,#inputs do - OUT=OUT..[[ - CommandLine.push_back( dataFinder.GetFile ("]]..inputs[inum]..[[") ); -]] end) - CommandLine.push_back ( outputFileName ); - EXPECT_EQ( 0, RunExecutable ( CommandLine, true ) ) << "non-zero returned from process"; - - $(if not no_return_image then - OUT=[[ - ASSERT_TRUE ( dataFinder.FileExists ( outputFileName ) ); - itk::simple::ImageFileReader reader; - itk::simple::HashImageFilter hasher; - itk::simple::Image output( 0, 0, itk::simple::sitkUInt8 ); - output = reader.SetFileName ( outputFileName ).Execute(); - ASSERT_TRUE ( output.GetITKBase() != NULL ) << "Loaded output image"; -]] - end) - - $(if md5hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${md5hash}",MD5,output,"Output MD5 hash failed"); - ]] - end) - $(if sha1hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${sha1hash}",SHA1,output,"Output SHA1 hash failed"); - ]] - end) - $(if tolerance then - OUT = [[ - IMAGECOMPAREWITHTOLERANCE_WITH_TESTCASE ( output, "BasicFilters", "${tag}", ${tolerance} ); - ]] - end) - } - ) -} -#endif - -#if defined(WRAP_CSHARP) - -TEST_F(CSharp,${name}) { - $(if #tests == 0 then - OUT=[[ - FAIL() << "Filter ${name} has no tests defined"; - ]] - end) - - std::string ExePath = dataFinder.GetCSharpBinaryDirectory(); - std::string ExeName = "Test${name}.exe"; - std::string ExePathAndName = ExePath + "/" + ExeName; - - // On Linux, we need to specify where the shared library is found - std::string path = dataFinder.GetBuildDirectory() + "/Wrapping/CSharpBinaries"; - SetEnvironment ( "LD_LIBRARY_PATH", path ); - - - $(foreach tests - { - /* ${description} */ - std::vector CommandLine; - std::string outputFileName = dataFinder.GetOutputFile ( "CSharp-${name}-${tag}.nrrd" ); - - // Make sure the output is deleted - if ( itksys::SystemTools::FileExists ( outputFileName.c_str() ) ) { - ASSERT_TRUE ( itksys::SystemTools::RemoveFile ( outputFileName.c_str() ) ) << "Deleting file " << outputFileName; - } - - std::vector cs_interp = dataFinder.GetCSharpInterpreter(); - - if ( cs_interp.size() && cs_interp[0].size() ) - { - CommandLine = dataFinder.GetCSharpInterpreter(); - } - CommandLine.push_back ( ExePathAndName ); - CommandLine.push_back ( dataFinder.GetFile ( "Input/RA-Short.nrrd" ).c_str() ); - CommandLine.push_back ( "${tag}" ); -$(for inum=1,#inputs do - OUT=OUT..[[ - CommandLine.push_back( dataFinder.GetFile ("]]..inputs[inum]..[[") ); -]] end) - CommandLine.push_back ( outputFileName ); - EXPECT_EQ( 0, RunExecutable ( CommandLine, true ) ) << "non-zero returned from process"; - - $(if not no_return_image then - OUT=[[ - ASSERT_TRUE ( dataFinder.FileExists ( outputFileName ) ); - itk::simple::ImageFileReader reader; - itk::simple::HashImageFilter hasher; - itk::simple::Image output( 0, 0, itk::simple::sitkUInt8 ); - output = reader.SetFileName ( outputFileName ).Execute(); - ASSERT_TRUE ( output.GetITKBase() != NULL ) << "Loaded output image"; -]] - end) - - $(if md5hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${md5hash}",MD5,output,"Output MD5 hash failed"); - ]] - end) - $(if sha1hash then - OUT = [[ - // Check the hash - IMAGECOMPAREWITHHASH("${sha1hash}",SHA1,output,"Output SHA1 hash failed"); - ]] - end) - $(if tolerance then - OUT = [[ - IMAGECOMPAREWITHTOLERANCE_WITH_TESTCASE ( output, "BasicFilters", "${tag}", ${tolerance} ); - ]] - end) - } - ) -} -#endif From 929bb7179ee1cecf67a29dd8359f54ed1b3e57c2 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 24 Jun 2016 16:06:16 -0400 Subject: [PATCH 301/412] Add support for generated CSharp files with full paths Change-Id: I7ca9a47ad57658c8ef5aa1d25c7ba5502bedbb14 --- CMake/UseCSharp.cmake | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CMake/UseCSharp.cmake b/CMake/UseCSharp.cmake index 18fc8b309..5c539afc5 100644 --- a/CMake/UseCSharp.cmake +++ b/CMake/UseCSharp.cmake @@ -76,6 +76,9 @@ macro( CSHARP_ADD_PROJECT type name ) FILE( GLOB it_glob ${it} ) list( APPEND sources ${it} ) list( APPEND sources_dep ${it_glob} ) + elseif( IS_ABSOLUTE ${it} ) + list( APPEND sources ${it} ) + list( APPEND sources_dep ${it} ) endif( ) endif ( ) endforeach( ) From 7b90d496ec634273c101a05bbdc014267046936c Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 27 Jun 2016 11:21:59 -0400 Subject: [PATCH 302/412] Removing TestHarness support with language tests Change-Id: I16d75bbf74b7a73ba34e15723ecae725a0568143 --- Testing/Unit/SimpleITKTestHarness.cxx | 240 -------------------- Testing/Unit/SimpleITKTestHarness.h | 59 ----- Testing/Unit/SimpleITKTestHarnessPaths.h.in | 30 --- Testing/Unit/SimpleITKUnitTestDriver.cxx | 1 - 4 files changed, 330 deletions(-) diff --git a/Testing/Unit/SimpleITKTestHarness.cxx b/Testing/Unit/SimpleITKTestHarness.cxx index 1136cce40..f56e5d61a 100644 --- a/Testing/Unit/SimpleITKTestHarness.cxx +++ b/Testing/Unit/SimpleITKTestHarness.cxx @@ -1,246 +1,6 @@ #include "SimpleITKTestHarness.h" -void DataFinder::SetRuntimeDirectoryFromArgv0 ( std::string argv0 ) - { - std::string errorMessage, path, dir, file; - bool result = itksys::SystemTools::FindProgramPath ( argv0.c_str(), path, errorMessage ); - mRuntimeDirectory = ""; - if ( result == false ) - { - std::cerr << "SetRuntimeDirectoryFromArgv0: couldn't determine the location of " - << argv0 << " error was: " << errorMessage << std::endl; - } - else - { - result = itksys::SystemTools::SplitProgramPath ( path.c_str(), dir, file ); - if ( result == false ) - { - std::cerr << "SetRuntimeDirectoryFromArgv0: couldn't split directory from path " << path << std::endl; - } - else - { - mRuntimeDirectory = dir; - } - } - } - -static void selectArch( std::vector& words ) - { - words.clear(); - -#ifdef OSX_ARCHITECTURES - - std::string osx_arch(OSX_ARCHITECTURES); - if (!osx_arch.length()) - { - // OSX_ARCHITECTURES has no value, so bail out - return; - } - - words.push_back("/usr/bin/arch"); - -#ifdef __x86_64__ - words.push_back("-x86_64"); -#endif -#ifdef __i386__ - words.push_back("-i386"); -#endif -#ifdef __ppc__ - words.push_back("-ppc"); -#endif -#ifdef __ppc64__ - words.push_back("-ppc64"); -#endif -#endif - } - - -std::vector DataFinder::FindExecutable ( std::string exe ) - { - return std::vector( 1, this->GetRuntimeDirectory() + "/" + exe + EXECUTABLE_SUFFIX ); - } - -std::vector DataFinder::GetLuaExecutable () - { - return this->FindExecutable ( "SimpleITKLua" ); - } - -std::vector DataFinder::GetTclExecutable () - { - return this->FindExecutable ( "SimpleITKTclsh" ); - } - -std::vector DataFinder::GetPythonExecutable () - { - std::vector words; - selectArch(words); - words.push_back(PYTHON_EXECUTABLE_PATH); - return words; - } - -std::vector DataFinder::GetRubyExecutable () - { - return std::vector ( 1, RUBY_EXECUTABLE_PATH ); - } - -std::vector DataFinder::GetRExecutable () - { - return std::vector ( 1, R_EXECUTABLE_PATH ); - } - -std::vector DataFinder::GetJavaExecutable () - { - std::vector words; - selectArch(words); - words.push_back(JAVA_EXECUTABLE_PATH); - -#ifdef OSX_ARCHITECTURES -#ifdef __x86_64__ - words.push_back("-d64"); -#endif -#ifdef __i386__ - words.push_back("-d32"); -#endif -#ifdef __ppc__ - words.push_back("-d32"); -#endif -#ifdef __ppc64__ - words.push_back("-d64"); -#endif -#endif - return words; - } - -std::vector DataFinder::GetCSharpCompiler () - { - return std::vector ( 1, CSHARP_COMPILER ); - } - -std::vector DataFinder::GetCSharpInterpreter () - { - return std::vector ( 1, CSHARP_INTERPRETER ); - } - -int ExternalProgramRunner::RunExecutable ( std::vector CommandLine, bool showOutput ) - { - std::string fullCommand; - for ( unsigned int idx = 0; idx < CommandLine.size(); idx++ ) { - fullCommand += CommandLine[idx]; - fullCommand += " "; - } - - if ( showOutput ) - { - std::cout << "Running command: '" << fullCommand << "'" << std::endl; - } - - // Allocate what we need - const char* StringCommandLine[256]; - for ( unsigned int idx = 0; idx < CommandLine.size(); idx++ ) - { - StringCommandLine[idx] = CommandLine[idx].c_str(); - } - StringCommandLine[CommandLine.size()] = NULL; - - itksysProcess* process = itksysProcess_New(); - itksysProcess_SetCommand ( process, StringCommandLine ); - itksysProcess_Execute ( process ); - - int status; - char* processData; - int processDataLength; - while ( 1 ) - { - status = itksysProcess_WaitForData ( process, &processData, &processDataLength, NULL ); - if ( status == itksysProcess_Pipe_STDOUT || status == itksysProcess_Pipe_STDERR ) - { - if ( showOutput ) - { - std::cout << std::string ( processData ) << std::endl; - } - } - else - { - // Nothing ready, so wait for the process to exit... - break; - } - } - - bool failed = false; - int ret = -1; - - itksysProcess_WaitForExit ( process, 0 ); - - switch (itksysProcess_GetState( process )) - { - case itksysProcess_State_Starting: - std::cerr << "No process has been executed." << std::endl; - failed = true; - break; - case itksysProcess_State_Executing: - std::cerr << "The process is still executing." << std::endl;; - failed = true; - break; - case itksysProcess_State_Expired: - std::cerr << "Child was killed when timeout expired." << std::endl; - failed = true; - break; - case itksysProcess_State_Exited: - ret = itksysProcess_GetExitValue(process); - break; - case itksysProcess_State_Killed: - std::cerr << "Child was killed by parent." << std::endl; - failed = true; - break; - case itksysProcess_State_Exception: - std::cerr << "Child terminated abnormally: " << itksysProcess_GetExceptionString( process ) << std::endl;; - failed = true; - break; - case itksysProcess_State_Disowned: - std::cerr << "Child was disowned." << std::endl; - failed = true; - break; - case itksysProcess_State_Error: - std::cerr << "Error in administrating child process: [" << itksysProcess_GetErrorString( process ) << "]" << std::endl; - failed = true; - break; - default: - std::cerr << "Unknown Process State" << std::endl; - failed = true; - }; - - itksysProcess_Delete ( process ); - - if ( failed ) - { - // HACK: GTest currently expects functions of void type, by - // using the comma operator we can get around this. - FAIL(), -1; - } - return ret; -} - - -void ExternalProgramRunner::CheckImageHash( const std::string &fileName, const std::string &hash ) - { - ASSERT_TRUE ( dataFinder.FileExists ( fileName ) ) << "check if " << fileName << " exists."; - - itk::simple::Image image = itk::simple::ReadImage( fileName ); - EXPECT_EQ ( hash, itk::simple::Hash( image ) ); - } - -void ExternalProgramRunner::SetEnvironment ( std::string key, std::string value ) - { -#ifdef WIN32 - std::string v = key + "=" + value; - _putenv ( v.c_str() ); - std::cout << "SetEnvironment: " << v << std::endl; -#else - setenv ( key.c_str(), value.c_str(), 1 ); - std::cout << "SetEnvironment: " << key << "=" << value << std::endl; -#endif - } ProcessObjectCommand::ProcessObjectCommand(itk::simple::ProcessObject &po) : m_Process(po) diff --git a/Testing/Unit/SimpleITKTestHarness.h b/Testing/Unit/SimpleITKTestHarness.h index ce76431a2..d994df205 100644 --- a/Testing/Unit/SimpleITKTestHarness.h +++ b/Testing/Unit/SimpleITKTestHarness.h @@ -60,13 +60,8 @@ inline std::ostream& operator<< (std::ostream& os, const std::vector& v) * should be ITK/Testing/Data * Set/GetOutputDirectory -- Temporary directory * SimpleITK-build/Testing/Temporary - * Set/GetRuntimeDirectory -- Where built executables are found - * SimpleITK-build/bin/$(OutDir)/ - * Set/GetLibraryDirectory -- Where built libraries are found - * SimpleITK-build/lib * GetOutputFile -- File in the temp directory * GetBuildDirectory -- SimpleITK-build - * FindExecutable -- Attempts to find an executable * Returns GetExecutableDirectory + "/" + filename */ class DataFinder @@ -77,8 +72,6 @@ class DataFinder { mDirectory = TEST_HARNESS_DATA_DIRECTORY; mOutputDirectory = TEST_HARNESS_TEMP_DIRECTORY; - mRuntimeDirectory = RUNTIME_OUTPUT_PATH; - mLibraryDirectory = LIBRARY_OUTPUT_PATH; }; void SetDirectory ( const char* dir ) @@ -91,7 +84,6 @@ class DataFinder mDirectory = dir; }; - void SetRuntimeDirectoryFromArgv0 ( std::string argv0 ) ; void SetOutputDirectory ( std::string dir ) { @@ -102,8 +94,6 @@ class DataFinder std::string GetOutputDirectory () const { return mOutputDirectory; }; std::string GetOutputFile ( std::string filename ) const { return mOutputDirectory + "/" + filename; }; - std::string GetRuntimeDirectory () const { return mRuntimeDirectory; } - std::string GetLibraryDirectory () const { return mLibraryDirectory; } std::string GetBuildDirectory () const { return std::string ( SIMPLEITK_BINARY_DIR ); } std::string GetPathSeparator () { @@ -114,18 +104,6 @@ class DataFinder #endif } - std::vector FindExecutable ( std::string exe ); - std::vector GetLuaExecutable (); - std::vector GetTclExecutable (); - std::vector GetPythonExecutable (); - std::vector GetRubyExecutable (); - std::vector GetRExecutable (); - std::vector GetJavaExecutable (); - std::vector GetCSharpCompiler (); - std::vector GetCSharpInterpreter (); - - std::string GetCSharpBinaryDirectory () { return std::string ( CSHARP_BINARY_DIRECTORY ); } - std::string GetSourceDirectory () { return std::string ( SIMPLEITK_SOURCE_DIR ); } bool FileExists ( const std::string &filename ) { @@ -150,48 +128,11 @@ class DataFinder std::string mDirectory; std::string mOutputDirectory; std::string mRuntimeDirectory; - std::string mLibraryDirectory; }; extern DataFinder dataFinder; -/// Class for running external programs -class ExternalProgramRunner : public testing::Test -{ -public: - - // check an image file that it matches the expected hash - void CheckImageHash ( const std::string &fileName, const std::string &hash ); - - // Return the separator - static std::string GetPathSeparator () - { -#ifdef WIN32 - return ";"; -#else - return ":"; -#endif - } - - /// \brief Set an environment variable - void SetEnvironment ( std::string key, std::string value ); - - /** \brief Run the command line specified in the list of arguments. - * Call FAIL if the executable fails returning -1, return the value returned by the - * process otherwise. - */ - int RunExecutable ( std::vector CommandLine, bool showOutput = false ); -}; - -class Python : public ExternalProgramRunner { }; -class Lua : public ExternalProgramRunner { }; -class Java : public ExternalProgramRunner { }; -class Tcl : public ExternalProgramRunner { }; -class R : public ExternalProgramRunner { }; -class Ruby : public ExternalProgramRunner { }; -class CSharp : public ExternalProgramRunner { }; - /** Base Command Class which holds onto a process object */ diff --git a/Testing/Unit/SimpleITKTestHarnessPaths.h.in b/Testing/Unit/SimpleITKTestHarnessPaths.h.in index 196cb3ecc..c3e657c57 100644 --- a/Testing/Unit/SimpleITKTestHarnessPaths.h.in +++ b/Testing/Unit/SimpleITKTestHarnessPaths.h.in @@ -18,39 +18,9 @@ #ifndef __SimpleITKTestHarnessPaths_h #define __SimpleITKTestHarnessPaths_h -#ifdef CMAKE_INTDIR - #define LIBRARY_OUTPUT_PATH "@CMAKE_LIBRARY_OUTPUT_DIRECTORY@" "/" CMAKE_INTDIR - #define RUNTIME_OUTPUT_PATH "@CMAKE_RUNTIME_OUTPUT_DIRECTORY@" "/" CMAKE_INTDIR -#else - #define LIBRARY_OUTPUT_PATH "@CMAKE_LIBRARY_OUTPUT_DIRECTORY@" - #define RUNTIME_OUTPUT_PATH "@CMAKE_RUNTIME_OUTPUT_DIRECTORY@" -#endif - -#define EXECUTABLE_SUFFIX "@CMAKE_EXECUTABLE_SUFFIX@" #define SIMPLEITK_SOURCE_DIR "@SimpleITK_SOURCE_DIR@" #define SIMPLEITK_BINARY_DIR "@SimpleITK_BINARY_DIR@" #define TEST_HARNESS_TEMP_DIRECTORY "@TEST_HARNESS_TEMP_DIRECTORY@" #define TEST_HARNESS_DATA_DIRECTORY "@TEST_HARNESS_DATA_DIRECTORY@" -#define PYTHON_EXECUTABLE_PATH "@TEST_PYTHON_EXECUTABLE@" -#define RSCRIPT_EXECUTABLE_PATH "@RSCRIPT_EXECUTABLE@" -#define R_EXECUTABLE_PATH "@R_COMMAND@" -#define JAVA_EXECUTABLE_PATH "@Java_JAVA_EXECUTABLE@" -#define JAVAC_EXECUTABLE_PATH "@Java_JAVAC_EXECUTABLE@" -#define RUBY_EXECUTABLE_PATH "@RUBY_EXECUTABLE@" -#define CSHARP_BINARY_DIRECTORY "@CSHARP_BINARY_DIRECTORY@" -#define CSHARP_COMPILER "@CSHARP_COMPILER@" -#define CSHARP_INTERPRETER "@CSHARP_INTERPRETER@" - -#define OSX_ARCHITECTURES "@CMAKE_OSX_ARCHITECTURES@" - -#cmakedefine SITK_PYTHON_USE_VIRTUALENV - -#cmakedefine WRAP_LUA -#cmakedefine WRAP_PYTHON -#cmakedefine WRAP_JAVA -#cmakedefine WRAP_CSHARP -#cmakedefine WRAP_TCL -#cmakedefine WRAP_R -#cmakedefine WRAP_RUBY #endif diff --git a/Testing/Unit/SimpleITKUnitTestDriver.cxx b/Testing/Unit/SimpleITKUnitTestDriver.cxx index 8ad11a632..fe8b28860 100644 --- a/Testing/Unit/SimpleITKUnitTestDriver.cxx +++ b/Testing/Unit/SimpleITKUnitTestDriver.cxx @@ -45,6 +45,5 @@ int main(int argc, char* argv[]) } } testing::InitGoogleTest ( &argc, argv ); - dataFinder.SetRuntimeDirectoryFromArgv0 ( argv[0] ); return RUN_ALL_TESTS(); } From fe999bff970290d45ef6aa88e5dfba9ded44d234 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 27 Jun 2016 14:11:08 -0400 Subject: [PATCH 303/412] Add Expand template generation for language tests Change-Id: Ib9ec094be3a609af2fae7a85c998f01ccb4b496c --- Testing/Unit/CMakeLists.txt | 13 ++ .../Unit/ImageFilterCTestTemplate.cmake.in | 137 ++++++++++++++++++ 2 files changed, 150 insertions(+) create mode 100644 Testing/Unit/ImageFilterCTestTemplate.cmake.in diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index c57b240e8..5df498519 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -39,6 +39,7 @@ if ( SITK_4D_IMAGES ) list(APPEND SimpleITKUnitTestSource sitkImage4DTests.cxx ) endif() +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/CTest) file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/PythonTests) file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/LuaTests) file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/TclTests) @@ -112,6 +113,18 @@ foreach ( FILTERNAME ${GENERATED_FILTER_LIST} ) set(template_name "${CMAKE_MATCH_1}" ) if (template_name) + set(OUTPUT_TEST_FILENAME "${SimpleITK_BINARY_DIR}/Testing/Unit/CTest/${FILTERNAME}.cmake") + file(REMOVE "${OUTPUT_TEST_FILENAME}") + execute_process( + COMMAND ${SITK_LUA_EXECUTABLE} ${template_expansion_script} test ${filter_json_file} ${SimpleITK_SOURCE_DIR}/Testing/Unit/ ${template_include_dir} CTestTemplate.cmake.in "${OUTPUT_TEST_FILENAME}" + RESULT_VARIABLE failed + ERROR_VARIABLE error + ) + if ( failed ) + message( FATAL_ERROR "Failed to generate ${OUTPUT_TEST_FILENAME}\n${error}" ) + endif() + include("${OUTPUT_TEST_FILENAME}") + set(OUTPUT_TEST_FILENAME "${SimpleITK_BINARY_DIR}/Testing/Unit/sitk${FILTERNAME}Test.cxx") add_custom_command ( OUTPUT ${OUTPUT_TEST_FILENAME} diff --git a/Testing/Unit/ImageFilterCTestTemplate.cmake.in b/Testing/Unit/ImageFilterCTestTemplate.cmake.in new file mode 100644 index 000000000..0966719a1 --- /dev/null +++ b/Testing/Unit/ImageFilterCTestTemplate.cmake.in @@ -0,0 +1,137 @@ +# TODO +# - test output + +# +# Lua Tests +# +$(for i=1,#tests do +local script = "$${SimpleITK_BINARY_DIR}/Testing/Unit/LuaTests/${name}Test.lua" +OUT=[[ + sitk_add_lua_test( ${name}.]]..tests[i].tag..[[ + "]]..script..[[" + ]]..tests[i].tag..[[ +]] +for j=1,#tests[i].inputs do + OUT=OUT..[[ + "DATA{$${SimpleITK_DATA_ROOT}/]]..tests[i].inputs[j]..[[}" +]] +end +OUT=OUT..[[ + "$${TEST_HARNESS_TEMP_DIRECTORY}/Lua-${name}-]]..tests[i].tag..[[.nrrd" )]] +end) + + +# +# Python Tests +# +$(for i=1,#tests do +local script = "$${SimpleITK_BINARY_DIR}/Testing/Unit/PythonTests/${name}Test.py" +OUT=[[ + sitk_add_python_test( ${name}.]]..tests[i].tag..[[ + "]]..script..[[" + ]]..tests[i].tag..[[ +]] +for j=1,#tests[i].inputs do + OUT=OUT..[[ + "DATA{$${SimpleITK_DATA_ROOT}/]]..tests[i].inputs[j]..[[}" +]] +end +OUT=OUT..[[ + "$${TEST_HARNESS_TEMP_DIRECTORY}/Python-${name}-]]..tests[i].tag..[[.nrrd" )]] +end) + +# +# Ruby Tests +# +$(for i=1,#tests do +local script = "$${SimpleITK_BINARY_DIR}/Testing/Unit/RubyTests/${name}Test.rb" +OUT=[[ + sitk_add_ruby_test( ${name}.]]..tests[i].tag..[[ + "]]..script..[[" + ]]..tests[i].tag..[[ +]] +for j=1,#tests[i].inputs do + OUT=OUT..[[ + "DATA{$${SimpleITK_DATA_ROOT}/]]..tests[i].inputs[j]..[[}" +]] +end +OUT=OUT..[[ + "$${TEST_HARNESS_TEMP_DIRECTORY}/Ruby-${name}-]]..tests[i].tag..[[.nrrd" )]] +end) + +# +# R Tests +# +$(for i=1,#tests do +local script = "$${SimpleITK_BINARY_DIR}/Testing/Unit/RTests/${name}Test.R" +OUT=[[ + sitk_add_r_test( ${name}.]]..tests[i].tag..[[ + "--file=]]..script..[[" + --args + ]]..tests[i].tag..[[ +]] +for j=1,#tests[i].inputs do + OUT=OUT..[[ + "DATA{$${SimpleITK_DATA_ROOT}/]]..tests[i].inputs[j]..[[}" +]] +end +OUT=OUT..[[ + "$${TEST_HARNESS_TEMP_DIRECTORY}/R-${name}-]]..tests[i].tag..[[.nrrd" )]] +end) + +# +# Tcl Tests +# +$(for i=1,#tests do +OUT=[[ + sitk_add_tcl_test( ${name}[]]..tests[i].tag..[[] + "$${SimpleITK_BINARY_DIR}/Testing/Unit/TclTests/${name}Test.tcl" + ]]..tests[i].tag..[[ +]] +for j=1,#tests[i].inputs do + OUT=OUT..[[ + "DATA{$${SimpleITK_DATA_ROOT}/]]..tests[i].inputs[j]..[[}" +]] +end +OUT=OUT..[[ + "$${TEST_HARNESS_TEMP_DIRECTORY}/Tcl-${name}-]]..tests[i].tag..[[.nrrd" )]] +end) + + +# +# Java Tests +# +$(for i=1,#tests do +OUT=[[ + sitk_add_java_test( ${name}.]]..tests[i].tag..[[ + "$${SimpleITK_BINARY_DIR}/Testing/Unit/JavaTests/${name}Test.java" + ]]..tests[i].tag..[[ +]] +for j=1,#tests[i].inputs do + OUT=OUT..[[ + "DATA{$${SimpleITK_DATA_ROOT}/]]..tests[i].inputs[j]..[[}" +]] +end +OUT=OUT..[[ + "$${TEST_HARNESS_TEMP_DIRECTORY}/Java-${name}-]]..tests[i].tag..[[.nrrd" )]] +end) + + + +# +# CSharp Tests +# +$(for i=1,#tests do +OUT=[[ + sitk_add_csharp_test( ${name}[]]..tests[i].tag..[[] + "$${SimpleITK_BINARY_DIR}/Testing/Unit/CSharpTests/${name}Test.cs" + ]]..tests[i].tag..[[ +]] +for j=1,#tests[i].inputs do + OUT=OUT..[[ + "DATA{$${SimpleITK_DATA_ROOT}/]]..tests[i].inputs[j]..[[}" +]] +end +OUT=OUT..[[ + "$${TEST_HARNESS_TEMP_DIRECTORY}/CSharp-${name}-]]..tests[i].tag..[[.nrrd" )]] +end) From f15e51e8251639eebad08004426dfcb51807b8a2 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 28 Jun 2016 09:23:32 -0400 Subject: [PATCH 304/412] Restore multiple tests for language generated tests. Change-Id: I447993c7d9a2e412f9edd216a52eff4f984b794b --- CMake/sitkAddTest.cmake | 16 ++++++++++------ Testing/Unit/ImageFilterCTestTemplate.cmake.in | 17 +++++++++-------- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index 0f65a1ddd..afad1b809 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -253,12 +253,16 @@ function(sitk_add_csharp_test name csharp_file) set( CSHARP_EXECUTABLE "CSharp${CSHARP_EXECUTABLE}" ) endif() - # add the target to compile the test - csharp_add_executable( - "${CSHARP_EXECUTABLE}" - SimpleITKCSharpManaged.dll - ${csharp_file} - ) + + if (NOT TARGET "${CSHARP_EXECUTABLE}") + + # add the target to compile the test + csharp_add_executable( + "${CSHARP_EXECUTABLE}" + SimpleITKCSharpManaged.dll + ${csharp_file} + ) + endif() # because each executable is it's own target we actually don't # need to make a target depend on this list diff --git a/Testing/Unit/ImageFilterCTestTemplate.cmake.in b/Testing/Unit/ImageFilterCTestTemplate.cmake.in index 0966719a1..e62e992c8 100644 --- a/Testing/Unit/ImageFilterCTestTemplate.cmake.in +++ b/Testing/Unit/ImageFilterCTestTemplate.cmake.in @@ -6,7 +6,7 @@ # $(for i=1,#tests do local script = "$${SimpleITK_BINARY_DIR}/Testing/Unit/LuaTests/${name}Test.lua" -OUT=[[ +OUT=OUT..[[ sitk_add_lua_test( ${name}.]]..tests[i].tag..[[ "]]..script..[[" ]]..tests[i].tag..[[ @@ -26,7 +26,7 @@ end) # $(for i=1,#tests do local script = "$${SimpleITK_BINARY_DIR}/Testing/Unit/PythonTests/${name}Test.py" -OUT=[[ +OUT=OUT..[[ sitk_add_python_test( ${name}.]]..tests[i].tag..[[ "]]..script..[[" ]]..tests[i].tag..[[ @@ -45,7 +45,7 @@ end) # $(for i=1,#tests do local script = "$${SimpleITK_BINARY_DIR}/Testing/Unit/RubyTests/${name}Test.rb" -OUT=[[ +OUT=OUT..[[ sitk_add_ruby_test( ${name}.]]..tests[i].tag..[[ "]]..script..[[" ]]..tests[i].tag..[[ @@ -64,7 +64,7 @@ end) # $(for i=1,#tests do local script = "$${SimpleITK_BINARY_DIR}/Testing/Unit/RTests/${name}Test.R" -OUT=[[ +OUT=OUT..[[ sitk_add_r_test( ${name}.]]..tests[i].tag..[[ "--file=]]..script..[[" --args @@ -76,14 +76,15 @@ for j=1,#tests[i].inputs do ]] end OUT=OUT..[[ - "$${TEST_HARNESS_TEMP_DIRECTORY}/R-${name}-]]..tests[i].tag..[[.nrrd" )]] + "$${TEST_HARNESS_TEMP_DIRECTORY}/R-${name}-]]..tests[i].tag..[[.nrrd" ) +]] end) # # Tcl Tests # $(for i=1,#tests do -OUT=[[ +OUT=OUT..[[ sitk_add_tcl_test( ${name}[]]..tests[i].tag..[[] "$${SimpleITK_BINARY_DIR}/Testing/Unit/TclTests/${name}Test.tcl" ]]..tests[i].tag..[[ @@ -102,7 +103,7 @@ end) # Java Tests # $(for i=1,#tests do -OUT=[[ +OUT=OUT..[[ sitk_add_java_test( ${name}.]]..tests[i].tag..[[ "$${SimpleITK_BINARY_DIR}/Testing/Unit/JavaTests/${name}Test.java" ]]..tests[i].tag..[[ @@ -122,7 +123,7 @@ end) # CSharp Tests # $(for i=1,#tests do -OUT=[[ +OUT=OUT..[[ sitk_add_csharp_test( ${name}[]]..tests[i].tag..[[] "$${SimpleITK_BINARY_DIR}/Testing/Unit/CSharpTests/${name}Test.cs" ]]..tests[i].tag..[[ From 7ec02ecc17bc8836fc5c18b04c1d117672dcf9cc Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 28 Jun 2016 10:02:53 -0400 Subject: [PATCH 305/412] Correct language test names to use "." over "[ ]". The brackets can be interpreted as part of a regular expression, which prevent the test name from being called with "ctest -R $name". Change-Id: I6bd590ba178d34074013855510c9d4152dccb260 --- Testing/Unit/ImageFilterCTestTemplate.cmake.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Testing/Unit/ImageFilterCTestTemplate.cmake.in b/Testing/Unit/ImageFilterCTestTemplate.cmake.in index e62e992c8..fbfe11c49 100644 --- a/Testing/Unit/ImageFilterCTestTemplate.cmake.in +++ b/Testing/Unit/ImageFilterCTestTemplate.cmake.in @@ -85,7 +85,7 @@ end) # $(for i=1,#tests do OUT=OUT..[[ - sitk_add_tcl_test( ${name}[]]..tests[i].tag..[[] + sitk_add_tcl_test( ${name}.]]..tests[i].tag..[[ "$${SimpleITK_BINARY_DIR}/Testing/Unit/TclTests/${name}Test.tcl" ]]..tests[i].tag..[[ ]] @@ -124,7 +124,7 @@ end) # $(for i=1,#tests do OUT=OUT..[[ - sitk_add_csharp_test( ${name}[]]..tests[i].tag..[[] + sitk_add_csharp_test( ${name}.]]..tests[i].tag..[[ "$${SimpleITK_BINARY_DIR}/Testing/Unit/CSharpTests/${name}Test.cs" ]]..tests[i].tag..[[ ]] From c10f41f7f07be19c94d7ef238e2085cefc07d368 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 28 Jun 2016 12:57:40 -0400 Subject: [PATCH 306/412] Adding missing new line after end of function. Change-Id: I4a1cb1391f8ce3d5d72cd091189efd39ea439cc3 --- Testing/Unit/ImageFilterCTestTemplate.cmake.in | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Testing/Unit/ImageFilterCTestTemplate.cmake.in b/Testing/Unit/ImageFilterCTestTemplate.cmake.in index fbfe11c49..f09d2f3ac 100644 --- a/Testing/Unit/ImageFilterCTestTemplate.cmake.in +++ b/Testing/Unit/ImageFilterCTestTemplate.cmake.in @@ -17,7 +17,8 @@ for j=1,#tests[i].inputs do ]] end OUT=OUT..[[ - "$${TEST_HARNESS_TEMP_DIRECTORY}/Lua-${name}-]]..tests[i].tag..[[.nrrd" )]] + "$${TEST_HARNESS_TEMP_DIRECTORY}/Lua-${name}-]]..tests[i].tag..[[.nrrd" ) +]] end) @@ -37,7 +38,8 @@ for j=1,#tests[i].inputs do ]] end OUT=OUT..[[ - "$${TEST_HARNESS_TEMP_DIRECTORY}/Python-${name}-]]..tests[i].tag..[[.nrrd" )]] + "$${TEST_HARNESS_TEMP_DIRECTORY}/Python-${name}-]]..tests[i].tag..[[.nrrd" ) +]] end) # @@ -56,7 +58,8 @@ for j=1,#tests[i].inputs do ]] end OUT=OUT..[[ - "$${TEST_HARNESS_TEMP_DIRECTORY}/Ruby-${name}-]]..tests[i].tag..[[.nrrd" )]] + "$${TEST_HARNESS_TEMP_DIRECTORY}/Ruby-${name}-]]..tests[i].tag..[[.nrrd" ) +]] end) # @@ -95,7 +98,8 @@ for j=1,#tests[i].inputs do ]] end OUT=OUT..[[ - "$${TEST_HARNESS_TEMP_DIRECTORY}/Tcl-${name}-]]..tests[i].tag..[[.nrrd" )]] + "$${TEST_HARNESS_TEMP_DIRECTORY}/Tcl-${name}-]]..tests[i].tag..[[.nrrd" ) +]] end) @@ -114,7 +118,8 @@ for j=1,#tests[i].inputs do ]] end OUT=OUT..[[ - "$${TEST_HARNESS_TEMP_DIRECTORY}/Java-${name}-]]..tests[i].tag..[[.nrrd" )]] + "$${TEST_HARNESS_TEMP_DIRECTORY}/Java-${name}-]]..tests[i].tag..[[.nrrd" ) +]] end) @@ -134,5 +139,6 @@ for j=1,#tests[i].inputs do ]] end OUT=OUT..[[ - "$${TEST_HARNESS_TEMP_DIRECTORY}/CSharp-${name}-]]..tests[i].tag..[[.nrrd" )]] + "$${TEST_HARNESS_TEMP_DIRECTORY}/CSharp-${name}-]]..tests[i].tag..[[.nrrd" ) +]] end) From bbea2f4b6eacd338eb83f23ac0ca41a85f4fd273 Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Wed, 15 Jun 2016 11:31:46 +1000 Subject: [PATCH 307/412] Correct R doc linking. Change-Id: Id83ab3bfab33b2c31676b323f7a5e958cd60cd87 --- Wrapping/R/Packaging/SimpleITK/man/SimpleITK_Image-class.Rd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Wrapping/R/Packaging/SimpleITK/man/SimpleITK_Image-class.Rd b/Wrapping/R/Packaging/SimpleITK/man/SimpleITK_Image-class.Rd index 7a2d963ee..7c47dedbf 100644 --- a/Wrapping/R/Packaging/SimpleITK/man/SimpleITK_Image-class.Rd +++ b/Wrapping/R/Packaging/SimpleITK/man/SimpleITK_Image-class.Rd @@ -102,5 +102,5 @@ Arrays can be converted to images using \code{as.image}. } } \references{ -\link{https://itk.org/SimpleITKDoxygen/html/index.html} +\url{https://itk.org/SimpleITKDoxygen/html/index.html} } From 157ca2796e8aa247dcd762b2cf0c518ec164debd Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 28 Jun 2016 14:53:45 -0400 Subject: [PATCH 308/412] Updating ITK tag with a couple more patches with 4.10 release Change-Id: I637e559ce826821c9469081186a77ec37a1f5cfc --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index b0c7f97b1..ee1217318 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -40,7 +40,7 @@ if("${git_protocol}" STREQUAL "git") endif() # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG b14b3488bd926c835a03ab12a5663bfc7eca3a92 ) # just after 4.10.0 release +set(ITK_TAG_COMMAND GIT_TAG 1bf7263085f1d700518bf968248647a1ccb971df ) # just after 4.10.0 release if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 6fc22492ca1fd3ebb493160b7968c37a0a6f1986 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 28 Jun 2016 15:05:01 -0400 Subject: [PATCH 309/412] Adding link type specification to SimpleITK libraries This should reduces the direct dependencies of SimpleITK libraries an may improve run-time linking when loading SimpleITK. Change-Id: I36eaf3296abe0f9a2ec0dbb5128efc1c62775a2f --- CMakeLists.txt | 4 +++- Code/BasicFilters/src/CMakeLists.txt | 15 +++++++++++---- Code/Common/src/CMakeLists.txt | 5 +++-- Code/Explicit/src/CMakeLists.txt | 2 +- Code/IO/src/CMakeLists.txt | 4 +++- Testing/Unit/CMakeLists.txt | 2 +- Wrapping/Python/CMakeLists.txt | 2 +- 7 files changed, 23 insertions(+), 11 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b44aedf16..6227226c0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -150,7 +150,9 @@ set ( SimpleITK_LIBRARIES SimpleITKCommon SimpleITKIO SimpleITKRegistration ) if (SITK_EXPLICIT_INSTANTIATION) list ( APPEND SimpleITK_INCLUDE_DIRS ${CMAKE_SOURCE_DIR}/Code/Explicit/include ) - list ( APPEND SimpleITK_LIBRARIES SimpleITKExplicit ) + # This library is linked privately to SimpleITK libraries and is not + # part of the public link interface + #list ( APPEND SimpleITK_LIBRARIES SimpleITKExplicit ) endif() set( SimpleITK_LIBRARIES ${SimpleITK_LIBRARIES} CACHE INTERNAL "" ) diff --git a/Code/BasicFilters/src/CMakeLists.txt b/Code/BasicFilters/src/CMakeLists.txt index ff67bc5fa..dbc55f881 100644 --- a/Code/BasicFilters/src/CMakeLists.txt +++ b/Code/BasicFilters/src/CMakeLists.txt @@ -17,7 +17,9 @@ set ( SimpleITKBasicFilters0Source ) add_library ( SimpleITKBasicFilters0 ${SimpleITKBasicFilters0Source} ) -target_link_libraries ( SimpleITKBasicFilters0 SimpleITKCommon ${ITK_LIBRARIES} ) +target_link_libraries ( SimpleITKBasicFilters0 + PUBLIC SimpleITKCommon + PRIVATE ${ITK_LIBRARIES} ) set_target_properties( SimpleITKBasicFilters0 PROPERTIES SKIP_BUILD_RPATH TRUE ) sitk_install_exported_target( SimpleITKBasicFilters0 ) @@ -48,7 +50,9 @@ set ( SimpleITKBasicFilters1Source ) add_library ( SimpleITKBasicFilters1 ${SimpleITKBasicFilters1Source} ) -target_link_libraries ( SimpleITKBasicFilters1 SimpleITKCommon SimpleITKBasicFilters0 ${ITK_LIBRARIES} ) +target_link_libraries ( SimpleITKBasicFilters1 + PUBLIC SimpleITKCommon SimpleITKBasicFilters0 + PRIVATE ${ITK_LIBRARIES} ) set_target_properties( SimpleITKBasicFilters1 PROPERTIES SKIP_BUILD_RPATH TRUE ) add_dependencies ( SimpleITKBasicFilters1 BasicFiltersSourceCode ) sitk_install_exported_target( SimpleITKBasicFilters1 ) @@ -101,11 +105,14 @@ foreach ( _start RANGE 0 ${_end_range} ${_stride} ) endforeach() add_library ( SimpleITKBasicFilters${_library_i} ${SRC} ) - target_link_libraries ( SimpleITKBasicFilters${_library_i} SimpleITKCommon SimpleITKBasicFilters0 ${ITK_LIBRARIES} ) + target_link_libraries ( SimpleITKBasicFilters${_library_i} + PUBLIC SimpleITKCommon SimpleITKBasicFilters0 + PRIVATE ${ITK_LIBRARIES} ) if(_last) # the last library include additional cxx files which may depend on # other filter libraries - target_link_libraries ( SimpleITKBasicFilters${_library_i} ${SimpleITK_LIBRARIES} ) + target_link_libraries ( SimpleITKBasicFilters${_library_i} + PRIVATE ${SimpleITK_LIBRARIES} ) endif() set_target_properties( SimpleITKBasicFilters${_library_i} PROPERTIES SKIP_BUILD_RPATH TRUE ) add_dependencies ( SimpleITKBasicFilters${_library_i} BasicFiltersSourceCode ) diff --git a/Code/Common/src/CMakeLists.txt b/Code/Common/src/CMakeLists.txt index bebb12252..ed119fee1 100644 --- a/Code/Common/src/CMakeLists.txt +++ b/Code/Common/src/CMakeLists.txt @@ -34,9 +34,10 @@ find_package(ITK COMPONENTS ITKCommon ITKImageCompose include(${ITK_USE_FILE}) add_library ( SimpleITKCommon ${SimpleITKCommonSource} ${SimpleITKAncillarySource} ) -target_link_libraries ( SimpleITKCommon ${ITK_LIBRARIES} ) +target_link_libraries ( SimpleITKCommon + PRIVATE ${ITK_LIBRARIES} ) if (SITK_EXPLICIT_INSTANTIATION) - target_link_libraries ( SimpleITKCommon SimpleITKExplicit ) + target_link_libraries ( SimpleITKCommon PRIVATE SimpleITKExplicit ) endif() set_target_properties( SimpleITKCommon PROPERTIES SKIP_BUILD_RPATH TRUE ) diff --git a/Code/Explicit/src/CMakeLists.txt b/Code/Explicit/src/CMakeLists.txt index befea99dc..93f17c8ba 100644 --- a/Code/Explicit/src/CMakeLists.txt +++ b/Code/Explicit/src/CMakeLists.txt @@ -32,6 +32,6 @@ if ( MSVC AND SITK_BUILD_SHARED_LIBS ) endif() add_library ( SimpleITKExplicit ${SimpleITKExplicit_FORCE_LIBRARY_TYPE} ${SimpleITKExplicitSource} ) -target_link_libraries ( SimpleITKExplicit ${ITK_LIBRARIES} ) +target_link_libraries ( SimpleITKExplicit PUBLIC ${ITK_LIBRARIES} ) set_target_properties( SimpleITKExplicit PROPERTIES SKIP_BUILD_RPATH TRUE ) sitk_install_exported_target( SimpleITKExplicit ) diff --git a/Code/IO/src/CMakeLists.txt b/Code/IO/src/CMakeLists.txt index ec131c89e..038872027 100644 --- a/Code/IO/src/CMakeLists.txt +++ b/Code/IO/src/CMakeLists.txt @@ -23,7 +23,9 @@ find_package(ITK COMPONENTS REQUIRED) include(${ITK_USE_FILE}) add_library ( SimpleITKIO ${SimpleITKIOSource} ) -target_link_libraries ( SimpleITKIO ${ITK_LIBRARIES} SimpleITKCommon ) +target_link_libraries ( SimpleITKIO + PUBLIC SimpleITKCommon + PRIVATE ${ITK_LIBRARIES} ) set_target_properties( SimpleITKIO PROPERTIES SKIP_BUILD_RPATH TRUE ) sitk_install_exported_target( SimpleITKIO ) diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index ad4e733f4..55d6400d9 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -54,7 +54,7 @@ set(JAR_FILE "simpleitk-${SimpleITK_VERSION}.jar") add_executable(SimpleITKUnitTestDriver0 SimpleITKUnitTestDriver.cxx ${SimpleITKUnitTestSource}) -target_link_libraries ( SimpleITKUnitTestDriver0 ${GTEST_LIBRARIES} SimpleITKUnitTestBase ${SimpleITK_LIBRARIES} ) +target_link_libraries ( SimpleITKUnitTestDriver0 ${GTEST_LIBRARIES} SimpleITKUnitTestBase ${SimpleITK_LIBRARIES} ${ITK_LIBRARIES} ) # # Glob for necessary template files up front, before the foreach loop over diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index 0205b0f45..addf772c8 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -48,7 +48,7 @@ SWIG_add_module ( SimpleITK python SimpleITK.i sitkPyCommand.cxx ) set(SWIG_MODULE_SimpleITKPython_TARGET_NAME "${SWIG_MODULE_SimpleITK_TARGET_NAME}") -target_link_libraries ( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ${SimpleITK_LIBRARIES} ) +target_link_libraries( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ${SimpleITK_LIBRARIES} ) sitk_target_link_libraries_with_dynamic_lookup( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ${PYTHON_LIBRARIES} ) set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") sitk_strip_target( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ) From e4421dcb8006e74cfd0145c0a57a8ec0a4b9191e Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 28 Jun 2016 15:30:47 -0400 Subject: [PATCH 310/412] Remove dead CMake code Change-Id: I1d620c18a46b2dbe33e79e9af362a27a72aa1f05 --- CMakeLists.txt | 7 ------- 1 file changed, 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b44aedf16..e8ba4f00c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -84,13 +84,6 @@ set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_ set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") - -if( NOT ITK_USE_REVIEW ) -# TODO need to check ITK configuration to verify that it has the needed modules -# message(FATAL_ERROR "Please reconfigure ITK by turning ITK_USE_REVIEW ON") -endif() - - #---------------------------------------------------------- # Place all options to go into sitkConfigure.h here option(BUILD_SHARED_LIBS "Build SimpleITK ITK with shared libraries. This does not effect wrapped languages." OFF) From c24c32d6c3ef9791f5cdfb13b1ad14c504324b32 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 28 Jun 2016 15:31:12 -0400 Subject: [PATCH 311/412] Add CMAKE_LINKER to propagate from Superbuild This is useful when setting the linker to ld.gold Change-Id: I814f36d7d79e7a2609930b0c96e390fbc29d82cb --- SuperBuild/SuperBuild.cmake | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 02be02d43..4ea2f4170 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -193,6 +193,8 @@ list( APPEND ep_common_list CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_RELWITHDEBINFO + CMAKE_LINKER + CMAKE_EXE_LINKER_FLAGS CMAKE_EXE_LINKER_FLAGS_DEBUG CMAKE_EXE_LINKER_FLAGS_MINSIZEREL From f00fe487ebcf7039c6e53af7f968127943f6a1ce Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 28 Jun 2016 15:55:34 -0400 Subject: [PATCH 312/412] Create Python SimpleITK library in wrapping directory Remove the copy step in the build process and just create the library where it needs to be for testing and packaging. Change-Id: Ie544639ccbdf1cd4b7541d9b6f8a94f3d95cbddd --- Wrapping/Python/CMakeLists.txt | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index 0205b0f45..031c16770 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -50,6 +50,7 @@ SWIG_add_module ( SimpleITK python set(SWIG_MODULE_SimpleITKPython_TARGET_NAME "${SWIG_MODULE_SimpleITK_TARGET_NAME}") target_link_libraries ( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ${SimpleITK_LIBRARIES} ) sitk_target_link_libraries_with_dynamic_lookup( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ${PYTHON_LIBRARIES} ) +set_target_properties( ${SWIG_MODULE_SimpleITK_TARGET_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") sitk_strip_target( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ) @@ -59,11 +60,6 @@ sitk_strip_target( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ) set( SIMPLEITK_PYTHON_PACKAGE_DIR "${CMAKE_CURRENT_BINARY_DIR}" ) file( TO_NATIVE_PATH "${SIMPLEITK_PYTHON_PACKAGE_DIR}" SIMPLEITK_PYTHON_PACKAGE_DIR ) get_target_property( SWIG_MODULE_SimpleITKPython_TARGET_LOCATION ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} OUTPUT_NAME ) -add_custom_command( - TARGET ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy "$" "${CMAKE_CURRENT_BINARY_DIR}" - ) get_target_property( SIMPLEITK_RELATIVE_BINARY_MODULE ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} LOCATION ) get_filename_component( SIMPLEITK_RELATIVE_BINARY_MODULE "${SIMPLEITK_RELATIVE_BINARY_MODULE}" NAME ) From 97f97d6e3483c092ac996b29ff323cb395c52801 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 28 Jun 2016 15:57:05 -0400 Subject: [PATCH 313/412] Override default output paths for language wrapping When building SimpleITK and all wrapped languages as one project, the language libraries are built in the language specific sub directory. This should prevent conflicts, preserve order, and clarify the executable and the libraries with directories. Change-Id: I8c39d15c56deb112eeaebe51144f9ab62bfecdda --- CMake/sitkProjectLanguageCommon.cmake | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/CMake/sitkProjectLanguageCommon.cmake b/CMake/sitkProjectLanguageCommon.cmake index 362b2c5fa..255cc0ac7 100644 --- a/CMake/sitkProjectLanguageCommon.cmake +++ b/CMake/sitkProjectLanguageCommon.cmake @@ -23,6 +23,18 @@ if (NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK" ) endif() + +# Setup build locations to the wrapping language sub directories +if(NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY OR CMAKE_PROJECT_NAME STREQUAL "SimpleITK" ) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin) +endif() +if(NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY OR CMAKE_PROJECT_NAME STREQUAL "SimpleITK" ) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/lib) +endif() +if(NOT CMAKE_ARCHIVE_OUTPUT_DIRECTORY OR CMAKE_PROJECT_NAME STREQUAL "SimpleITK" ) + set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/lib) +endif() + if(NOT TARGET dist) add_custom_target( dist cmake -E echo "Finished generating wrapped packages for distribution..." ) endif() From bed185dd7b0bdab5296a94209c02e0938a3d354f Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 29 Jun 2016 10:18:03 -0400 Subject: [PATCH 314/412] Updating Swig superbuild version to 3.0.10 Change-Id: I45449b5341410dac5f03cdb868e3b8ddab6f7677 --- SuperBuild/External_Swig.cmake | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/SuperBuild/External_Swig.cmake b/SuperBuild/External_Swig.cmake index 3de7a2e96..d624bab80 100644 --- a/SuperBuild/External_Swig.cmake +++ b/SuperBuild/External_Swig.cmake @@ -20,14 +20,14 @@ if(NOT SWIG_DIR) if( USE_SWIG_FROM_GIT ) set(SWIG_GIT_REPOSITORY "${git_protocol}://github.com/swig/swig.git" CACHE STRING "URL of swig git repo") - set(SWIG_GIT_TAG "rel-3.0.9" CACHE STRING "Tag in swig git repo") + set(SWIG_GIT_TAG "rel-3.0.10" CACHE STRING "Tag in swig git repo") mark_as_advanced(SWIG_GIT_REPO) mark_as_advanced(SWIG_GIT_TAG) endif() - set(SWIG_TARGET_VERSION "3.0.9" ) - set(SWIG_DOWNLOAD_SOURCE_HASH "4bc5f46a6cdedbd8f579b25fafc96fd6") - set(SWIG_DOWNLOAD_WIN_HASH "811adf794d26a0cf54da578c2b9a14a3") + set(SWIG_TARGET_VERSION "3.0.10" ) + set(SWIG_DOWNLOAD_SOURCE_HASH "bb4ab8047159469add7d00910e203124") + set(SWIG_DOWNLOAD_WIN_HASH "f229724fe856aa78df6128ecfefe6e0a") if(WIN32) # binary SWIG for windows From 066d755c935d45ee9591e10b5e97173b0114b75a Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 29 Jun 2016 12:22:34 -0400 Subject: [PATCH 315/412] CMake version 3 is now required There are two problems encountered with CMake <3.0 that are motivating the problem: - Use PRIVATE,PUBLIC,INTERFACE with target_link_libraries. This is the current recommended way, and does not encounter CMP0022 issues. - We are using generator expression in ctest properties for environment variables. CMake 3.0 has better support for generator expressions. Change-Id: If3d100877b8d7d98ce253f7016701213dca42176 --- CMakeLists.txt | 4 ++-- SuperBuild/CMakeLists.txt | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e8ba4f00c..d57179515 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) +cmake_minimum_required ( VERSION 3.0 FATAL_ERROR ) # Explicitly add INCREMENTAL linking option to command lines. # http://www.cmake.org/pipermail/cmake/2010-February/035174.html @@ -6,7 +6,7 @@ SET(MSVC_INCREMENTAL_DEFAULT ON) project ( SimpleITK ) -cmake_policy( VERSION 2.8.1 ) +cmake_policy( VERSION 3.0 ) # NEW CMP0042 diff --git a/SuperBuild/CMakeLists.txt b/SuperBuild/CMakeLists.txt index 4b7045ead..3849141d9 100644 --- a/SuperBuild/CMakeLists.txt +++ b/SuperBuild/CMakeLists.txt @@ -12,7 +12,7 @@ if( NOT DEFINED CMAKE_INSTALL_PREFIX ) set(CMAKE_INSTALL_PREFIX ${CMAKE_CURRENT_BINARY_DIR} CACHE PATH "Where all the prerequisite libraries go") endif() -cmake_minimum_required ( VERSION 2.8.4 ) +cmake_minimum_required ( VERSION 3.0 ) project ( SuperBuildSimpleITK ) #----------------------------------------------------------------------------- From cfc925366537fd8dd01a22be15ccc04840f5b01b Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 29 Jun 2016 13:27:02 -0400 Subject: [PATCH 316/412] Install generated headers and ".i" files in generation function Change-Id: I9fd347d9349acf5c5a1c341498ee1785bb0d8ce9 --- CMake/sitkGenerateFilterSource.cmake | 8 ++++++++ CMakeLists.txt | 4 ---- Code/BasicFilters/src/CMakeLists.txt | 5 ----- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/CMake/sitkGenerateFilterSource.cmake b/CMake/sitkGenerateFilterSource.cmake index edf2510ee..fef2c395a 100644 --- a/CMake/sitkGenerateFilterSource.cmake +++ b/CMake/sitkGenerateFilterSource.cmake @@ -231,4 +231,12 @@ macro(generate_filter_source) configure_file( "${tmp_generated_headers_h}" "${generated_headers_h}" COPYONLY ) configure_file( "${tmp_generated_headers_i}" "${generated_headers_i}" COPYONLY ) + install(FILES + ${SimpleITK${directory_name}GeneratedSource} + ${generated_headers_h} + ${generated_headers_i} + DESTINATION ${SimpleITK_INSTALL_INCLUDE_DIR} + COMPONENT Development) + + endmacro() diff --git a/CMakeLists.txt b/CMakeLists.txt index d57179515..0d8d35524 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -442,10 +442,6 @@ file( GLOB __files ${CMAKE_SOURCE_DIR}/Code/Registration/include/*.hxx ) -set(__files ${__files} - ${SimpleITKBasicFiltersGeneratedHeader} - ) - install(FILES ${__files} DESTINATION ${SimpleITK_INSTALL_INCLUDE_DIR} COMPONENT Development) diff --git a/Code/BasicFilters/src/CMakeLists.txt b/Code/BasicFilters/src/CMakeLists.txt index ff67bc5fa..564969252 100644 --- a/Code/BasicFilters/src/CMakeLists.txt +++ b/Code/BasicFilters/src/CMakeLists.txt @@ -117,8 +117,3 @@ foreach ( _start RANGE 0 ${_end_range} ${_stride} ) sitk_install_exported_target( SimpleITKBasicFilters${_library_i} ) endforeach () - - -install( FILES ${CMAKE_CURRENT_BINARY_DIR}/../include/SimpleITKBasicFiltersGeneratedHeaders.h - DESTINATION ${SimpleITK_INSTALL_INCLUDE_DIR} - COMPONENT Development ) From 77bf10298fed3dffaddfd30f32e87b3eb0a25db5 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 29 Jun 2016 14:13:50 -0400 Subject: [PATCH 317/412] Remove wrapping projects dependency on SimpleITK binary directory. Just use all the dependencies for the swig targets when in the binary directory. When the wrapping projects are built separately just use one header file. Change-Id: I919b109aad1d3eb23cd403b710f81864815a980d --- CMake/sitkProjectLanguageCommon.cmake | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/CMake/sitkProjectLanguageCommon.cmake b/CMake/sitkProjectLanguageCommon.cmake index 362b2c5fa..bd2471f5f 100644 --- a/CMake/sitkProjectLanguageCommon.cmake +++ b/CMake/sitkProjectLanguageCommon.cmake @@ -8,9 +8,6 @@ if (NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK" ) set( SimpleITK_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../.." ) list(APPEND CMAKE_MODULE_PATH "${SimpleITK_SOURCE_DIR}/CMake") - #HACK - we should not be using anything from this directory - set( SimpleITK_BINARY_DIR ${SimpleITK_DIR} ) - find_package(SimpleITK REQUIRED) include(${SimpleITK_USE_FILE}) @@ -47,16 +44,25 @@ include (sitkUseSWIG) set(SIMPLEITK_WRAPPING_COMMON_DIR ${SimpleITK_SOURCE_DIR}/Wrapping/Common) -file(GLOB SWIG_EXTRA_DEPS - "${SimpleITK_SOURCE_DIR}/Code/Common/include/*.h" - "${SimpleITK_SOURCE_DIR}/Code/Registration/include/*.h" - "${SimpleITK_SOURCE_DIR}/Code/IO/include/*.h") +if ( CMAKE_PROJECT_NAME STREQUAL "SimpleITK" ) + file(GLOB SWIG_EXTRA_DEPS + "${SimpleITK_SOURCE_DIR}/Code/Common/include/*.h" + "${SimpleITK_SOURCE_DIR}/Code/Registration/include/*.h" + "${SimpleITK_SOURCE_DIR}/Code/IO/include/*.h") + list( APPEND SWIG_EXTRA_DEPS + "${SimpleITK_BINARY_DIR}/Code/BasicFilters/include/SimpleITKBasicFiltersGeneratedHeaders.h" + ${SimpleITKBasicFiltersGeneratedHeader} ) +else() + find_file( _file + NAMES SimpleITKBasicFiltersGeneratedHeaders.h + PATHS ${SimpleITK_INCLUDE_DIRS} + NO_DEFAULT_PATH ) + list( APPEND SWIG_EXTRA_DEPS ${_file} ) +endif() # make a manual list of dependencies for the Swig.i files -list( APPEND SWIG_EXTRA_DEPS "${SimpleITK_BINARY_DIR}/Code/BasicFilters/include/SimpleITKBasicFiltersGeneratedHeaders.i" - "${SimpleITK_BINARY_DIR}/Code/BasicFilters/include/SimpleITKBasicFiltersGeneratedHeaders.h" +list( APPEND SWIG_EXTRA_DEPS "${SIMPLEITK_WRAPPING_COMMON_DIR}/SimpleITK_Common.i" - ${SimpleITKBasicFiltersGeneratedHeader} ) # check if uint64_t is the same as unsigned long From afa2ab2fd0b59dfcbb6d4bfec429c1322d2df5e1 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 30 Jun 2016 10:29:40 -0400 Subject: [PATCH 318/412] Corrected installation of headers Change-Id: Ia6afd465c49955e7d8a390c0892ab7dbe7ce5463 --- CMake/sitkGenerateFilterSource.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMake/sitkGenerateFilterSource.cmake b/CMake/sitkGenerateFilterSource.cmake index fef2c395a..099795681 100644 --- a/CMake/sitkGenerateFilterSource.cmake +++ b/CMake/sitkGenerateFilterSource.cmake @@ -232,7 +232,7 @@ macro(generate_filter_source) configure_file( "${tmp_generated_headers_i}" "${generated_headers_i}" COPYONLY ) install(FILES - ${SimpleITK${directory_name}GeneratedSource} + ${SimpleITK${directory_name}GeneratedHeader} ${generated_headers_h} ${generated_headers_i} DESTINATION ${SimpleITK_INSTALL_INCLUDE_DIR} From dfa8ee2ed88a3b4bf6442a45719c8c6e7e2d90a5 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 30 Jun 2016 10:39:30 -0400 Subject: [PATCH 319/412] Address CMP0058 issue with generate CSharp files Change-Id: Ic15f5bccb572072d42fd4e7defea887bce446c59 --- Wrapping/CSharp/CMakeLists.txt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Wrapping/CSharp/CMakeLists.txt b/Wrapping/CSharp/CMakeLists.txt index b2cc7f820..5178f6725 100644 --- a/Wrapping/CSharp/CMakeLists.txt +++ b/Wrapping/CSharp/CMakeLists.txt @@ -74,6 +74,14 @@ endif() endif( UNIX ) sitk_strip_target( ${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} ) + # These CSharp files are generated by SWIG, they are not there + # during the first build. But the charp_add_library will add them as + # a dependency when the exists. This is needed for CMP0058 + file(GLOB _files "${CSHARP_SOURCE_DIRECTORY}/*.cs") + add_custom_command( TARGET ${SWIG_MODULE_SimpleITKCSharpNative_TARGET_NAME} + POST_BUILD + BYPRODUCTS ${_files} ) + # Configure AssemblyInfo.cs configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/AssemblyInfo.cs.in From ab01980191b1eac600263d543a60a28c763635f9 Mon Sep 17 00:00:00 2001 From: Dave Chen Date: Wed, 29 Jun 2016 11:13:47 -0400 Subject: [PATCH 320/412] Build a loadable Lua module Previously we only built a standalone Lua executable. Now we also build a SimpleITK module that can be loaded into any Lua interpreter. This set of patches also changes the Lua tests to use the system Lua executable and load SimpleITK as a module in that executable. Also building the standalone Lua executable is now an option that defaults to OFF. --- CMake/sitkAddTest.cmake | 5 ++++- CMake/sitkLanguageOptions.cmake | 2 ++ .../Unit/LuaImageFilterTestTemplate.lua.in | 2 ++ Wrapping/Lua/CMakeLists.txt | 21 +++++++++++++++---- 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index afad1b809..d5bfeb549 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -83,7 +83,7 @@ function(sitk_add_lua_test name) return() endif() - set(command "$") + set(command "${LUA_EXECUTABLE}") # add extra command which may be needed on some systems if(CMAKE_OSX_ARCHITECTURES) @@ -96,6 +96,9 @@ function(sitk_add_lua_test name) ${command} ${ARGN} ) + set_property(TEST Lua.${name} + PROPERTY ENVIRONMENT LUA_CPATH=$ + ) endfunction() diff --git a/CMake/sitkLanguageOptions.cmake b/CMake/sitkLanguageOptions.cmake index 95c075430..6104798bd 100644 --- a/CMake/sitkLanguageOptions.cmake +++ b/CMake/sitkLanguageOptions.cmake @@ -51,7 +51,9 @@ mark_as_advanced( LUA_ADDITIONAL_LIBRARIES ) option ( WRAP_LUA "Wrap Lua" ${WRAP_LUA_DEFAULT} ) if ( WRAP_LUA ) + find_package( LuaInterp REQUIRED ) list( APPEND SITK_LANGUAGES_VARS + LUA_EXECUTABLE LUA_LIBRARIES LUA_INCLUDE_DIR LUA_VERSION_STRING diff --git a/Testing/Unit/LuaImageFilterTestTemplate.lua.in b/Testing/Unit/LuaImageFilterTestTemplate.lua.in index 430683a19..c1e1b7ad8 100644 --- a/Testing/Unit/LuaImageFilterTestTemplate.lua.in +++ b/Testing/Unit/LuaImageFilterTestTemplate.lua.in @@ -25,6 +25,8 @@ -- This is Lua code to test ${name} +require "SimpleITK" + inputs = 1 $(if number_of_inputs then OUT=[[inputs = ${number_of_inputs}]] diff --git a/Wrapping/Lua/CMakeLists.txt b/Wrapping/Lua/CMakeLists.txt index 93dec564f..c63a6e48f 100644 --- a/Wrapping/Lua/CMakeLists.txt +++ b/Wrapping/Lua/CMakeLists.txt @@ -14,7 +14,7 @@ else() find_package ( Lua ${_QUIET} ) endif() -set( LUA_ADDITIONAL_LIBRARIES "" CACHE STRING "Additional libraries which may be needed for lua such as readline.") +set( LUA_ADDITIONAL_LIBRARIES "" CACHE STRING "Additional libraries which may be needed for lua executable such as readline.") mark_as_advanced( LUA_ADDITIONAL_LIBRARIES ) include_directories ( ${LUA_INCLUDE_DIR} ) @@ -30,6 +30,19 @@ SWIG_module_initialize ( SimpleITKLua lua ) SWIG_add_source_to_module ( SimpleITKLua swig_generated_source SimpleITK.i ${SWIG_EXTRA_DEPS} ) set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w" ) -add_executable ( SimpleITKLua SimpleITKLuaMain.cxx ${swig_generated_file_fullname} ) -target_link_libraries ( SimpleITKLua ${SimpleITK_LIBRARIES} ${LUA_LIBRARIES} ${LUA_ADDITIONAL_LIBRARIES} ) -sitk_strip_target( SimpleITKLua ) +# Create a standalone Lua executable that includes SimpleITK. +option( SITK_LUA_BUILD_EXECUTABLE "Build a standalone SimpleITK-Lua executable" OFF) +if ( SITK_LUA_BUILD_EXECUTABLE ) + add_executable ( SimpleITKLua SimpleITKLuaMain.cxx ${swig_generated_file_fullname} ) + target_link_libraries ( SimpleITKLua ${SimpleITK_LIBRARIES} ${LUA_LIBRARIES} ${LUA_ADDITIONAL_LIBRARIES} ) + sitk_strip_target( SimpleITKLua ) +endif () + +# Create a SimpleITK Lua module that can be loaded into any Lua executable. +SWIG_add_module( SimpleITKLuaModule lua SimpleITK.i ) +target_link_libraries( ${SWIG_MODULE_SimpleITKLuaModule_TARGET_NAME} ${SimpleITK_LIBRARIES} ) +set_target_properties( ${SWIG_MODULE_SimpleITKLuaModule_TARGET_NAME} PROPERTIES PREFIX "" OUTPUT_NAME "SimpleITK" ) +sitk_target_link_libraries_with_dynamic_lookup( ${SWIG_MODULE_SimpleITKLuaModule_TARGET_NAME} ${LUA_LIBRARIES} ) +set_source_files_properties( ${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") +sitk_strip_target( ${SWIG_MODULE_SimpleITKLuaModule_TARGET_NAME} ) + From ec65c05a15be1c7b3b4e64b84128aa03b833c187 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Wed, 29 Jun 2016 14:27:41 -0400 Subject: [PATCH 321/412] Updated Lua examples to load SimpleITK module Added the 'require "SimpleITK"' statement to load the SimpleITK module. Previously the examples ran with the standalone SimpleITK Lua executable which did not need to load SimpleITK. Change-Id: Icc0e7dfb9c2f21c4d2cf64c22d6426829614d961 --- Examples/Lua/DicomSeriesReader.lua | 1 + Examples/Lua/ImageRegistrationMethod1.lua | 1 + Examples/Lua/SimpleDerivative.lua | 2 ++ Examples/Lua/SimpleGaussian.lua | 3 ++- 4 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Examples/Lua/DicomSeriesReader.lua b/Examples/Lua/DicomSeriesReader.lua index ad1873838..bbe14ac35 100644 --- a/Examples/Lua/DicomSeriesReader.lua +++ b/Examples/Lua/DicomSeriesReader.lua @@ -16,6 +16,7 @@ -- --========================================================================= +require "SimpleITK" if #arg < 2 then print ( "Usage: DicomSeriesReader " ) diff --git a/Examples/Lua/ImageRegistrationMethod1.lua b/Examples/Lua/ImageRegistrationMethod1.lua index 9a807387f..bc5d7989e 100644 --- a/Examples/Lua/ImageRegistrationMethod1.lua +++ b/Examples/Lua/ImageRegistrationMethod1.lua @@ -16,6 +16,7 @@ -- --========================================================================= +require "SimpleITK" function command_iteration(method) print(method) diff --git a/Examples/Lua/SimpleDerivative.lua b/Examples/Lua/SimpleDerivative.lua index 669d87bc2..0a938b9c8 100644 --- a/Examples/Lua/SimpleDerivative.lua +++ b/Examples/Lua/SimpleDerivative.lua @@ -17,6 +17,8 @@ -- --========================================================================= +require "SimpleITK" + local sitk = {} sitk = SimpleITK diff --git a/Examples/Lua/SimpleGaussian.lua b/Examples/Lua/SimpleGaussian.lua index 8b74efbd5..14fddff1c 100644 --- a/Examples/Lua/SimpleGaussian.lua +++ b/Examples/Lua/SimpleGaussian.lua @@ -16,6 +16,7 @@ -- --========================================================================= +require "SimpleITK" if #arg < 3 then print ( "Usage: SimpleGaussian " ) @@ -26,7 +27,7 @@ reader = SimpleITK.ImageFileReader() -- Remember that Lua arrays are 1-based, and that arg does not contain the application name! reader:SetFileName ( arg[1] ) image = reader:Execute(); - + inputPixelType = image:GetPixelIDValue() gaussian = SimpleITK.SmoothingRecursiveGaussianImageFilter() From 46d821676a3ca1d54eb16fe3abbfe982ccdb9dee Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Wed, 29 Jun 2016 15:39:07 -0400 Subject: [PATCH 322/412] Save LUA_EXECUTABLE cmake variable When searching for a Lua executable to run the SimpleITK code generation with, we need to save and restore the LUA_EXECUTABLE variable to keep it from getting clobbered. Change-Id: I0133b5867322b415aacb7a8c1b56c8f1897d4b07 --- CMake/sitkGenerateFilterSource.cmake | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/CMake/sitkGenerateFilterSource.cmake b/CMake/sitkGenerateFilterSource.cmake index edf2510ee..64f892d57 100644 --- a/CMake/sitkGenerateFilterSource.cmake +++ b/CMake/sitkGenerateFilterSource.cmake @@ -1,10 +1,21 @@ +# Find a Lua executable +# if ( NOT SITK_LUA_EXECUTABLE ) + set ( SAVE_LUA_EXECUTABLE ${LUA_EXECUTABLE} ) + find_package( LuaInterp REQUIRED 5.1 ) set( SITK_LUA_EXECUTABLE ${LUA_EXECUTABLE} CACHE PATH "Lua executable used for code generation." ) - unset( LUA_EXECUTABLE CACHE ) + + if (defined SAVE_LUA_EXECUTABLE) + set( LUA_EXECUTABLE ${SAVE_LUA_EXECUTABLE} CACHE ) + else() + unset( LUA_EXECUTABLE CACHE ) + endif() endif() +# Get the Lua version +# execute_process( COMMAND ${SITK_LUA_EXECUTABLE} -v OUTPUT_VARIABLE @@ -17,6 +28,8 @@ execute_process( ERROR_STRIP_TRAILING_WHITESPACE ) +# Check that the Lua version is acceptable +# if( NOT SITK_LUA_VERSION_RESULT_VARIABLE ) string( REGEX MATCH "([0-9]*)([.])([0-9]*)([.]*)([0-9]*)" SITK_LUA_EXECUTABLE_VERSION From a13e4eb0c8daccf16f3887e4091b5a43f5b92167 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 30 Jun 2016 12:07:35 -0400 Subject: [PATCH 323/412] Updating ITK superbuild version along 4.10 release ITK now sets CMP0063 to new to for setting of visibility. Change-Id: I26f9289698764da978f680381503783afeb9f66e --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index ee1217318..22f7c58de 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -40,7 +40,7 @@ if("${git_protocol}" STREQUAL "git") endif() # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG 1bf7263085f1d700518bf968248647a1ccb971df ) # just after 4.10.0 release +set(ITK_TAG_COMMAND GIT_TAG 8565bd9b4bc4446b05554e11ccb27bda1d6db647 ) # just after 4.10.0 release if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From f497700fdc75c034c953fc5ab5e7c2f3c66395d7 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 30 Jun 2016 15:50:14 -0400 Subject: [PATCH 324/412] Prepend SimpleITK CMake module directory to search path This will allow SimpleITK to override the CMake modules Change-Id: Ida4b5f7112f9d9eba9b447ba2134390c305253a2 --- CMake/sitkProjectLanguageCommon.cmake | 2 +- CMakeLists.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CMake/sitkProjectLanguageCommon.cmake b/CMake/sitkProjectLanguageCommon.cmake index bd2471f5f..713859ab7 100644 --- a/CMake/sitkProjectLanguageCommon.cmake +++ b/CMake/sitkProjectLanguageCommon.cmake @@ -6,7 +6,7 @@ if (NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK" ) set( SimpleITK_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../.." ) - list(APPEND CMAKE_MODULE_PATH "${SimpleITK_SOURCE_DIR}/CMake") + list(INSERT CMAKE_MODULE_PATH 0 "${CMAKE_CURRENT_SOURCE_DIR}/CMake") find_package(SimpleITK REQUIRED) include(${SimpleITK_USE_FILE}) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0d8d35524..cedc4155c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,7 +13,7 @@ cmake_policy( VERSION 3.0 ) set( CMAKE_MACOSX_RPATH 1) # Include extra CMake files -list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/CMake") +list(INSERT CMAKE_MODULE_PATH 0 "${CMAKE_CURRENT_SOURCE_DIR}/CMake") #----------------------------------------------------------------------------- # Version information From 5b5748be98c11ab08fda749fdb7d136b228731e8 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 30 Jun 2016 15:51:38 -0400 Subject: [PATCH 325/412] Only set POSITION_INDEPENDENT_CODE flag if not already set This will allow the user to override this default behavior. Change-Id: I8858258d2bb444ba3092366d2d5c8e95ccfb8a12 --- CMakeLists.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index cedc4155c..94fad0679 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -213,14 +213,14 @@ include(sitkStripOption) #------------------------------------------------------------------------------ # These are some system specific compiler options needed to build SimpleITK +include(CheckCXXCompilerFlag) +if( NOT DEFINED CMAKE_POSITION_INDEPENDENT_CODE ) + set( CMAKE_POSITION_INDEPENDENT_CODE 1 ) +endif() -include(CheckCXXCompilerFlag) -# always create position independent code so that the libraries can be -# used with shared libraries needed for language bindings. -set( CMAKE_POSITION_INDEPENDENT_CODE 1 ) #----------------------------------------------------------- # Place all checks and try compile variable for sitkConfigure.h here From 17735d7c1007d3611c3c55f40736c5b7e00f1a86 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 30 Jun 2016 15:52:23 -0400 Subject: [PATCH 326/412] Remove unused cmake macro Change-Id: Ibd5ac3ec568e4e072896ce8e5773d27e265c21b7 --- SuperBuild/SuperBuild.cmake | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 4ea2f4170..6893e0b94 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -156,16 +156,6 @@ endif() #------------------------------------------------------------------------------ # Setup build locations. #------------------------------------------------------------------------------ -if(NOT SETIFEMPTY) - macro(SETIFEMPTY) # A macro to set empty variables to meaninful defaults - set(KEY ${ARGV0}) - set(VALUE ${ARGV1}) - if(NOT ${KEY}) - set(${ARGV}) - endif(NOT ${KEY}) - endmacro(SETIFEMPTY KEY VALUE) -endif(NOT SETIFEMPTY) - #------------------------------------------------------------------------------ # Common Build Options to pass to all subsequent tools From 0bdfd838f7389cd5d655395aa3a00ade28f5f7a9 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 30 Jun 2016 15:57:32 -0400 Subject: [PATCH 327/412] Remove SKIP_BUILD_RPATH property for SimpleITK libraries. This property was not having the intended effect on produced language libraries. Change-Id: I602926b6685be69a477a03eba6db4eaf950184cf --- Code/BasicFilters/src/CMakeLists.txt | 3 --- Code/Common/src/CMakeLists.txt | 2 -- Code/Explicit/src/CMakeLists.txt | 2 -- Code/IO/src/CMakeLists.txt | 2 -- Code/Registration/src/CMakeLists.txt | 2 -- 5 files changed, 11 deletions(-) diff --git a/Code/BasicFilters/src/CMakeLists.txt b/Code/BasicFilters/src/CMakeLists.txt index dbc55f881..6e9aa94c3 100644 --- a/Code/BasicFilters/src/CMakeLists.txt +++ b/Code/BasicFilters/src/CMakeLists.txt @@ -20,7 +20,6 @@ add_library ( SimpleITKBasicFilters0 ${SimpleITKBasicFilters0Source} ) target_link_libraries ( SimpleITKBasicFilters0 PUBLIC SimpleITKCommon PRIVATE ${ITK_LIBRARIES} ) -set_target_properties( SimpleITKBasicFilters0 PROPERTIES SKIP_BUILD_RPATH TRUE ) sitk_install_exported_target( SimpleITKBasicFilters0 ) # append this new library to the globally cached list @@ -53,7 +52,6 @@ add_library ( SimpleITKBasicFilters1 ${SimpleITKBasicFilters1Source} ) target_link_libraries ( SimpleITKBasicFilters1 PUBLIC SimpleITKCommon SimpleITKBasicFilters0 PRIVATE ${ITK_LIBRARIES} ) -set_target_properties( SimpleITKBasicFilters1 PROPERTIES SKIP_BUILD_RPATH TRUE ) add_dependencies ( SimpleITKBasicFilters1 BasicFiltersSourceCode ) sitk_install_exported_target( SimpleITKBasicFilters1 ) list ( APPEND SimpleITK_LIBRARIES SimpleITKBasicFilters1 ) @@ -114,7 +112,6 @@ foreach ( _start RANGE 0 ${_end_range} ${_stride} ) target_link_libraries ( SimpleITKBasicFilters${_library_i} PRIVATE ${SimpleITK_LIBRARIES} ) endif() - set_target_properties( SimpleITKBasicFilters${_library_i} PROPERTIES SKIP_BUILD_RPATH TRUE ) add_dependencies ( SimpleITKBasicFilters${_library_i} BasicFiltersSourceCode ) # append this new library to the globaly cached list diff --git a/Code/Common/src/CMakeLists.txt b/Code/Common/src/CMakeLists.txt index ed119fee1..d1602073f 100644 --- a/Code/Common/src/CMakeLists.txt +++ b/Code/Common/src/CMakeLists.txt @@ -39,8 +39,6 @@ target_link_libraries ( SimpleITKCommon if (SITK_EXPLICIT_INSTANTIATION) target_link_libraries ( SimpleITKCommon PRIVATE SimpleITKExplicit ) endif() -set_target_properties( SimpleITKCommon PROPERTIES SKIP_BUILD_RPATH TRUE ) - sitk_install_exported_target( SimpleITKCommon ) # Add custom command that will delete java files which need to be rebuilt when changes diff --git a/Code/Explicit/src/CMakeLists.txt b/Code/Explicit/src/CMakeLists.txt index 93f17c8ba..ab9417b49 100644 --- a/Code/Explicit/src/CMakeLists.txt +++ b/Code/Explicit/src/CMakeLists.txt @@ -30,8 +30,6 @@ include(${ITK_USE_FILE}) if ( MSVC AND SITK_BUILD_SHARED_LIBS ) set( SimpleITKExplicit_FORCE_LIBRARY_TYPE "STATIC" ) endif() - add_library ( SimpleITKExplicit ${SimpleITKExplicit_FORCE_LIBRARY_TYPE} ${SimpleITKExplicitSource} ) target_link_libraries ( SimpleITKExplicit PUBLIC ${ITK_LIBRARIES} ) -set_target_properties( SimpleITKExplicit PROPERTIES SKIP_BUILD_RPATH TRUE ) sitk_install_exported_target( SimpleITKExplicit ) diff --git a/Code/IO/src/CMakeLists.txt b/Code/IO/src/CMakeLists.txt index 038872027..e4f018d26 100644 --- a/Code/IO/src/CMakeLists.txt +++ b/Code/IO/src/CMakeLists.txt @@ -26,8 +26,6 @@ add_library ( SimpleITKIO ${SimpleITKIOSource} ) target_link_libraries ( SimpleITKIO PUBLIC SimpleITKCommon PRIVATE ${ITK_LIBRARIES} ) -set_target_properties( SimpleITKIO PROPERTIES SKIP_BUILD_RPATH TRUE ) - sitk_install_exported_target( SimpleITKIO ) # Add custom command that will delete java files which need to be rebuilt when changes diff --git a/Code/Registration/src/CMakeLists.txt b/Code/Registration/src/CMakeLists.txt index c80142d24..3d49c3307 100644 --- a/Code/Registration/src/CMakeLists.txt +++ b/Code/Registration/src/CMakeLists.txt @@ -16,6 +16,4 @@ include(${ITK_USE_FILE}) add_library ( SimpleITKRegistration ${SimpleITKRegistration} ) # The BasicFiltersLibrary is needed of the Cast filter target_link_libraries ( SimpleITKRegistration ${ITK_LIBRARIES} SimpleITKCommon SimpleITKBasicFilters1 ) -set_target_properties( SimpleITKRegistration PROPERTIES SKIP_BUILD_RPATH TRUE ) - sitk_install_exported_target( SimpleITKRegistration ) From ad245bd17c5cdadd4d98ad9e354414fa2f605c9a Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 30 Jun 2016 16:17:23 -0400 Subject: [PATCH 328/412] Disable build RPATHs for wrapped languages. Previously, the RPATHs for the build directory were still being encoded in the distributed language packages. The disabling of the build rpath needs to occur on this final shared library, and not on the dependent SimpleITK libraries. Change-Id: I5be7aea2dc60410e82ddc81a34557ade53578c45 --- CMake/sitkProjectLanguageCommon.cmake | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CMake/sitkProjectLanguageCommon.cmake b/CMake/sitkProjectLanguageCommon.cmake index 255cc0ac7..6d74528ca 100644 --- a/CMake/sitkProjectLanguageCommon.cmake +++ b/CMake/sitkProjectLanguageCommon.cmake @@ -35,6 +35,13 @@ if(NOT CMAKE_ARCHIVE_OUTPUT_DIRECTORY OR CMAKE_PROJECT_NAME STREQUAL "SimpleITK" set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/lib) endif() + +# Since most language libraries are not installed with CMake, the +# RPATH does not get fixed up during installation. So skip the RPATH +if(NOT DEFINED CMAKE_SKIP_BUILD_RPATH) + set(CMAKE_SKIP_BUILD_RPATH 1) +endif() + if(NOT TARGET dist) add_custom_target( dist cmake -E echo "Finished generating wrapped packages for distribution..." ) endif() From e6cd33509450bdc34ff57364625c5507cf41ab08 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 30 Jun 2016 16:21:56 -0400 Subject: [PATCH 329/412] Remove visibility flags in superbuild for CMAKE property defaults Change-Id: I3171a47409af55fb1d43a951ff7d4b39e0cf6819 --- SuperBuild/External_ITK.cmake | 1 + SuperBuild/SuperBuild.cmake | 8 -------- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 53eb66216..e1b677710 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -64,6 +64,7 @@ ExternalProject_Add(${proj} ${ep_itk_args} ${ep_common_args} -DCMAKE_POSITION_INDEPENDENT_CODE:BOOL=ON + -DCMAKE_VISIBILITY_INLINES_HIDDEN:BOOL=ON -DBUILD_EXAMPLES:BOOL=OFF -DBUILD_TESTING:BOOL=OFF -DBUILD_SHARED_LIBS:BOOL=${ITK_BUILD_SHARED_LIBS} diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 02be02d43..afd92a0c9 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -126,14 +126,6 @@ endif() include(sitkCheckRequiredFlags) set ( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SimpleITK_REQUIRED_CXX_FLAGS}" ) -# the hidden visibility for inline methods should be consistent between ITK and SimpleITK -if(NOT WIN32 AND CMAKE_COMPILER_IS_GNUCXX AND BUILD_SHARED_LIBS) - check_cxx_compiler_flag("-fvisibility-inlines-hidden" CXX_HAS-fvisibility-inlines-hidden) - if( CXX_HAS-fvisibility-inlines-hidden ) - set ( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility-inlines-hidden" ) - endif() -endif() - #------------------------------------------------------------------------------ # BuildName used for dashboard reporting #------------------------------------------------------------------------------ From e35fef8c39d098328811f90b51b55e88b35d4169 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 30 Jun 2016 16:24:55 -0400 Subject: [PATCH 330/412] Always build ITK with hidden visibility with static libraries Change-Id: If66e47135ff7f4c3e19bc3b11d3b24d16f7c79b7 --- SuperBuild/External_ITK.cmake | 1 + 1 file changed, 1 insertion(+) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index e1b677710..fccb91bfc 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -46,6 +46,7 @@ if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) else() set( ITK_BUILD_SHARED_LIBS OFF ) + list( APPEND ep_itk_args"-DCMAKE_C_VISIBILITY_PRESET:BOOL=hidden" "-DCMAKE_CXX_VISIBILITY_PRESET:BOOL=hidden" ) endif() From e4753668eba93f815cf88047ba1122c52df7e97e Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 1 Jul 2016 14:25:49 -0400 Subject: [PATCH 331/412] Enable CMP0042 and CMP0063 to New Change-Id: I1a1a48989869a5c75d56090b30ea7f6e7e05c8e4 --- CMake/sitkProjectLanguageCommon.cmake | 10 ++++++++++ CMakeLists.txt | 11 ++++++++--- Examples/CMakeLists.txt | 9 +++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/CMake/sitkProjectLanguageCommon.cmake b/CMake/sitkProjectLanguageCommon.cmake index 6d74528ca..965629e99 100644 --- a/CMake/sitkProjectLanguageCommon.cmake +++ b/CMake/sitkProjectLanguageCommon.cmake @@ -1,4 +1,14 @@ +foreach(p + CMP0042 # CMake 3.0 + CMP0063 # CMake 3.3.2 + ) + if(POLICY ${p}) + cmake_policy(SET ${p} NEW) + endif() +endforeach() + + # # Project setup # diff --git a/CMakeLists.txt b/CMakeLists.txt index 6227226c0..a83cc86e7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,9 +8,14 @@ project ( SimpleITK ) cmake_policy( VERSION 2.8.1 ) - -# NEW CMP0042 -set( CMAKE_MACOSX_RPATH 1) +foreach(p + CMP0042 # CMake 3.0 + CMP0063 # CMake 3.3.2 + ) + if(POLICY ${p}) + cmake_policy(SET ${p} NEW) + endif() +endforeach() # Include extra CMake files list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/CMake") diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index 25838ba40..f649afcf7 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -1,6 +1,15 @@ cmake_minimum_required(VERSION 2.8) project(SimpleITKExamples) +foreach(p + CMP0042 # CMake 3.0 + CMP0063 # CMake 3.3.2 + ) + if(POLICY ${p}) + cmake_policy(SET ${p} NEW) + endif() +endforeach() + if(NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK") find_package(SimpleITK REQUIRED) include(${SimpleITK_USE_FILE}) From a99085060c73346f15b54b916f56ece9a9501801 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 1 Jul 2016 14:26:29 -0400 Subject: [PATCH 332/412] Remove Segmentation examples as separate project Change-Id: Id9c6f07ef3346cc32f6a83ae881f75574dcdd2fd --- Examples/Segmentation/CMakeLists.txt | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Examples/Segmentation/CMakeLists.txt b/Examples/Segmentation/CMakeLists.txt index c6daba3a1..018599c61 100644 --- a/Examples/Segmentation/CMakeLists.txt +++ b/Examples/Segmentation/CMakeLists.txt @@ -1,10 +1,3 @@ -cmake_minimum_required(VERSION 2.8) -project(SimpleITKSegmentationExamples) - -if(NOT SimpleITK_SOURCE_DIR) - find_package(SimpleITK REQUIRED) - include(${SimpleITK_USE_FILE}) -endif() # Add executable example targets add_executable ( ConnectedThresholdImageFilter ConnectedThresholdImageFilter.cxx ) From 0d37820d55f592f0bfd42608c03b4926bcd706da Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 1 Jul 2016 16:13:53 -0400 Subject: [PATCH 333/412] Don't use per-configuration output directory for Python library. This is needed because the python packaging script is currently not supporting generator expressions. We can't have different paths for Release and Debug builds. Change-Id: Idf14901ceb6935e2335da9a0d02cbc3b176a70f1 --- Wrapping/Python/CMakeLists.txt | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index e35b9584b..c3533ce07 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -51,6 +51,15 @@ set(SWIG_MODULE_SimpleITKPython_TARGET_NAME "${SWIG_MODULE_SimpleITK_TARGET_NAME target_link_libraries( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ${SimpleITK_LIBRARIES} ) sitk_target_link_libraries_with_dynamic_lookup( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ${PYTHON_LIBRARIES} ) set_target_properties( ${SWIG_MODULE_SimpleITK_TARGET_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) +if ( MSVC ) + foreach ( CMAKE_CONFIGURATION_TYPE ${CMAKE_CONFIGURATION_TYPES} ) + string(TOUPPER ${CMAKE_CONFIGURATION_TYPE} CMAKE_CONFIGURATION_TYPE) + set_target_properties(${SWIG_MODULE_SimpleITK_TARGET_NAME} + PROPERTIES LIBRARY_OUTPUT_DIRECTORY_${CMAKE_CONFIGURATION_TYPE} "${CMAKE_CURRENT_BINARY_DIR}") + set_target_properties(${SWIG_MODULE_SimpleITK_TARGET_NAME} + PROPERTIES RUNTIME_OUTPUT_DIRECTORY_${CMAKE_CONFIGURATION_TYPE} "${CMAKE_CURRENT_BINARY_DIR}") + endforeach( ) +endif() set_source_files_properties(${swig_generated_file_fullname} PROPERTIES COMPILE_FLAGS "-w") sitk_strip_target( ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} ) From afc50ede8b5a2cbd9d8020a09200dcb05b2e57c4 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 5 Jul 2016 11:50:47 -0400 Subject: [PATCH 334/412] Move DataFinder implementation to cxx file. Due to it's usage of ITK's kwsys it presented a dependency problem. --- Testing/Unit/SimpleITKTestHarness.cxx | 82 +++++++++++++++++++++++++++ Testing/Unit/SimpleITKTestHarness.h | 63 ++++---------------- 2 files changed, 94 insertions(+), 51 deletions(-) diff --git a/Testing/Unit/SimpleITKTestHarness.cxx b/Testing/Unit/SimpleITKTestHarness.cxx index f56e5d61a..bc4adadac 100644 --- a/Testing/Unit/SimpleITKTestHarness.cxx +++ b/Testing/Unit/SimpleITKTestHarness.cxx @@ -1,6 +1,88 @@ #include "SimpleITKTestHarness.h" +#include +#include + + +DataFinder::DataFinder() : + mDirectory(TEST_HARNESS_DATA_DIRECTORY), + mOutputDirectory(TEST_HARNESS_TEMP_DIRECTORY) +{ +} + +void DataFinder::SetDirectory ( const char* dir ) +{ + mDirectory = dir; +} + + +void DataFinder::SetDirectory ( std::string dir ) +{ + mDirectory = dir; +} + + +void DataFinder::SetOutputDirectory ( std::string dir ) +{ + mOutputDirectory = dir; +} + + + +std::string DataFinder::GetDirectory () const +{ + return mDirectory; +} + +std::string DataFinder::GetOutputDirectory () const +{ + return mOutputDirectory; +} + +std::string DataFinder::GetOutputFile ( std::string filename ) const +{ + return mOutputDirectory + "/" + filename; +} + +std::string DataFinder::GetBuildDirectory () const +{ + return std::string ( SIMPLEITK_BINARY_DIR ); +} + +std::string DataFinder::GetPathSeparator () const +{ +#ifdef WIN32 + return ";"; +#else + return ":"; +#endif +} + +bool DataFinder::FileExists ( const std::string &filename ) const +{ + return itksys::SystemTools::FileExists ( filename.c_str() ); +} + +std::string DataFinder::GetFile ( const std::string &filename ) const +{ + std::string name; + + name = mDirectory + "/" + filename; + if (this->FileExists(name)) + return name; + + // fall back to source code path + name = std::string(SIMPLEITK_SOURCE_DIR) + "/Testing/Data/" + filename; + + return name; +} + + +// +// +// + ProcessObjectCommand::ProcessObjectCommand(itk::simple::ProcessObject &po) : m_Process(po) diff --git a/Testing/Unit/SimpleITKTestHarness.h b/Testing/Unit/SimpleITKTestHarness.h index d994df205..c93d0c99c 100644 --- a/Testing/Unit/SimpleITKTestHarness.h +++ b/Testing/Unit/SimpleITKTestHarness.h @@ -42,8 +42,6 @@ inline std::ostream& operator<< (std::ostream& os, const std::vector& v) #include #include #include -#include -#include #include "sitkImage.h" #include "sitkImageFileReader.h" @@ -68,61 +66,24 @@ class DataFinder { public: - DataFinder () - { - mDirectory = TEST_HARNESS_DATA_DIRECTORY; - mOutputDirectory = TEST_HARNESS_TEMP_DIRECTORY; - }; - - void SetDirectory ( const char* dir ) - { - mDirectory = dir; - }; - - void SetDirectory ( std::string dir ) - { - mDirectory = dir; - }; - - - void SetOutputDirectory ( std::string dir ) - { - mOutputDirectory = dir; - }; - - std::string GetDirectory () const { return mDirectory; }; - std::string GetOutputDirectory () const { return mOutputDirectory; }; - std::string GetOutputFile ( std::string filename ) - const { return mOutputDirectory + "/" + filename; }; - std::string GetBuildDirectory () const { return std::string ( SIMPLEITK_BINARY_DIR ); } - std::string GetPathSeparator () - { -#ifdef WIN32 - return ";"; -#else - return ":"; -#endif - } + DataFinder (); + + void SetDirectory ( const char* dir ); + void SetDirectory ( std::string dir ); - bool FileExists ( const std::string &filename ) - { - return itksys::SystemTools::FileExists ( filename.c_str() ); - } + void SetOutputDirectory ( std::string dir ); - std::string GetFile ( const std::string &filename ) - { - std::string name; + std::string GetDirectory () const; + std::string GetOutputDirectory () const; + std::string GetOutputFile ( std::string filename ) const; + std::string GetBuildDirectory () const; + std::string GetPathSeparator () const; - name = mDirectory + "/" + filename; - if (this->FileExists(name)) - return name; - // fall back to source code path - name = std::string(SIMPLEITK_SOURCE_DIR) + "/Testing/Data/" + filename; + bool FileExists ( const std::string &filename ) const; - return name; - }; + std::string GetFile ( const std::string &filename ) const; protected: std::string mDirectory; From b9ad6ea684f7f1ead82c72230a01d89e84e131ca Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 5 Jul 2016 11:51:43 -0400 Subject: [PATCH 335/412] Added missing library dependencies in Testing. --- Testing/Unit/CMakeLists.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index 64dedaa8e..431a65b74 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -10,8 +10,8 @@ set ( SimpleITKUnitTestSourceBase sitkTransformCompare.cxx ) add_library ( SimpleITKUnitTestBase STATIC ${SimpleITKUnitTestSourceBase} ) -add_dependencies( SimpleITKUnitTestBase BasicFiltersSourceCode ) -target_link_libraries( SimpleITKUnitTestBase ${GTEST_LIBRARIES} ${SimpleITK_LIBRARIES} ) +add_dependencies( SimpleITKUnitTestBase BasicFiltersSourceCode ) +target_link_libraries( SimpleITKUnitTestBase ${GTEST_LIBRARIES} ${SimpleITK_LIBRARIES} ${ITK_LIBRARIES} ) add_executable( sitkTransformCompareDriver sitkTransformCompareDriver.cxx ) target_link_libraries( sitkTransformCompareDriver ${GTEST_LIBRARIES} SimpleITKUnitTestBase ${SimpleITK_LIBRARIES} ) @@ -248,10 +248,10 @@ if(MSVC_VERSION EQUAL 1700) endif() add_executable(sitkShowTest sitkShowTest.cxx ) -target_link_libraries ( sitkShowTest ${SimpleITK_LIBRARIES} ) +target_link_libraries ( sitkShowTest ${SimpleITK_LIBRARIES} SimpleITKUnitTestBase ) add_executable( sitkSystemInformationTest sitkSystemInformationTest.cxx ) -target_link_libraries( sitkSystemInformationTest ${SimpleITK_LIBRARIES} ) +target_link_libraries( sitkSystemInformationTest ${SimpleITK_LIBRARIES} ${ITK_LIBRARIES}) add_test( NAME sitkSystemInformaionTest COMMAND sitkSystemInformationTest ${CMAKE_BINARY_DIR} ) From d635451c31daabff14a5469ce582e96c2d06462c Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 5 Jul 2016 11:52:28 -0400 Subject: [PATCH 336/412] Adding missing library linkage to SimpleITKExplicit --- Code/BasicFilters/src/CMakeLists.txt | 10 ++++++++++ Code/IO/src/CMakeLists.txt | 4 ++++ Code/Registration/src/CMakeLists.txt | 8 +++++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Code/BasicFilters/src/CMakeLists.txt b/Code/BasicFilters/src/CMakeLists.txt index c236ee51e..c60575d88 100644 --- a/Code/BasicFilters/src/CMakeLists.txt +++ b/Code/BasicFilters/src/CMakeLists.txt @@ -20,6 +20,10 @@ add_library ( SimpleITKBasicFilters0 ${SimpleITKBasicFilters0Source} ) target_link_libraries ( SimpleITKBasicFilters0 PUBLIC SimpleITKCommon PRIVATE ${ITK_LIBRARIES} ) +if (SITK_EXPLICIT_INSTANTIATION) + target_link_libraries ( SimpleITKBasicFilters0 PRIVATE SimpleITKExplicit ) +endif() + sitk_install_exported_target( SimpleITKBasicFilters0 ) # append this new library to the globally cached list @@ -52,6 +56,9 @@ add_library ( SimpleITKBasicFilters1 ${SimpleITKBasicFilters1Source} ) target_link_libraries ( SimpleITKBasicFilters1 PUBLIC SimpleITKCommon SimpleITKBasicFilters0 PRIVATE ${ITK_LIBRARIES} ) +if (SITK_EXPLICIT_INSTANTIATION) + target_link_libraries ( SimpleITKBasicFilters1 PRIVATE SimpleITKExplicit ) +endif() add_dependencies ( SimpleITKBasicFilters1 BasicFiltersSourceCode ) sitk_install_exported_target( SimpleITKBasicFilters1 ) list ( APPEND SimpleITK_LIBRARIES SimpleITKBasicFilters1 ) @@ -106,6 +113,9 @@ foreach ( _start RANGE 0 ${_end_range} ${_stride} ) target_link_libraries ( SimpleITKBasicFilters${_library_i} PUBLIC SimpleITKCommon SimpleITKBasicFilters0 PRIVATE ${ITK_LIBRARIES} ) + if (SITK_EXPLICIT_INSTANTIATION) + target_link_libraries ( SimpleITKBasicFilters${_library_i} PRIVATE SimpleITKExplicit ) + endif() if(_last) # the last library include additional cxx files which may depend on # other filter libraries diff --git a/Code/IO/src/CMakeLists.txt b/Code/IO/src/CMakeLists.txt index e4f018d26..afe2f0a98 100644 --- a/Code/IO/src/CMakeLists.txt +++ b/Code/IO/src/CMakeLists.txt @@ -26,6 +26,10 @@ add_library ( SimpleITKIO ${SimpleITKIOSource} ) target_link_libraries ( SimpleITKIO PUBLIC SimpleITKCommon PRIVATE ${ITK_LIBRARIES} ) +if (SITK_EXPLICIT_INSTANTIATION) + target_link_libraries ( SimpleITKIO PRIVATE SimpleITKExplicit ) +endif() + sitk_install_exported_target( SimpleITKIO ) # Add custom command that will delete java files which need to be rebuilt when changes diff --git a/Code/Registration/src/CMakeLists.txt b/Code/Registration/src/CMakeLists.txt index 3d49c3307..7672f93a0 100644 --- a/Code/Registration/src/CMakeLists.txt +++ b/Code/Registration/src/CMakeLists.txt @@ -15,5 +15,11 @@ include(${ITK_USE_FILE}) add_library ( SimpleITKRegistration ${SimpleITKRegistration} ) # The BasicFiltersLibrary is needed of the Cast filter -target_link_libraries ( SimpleITKRegistration ${ITK_LIBRARIES} SimpleITKCommon SimpleITKBasicFilters1 ) +target_link_libraries ( SimpleITKRegistration + PUBLIC SimpleITKCommon SimpleITKBasicFilters1 + PRIVATE ${ITK_LIBRARIES} ) +if (SITK_EXPLICIT_INSTANTIATION) + target_link_libraries ( SimpleITKRegistration PRIVATE SimpleITKExplicit ) +endif() + sitk_install_exported_target( SimpleITKRegistration ) From 0f9a0b09cd5bca53d07bbbb701bb95ca6ac911b1 Mon Sep 17 00:00:00 2001 From: Dave Chen Date: Tue, 5 Jul 2016 11:55:59 -0400 Subject: [PATCH 337/412] Added return values for sitkShowTest If any of the calls to sitk.Show throw an exception, the main function returns a 1. If they all execute without problem, a 0 is returned. Change-Id: If9e4696907dc5e2ed04b1e4551609cf47f7c05c1 --- Testing/Unit/sitkShowTest.cxx | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Testing/Unit/sitkShowTest.cxx b/Testing/Unit/sitkShowTest.cxx index 13922137d..97276c8e3 100644 --- a/Testing/Unit/sitkShowTest.cxx +++ b/Testing/Unit/sitkShowTest.cxx @@ -16,6 +16,7 @@ * *=========================================================================*/ +#include #include #include @@ -45,10 +46,12 @@ int main (int argc, char *argv[]) catch (std::exception &e) { std::cout << "Exception: " << e.what() << std::endl; + return EXIT_FAILURE; } catch (...) { std::cout << "Default exception\n"; + return EXIT_FAILURE; } } } @@ -65,10 +68,12 @@ int main (int argc, char *argv[]) catch (std::exception &e) { std::cout << "Exception: " << e.what() << std::endl; + return EXIT_FAILURE; } catch (...) { std::cout << "Default exception\n"; + return EXIT_FAILURE; } @@ -82,10 +87,12 @@ int main (int argc, char *argv[]) catch (std::exception &e) { std::cout << "Exception: " << e.what() << std::endl; + return EXIT_FAILURE; } catch (...) { std::cout << "Default exception\n"; + return EXIT_FAILURE; } try @@ -98,10 +105,14 @@ int main (int argc, char *argv[]) catch (std::exception &e) { std::cout << "Exception: " << e.what() << std::endl; + return EXIT_FAILURE; } catch (...) { std::cout << "Default exception\n"; + return EXIT_FAILURE; } } + + return EXIT_SUCCESS; } From d15b14e3f0c55dca24628884e7258a2cd53efb82 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Tue, 5 Jul 2016 16:18:21 -0400 Subject: [PATCH 338/412] Default the visibility of SimpleITK libraries to hidden The SimpleITK libraries have explicit visibility settings for the interface. This works for both shared and static libraries. By enabling the CMake property be default the number of symbols are greatly reduced resulting in smaller binaries and more efficient loading of SimpleITK. This default value can be overridden by the users by setting CMAKE_CXX_VISIBILITY_PRESET. Change-Id: I2651ca2f4d4756e7c45a4062ae07dd1b16916bac --- CMakeLists.txt | 11 +++++++++++ Code/Explicit/src/CMakeLists.txt | 3 +++ 2 files changed, 14 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index a83cc86e7..d0d06ed54 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -231,6 +231,17 @@ include(sitkStripOption) include(CheckCXXCompilerFlag) +if( NOT DEFINED CMAKE_C_VISIBILITY_PRESET ) + set(CMAKE_C_VISIBILITY_PRESET hidden) +endif() + +if( NOT DEFINED CMAKE_CXX_VISIBILITY_PRESET ) + set(CMAKE_CXX_VISIBILITY_PRESET hidden) +endif() + +if( NOT DEFINED CMAKE_VISIBILITY_INLINES_HIDDEN ) + set( CMAKE_VISIBILITY_INLINES_HIDDEN 1 ) +endif() # always create position independent code so that the libraries can be # used with shared libraries needed for language bindings. diff --git a/Code/Explicit/src/CMakeLists.txt b/Code/Explicit/src/CMakeLists.txt index ab9417b49..1b7cc1186 100644 --- a/Code/Explicit/src/CMakeLists.txt +++ b/Code/Explicit/src/CMakeLists.txt @@ -31,5 +31,8 @@ if ( MSVC AND SITK_BUILD_SHARED_LIBS ) set( SimpleITKExplicit_FORCE_LIBRARY_TYPE "STATIC" ) endif() add_library ( SimpleITKExplicit ${SimpleITKExplicit_FORCE_LIBRARY_TYPE} ${SimpleITKExplicitSource} ) +if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9) + set_target_properties(SimpleITKExplicit PROPERTIES CXX_VISIBILITY_PRESET default) +endif() target_link_libraries ( SimpleITKExplicit PUBLIC ${ITK_LIBRARIES} ) sitk_install_exported_target( SimpleITKExplicit ) From dddbfd2be651cec5f9c745d532a280c1b6d8091e Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Wed, 6 Jul 2016 10:53:58 -0400 Subject: [PATCH 339/412] Old CMake Uppercase Expression Fix "defined" is changed to "DEFINED" because older cmake version (less than 3) are case sensitive. Change-Id: Iee95ab07cbdb35416837698d689359039d988b90 --- CMake/sitkGenerateFilterSource.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMake/sitkGenerateFilterSource.cmake b/CMake/sitkGenerateFilterSource.cmake index 64f892d57..a97f08b37 100644 --- a/CMake/sitkGenerateFilterSource.cmake +++ b/CMake/sitkGenerateFilterSource.cmake @@ -7,7 +7,7 @@ if ( NOT SITK_LUA_EXECUTABLE ) find_package( LuaInterp REQUIRED 5.1 ) set( SITK_LUA_EXECUTABLE ${LUA_EXECUTABLE} CACHE PATH "Lua executable used for code generation." ) - if (defined SAVE_LUA_EXECUTABLE) + if (DEFINED SAVE_LUA_EXECUTABLE) set( LUA_EXECUTABLE ${SAVE_LUA_EXECUTABLE} CACHE ) else() unset( LUA_EXECUTABLE CACHE ) From 6503c7ba3f645032fe877996a10a5c5a4c8d9626 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 7 Jul 2016 12:07:38 -0400 Subject: [PATCH 340/412] Adding Image methods to set meta-data and erase a key Many users have requested write access to the meta-data for writing. Providing these additional interface methods should give the ability to manually copy the dictionary elements one by one. This should encourage processing the elements as opposed to just coping the elements with out respect to standards and processes. Change-Id: Iccd88d733369de4e978f89ad5f29bdc99f2da310 --- Code/Common/include/sitkImage.h | 15 ++++++++++++++- Code/Common/src/sitkImage.cxx | 15 +++++++++++++++ Testing/Unit/sitkImageTests.cxx | 17 +++++++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/Code/Common/include/sitkImage.h b/Code/Common/include/sitkImage.h index 868758a75..796678e43 100644 --- a/Code/Common/include/sitkImage.h +++ b/Code/Common/include/sitkImage.h @@ -196,7 +196,7 @@ namespace simple /** \brief Copy common meta-data from an image to this one. * * Copies the Origin, Spacing, and Direction from the source image - * to this image. + * to this image. The meta-data dictionary is \b not copied. * * It is required for the source Image's dimension and size to * match, this image's attributes, otherwise an exception will be @@ -227,6 +227,19 @@ namespace simple */ std::string GetMetaData( const std::string &key ) const; + /** \brief Set an entry in the meta-data dictionary. + * + * Replaces or creates an entry in the image's meta-data dictionary. + */ + void SetMetaData( const std::string &key, const std::string &value); + + /** \brief Remove an entry from the meta-data dictionary. + * + * Returns true, when the value exists in the dictionary and is + * removed, false otherwise. + */ + bool EraseMetaData( const std::string &key ); + std::string GetPixelIDTypeAsString( void ) const; std::string ToString( void ) const; diff --git a/Code/Common/src/sitkImage.cxx b/Code/Common/src/sitkImage.cxx index f44df47fe..592bbfef3 100644 --- a/Code/Common/src/sitkImage.cxx +++ b/Code/Common/src/sitkImage.cxx @@ -256,6 +256,21 @@ namespace itk return ss.str(); } + void Image::SetMetaData( const std::string &key, const std::string &value) + { + assert( m_PimpleImage ); + this->MakeUnique(); + itk::MetaDataDictionary &mdd = this->m_PimpleImage->GetDataBase()->GetMetaDataDictionary(); + itk::EncapsulateMetaData(mdd, key, value); + } + + bool Image::EraseMetaData( const std::string &key ) + { + assert( m_PimpleImage ); + itk::MetaDataDictionary &mdd = this->m_PimpleImage->GetDataBase()->GetMetaDataDictionary(); + this->MakeUnique(); + return mdd.Erase(key); + } // Physical Point to Continuous Index std::vector< int64_t > Image::TransformPhysicalPointToIndex( const std::vector< double > &pt ) const diff --git a/Testing/Unit/sitkImageTests.cxx b/Testing/Unit/sitkImageTests.cxx index 7924bf26e..7c6029e89 100644 --- a/Testing/Unit/sitkImageTests.cxx +++ b/Testing/Unit/sitkImageTests.cxx @@ -1600,6 +1600,23 @@ TEST_F(Image,MetaDataDictionary) std::cout << "Key = \"" << keys[i] << "\" Value = \"" << value << "\"" << std::endl; } + img = sitk::Image( 10,10, 10, sitk::sitkFloat32 ); + img.SetMetaData( "k1", "somevalue"); + + EXPECT_EQ( 1u, img.GetMetaDataKeys().size() ); + EXPECT_TRUE( img.HasMetaDataKey("k1") ); + EXPECT_EQ( "somevalue", img.GetMetaData("k1") ); + + EXPECT_FALSE( img.EraseMetaData("wrong") ); + EXPECT_EQ( 1u, img.GetMetaDataKeys().size() ); + EXPECT_TRUE( img.HasMetaDataKey("k1") ); + + EXPECT_TRUE( img.EraseMetaData("k1") ); + EXPECT_FALSE( img.HasMetaDataKey("k1") ); + EXPECT_EQ( 0u, img.GetMetaDataKeys().size() ); + + EXPECT_TRUE( img.EraseMetaData("k1") ); + } From 1c91154fc852b183901f213e5f191baa2e63c671 Mon Sep 17 00:00:00 2001 From: Ziv Yaniv Date: Thu, 7 Jul 2016 16:45:29 -0400 Subject: [PATCH 341/412] Adding test for meta data dictionary. Test that the meta data dictionary is valid after reading an image as a DICOM series - should be empty as we have a set of dictionaries, one from each slice. Change-Id: I75f410487b26fc7fef2b5930f0c3530caaa9e2fe --- Testing/Unit/sitkImageIOTests.cxx | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Testing/Unit/sitkImageIOTests.cxx b/Testing/Unit/sitkImageIOTests.cxx index f5fe5c41d..4482099c9 100644 --- a/Testing/Unit/sitkImageIOTests.cxx +++ b/Testing/Unit/sitkImageIOTests.cxx @@ -342,11 +342,18 @@ TEST(IO, DicomSeriesReader) { fileNames = reader.GetGDCMSeriesFileNames( dicomDir ); - sitk::Image image = reader.SetFileNames( fileNames ).Execute(); + reader.SetFileNames( fileNames ); + sitk::Image image = reader.Execute(); EXPECT_EQ( "f5ad2854d68fc87a141e112e529d47424b58acfb", sitk::Hash( image ) ); fileNames = reader.GetGDCMSeriesFileNames( dicomDir, "1.2.840.113619.2.133.1762890640.1886.1055165015.999" ); EXPECT_EQ( 3u, fileNames.size() ); + + // When reading a series each slice has its own meta-data dictionary + // so the user has to decide on how to combine them, our image will + // return an empty dictionary. + std::vector< std::string > metaDataKeys = image.GetMetaDataKeys(); + EXPECT_EQ( 0u, metaDataKeys.size() ); } From 79798f6d9b5e0decbfb5c364c99a26dbdf5aa458 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 8 Jul 2016 15:52:56 -0400 Subject: [PATCH 342/412] Updating ITK Superbuild version to just before 4.10.1 release Change-Id: I58abf85d4f64ba0f9d804ae390d666ed09c32563 --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 22f7c58de..6777ac2d2 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -40,7 +40,7 @@ if("${git_protocol}" STREQUAL "git") endif() # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG 8565bd9b4bc4446b05554e11ccb27bda1d6db647 ) # just after 4.10.0 release +set(ITK_TAG_COMMAND GIT_TAG 0ab6b7b7dbcca3b91a4a4c3a57975d297046ef61 ) # just before 4.10.1 release if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 95ebfa1a45091eb6a26384acc13ffaf429b06684 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 8 Jul 2016 16:39:29 -0400 Subject: [PATCH 343/412] Remove creation for MetaDataDictionary array in ImageSeriesReader Due to the large number of flags in a dicom files, there are performance benefits gained by explicitly not doing this operation. Change-Id: Ic2da668d20e8fa81742fab249a695814ad5f3ad5 --- Code/IO/src/sitkImageSeriesReader.cxx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/IO/src/sitkImageSeriesReader.cxx b/Code/IO/src/sitkImageSeriesReader.cxx index 74950df0e..6da7c68f5 100644 --- a/Code/IO/src/sitkImageSeriesReader.cxx +++ b/Code/IO/src/sitkImageSeriesReader.cxx @@ -164,12 +164,14 @@ namespace itk { typedef itk::ImageSeriesReader Reader; // if the IsInstantiated is correctly implemented this should - // not occour + // not occur assert( ImageTypeToPixelIDValue::Result != (int)sitkUnknown ); assert( imageio != SITK_NULLPTR ); typename Reader::Pointer reader = Reader::New(); reader->SetImageIO( imageio ); reader->SetFileNames( this->m_FileNames ); + // save some computation by not updating this unneeded data-structure + reader->MetaDataDictionaryArrayUpdateOff(); this->PreUpdate( reader.GetPointer() ); From adc4ec2877781ab22eacb1e4b4bab1234c4c5508 Mon Sep 17 00:00:00 2001 From: Ziv Yaniv Date: Mon, 11 Jul 2016 12:03:20 -0400 Subject: [PATCH 344/412] Adding example illustrating changes in DICOM tags. Change-Id: Icd6e0510331511ce6ed63f8cc867bd9b8626e5e3 --- Examples/Python/CMakeLists.txt | 6 +++ Examples/Python/DicomModifyTags.py | 64 ++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 Examples/Python/DicomModifyTags.py diff --git a/Examples/Python/CMakeLists.txt b/Examples/Python/CMakeLists.txt index ea7e4975d..e93015bfc 100644 --- a/Examples/Python/CMakeLists.txt +++ b/Examples/Python/CMakeLists.txt @@ -282,3 +282,9 @@ sitk_add_python_test(Example.DemonsRegistration2 DATA{${SimpleITK_DATA_ROOT}/Baseline/DemonsRegistration2Test_displacement.mha} 0.01 ) + +sitk_add_python_test(Example.DicomModifyTags + "${CMAKE_CURRENT_SOURCE_DIR}/DicomModifyTags.py" + DATA{${SimpleITK_DATA_ROOT}/Input/DicomSeries/Image0075.dcm + ${TEST_HARNESS_TEMP_DIRECTORY}/modifiedTags.dcm + ) diff --git a/Examples/Python/DicomModifyTags.py b/Examples/Python/DicomModifyTags.py new file mode 100644 index 000000000..32bbcf7c3 --- /dev/null +++ b/Examples/Python/DicomModifyTags.py @@ -0,0 +1,64 @@ +#========================================================================= +# +# Copyright Insight Software Consortium +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0.txt +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#========================================================================= + +from __future__ import print_function + +import SimpleITK as sitk + +import sys, time + +if len( sys.argv ) < 3: + print( "Usage: python " + __file__ + " " ) + sys.exit ( 1 ) + +# Read the image, single 3D DICOM slice +image = sitk.ReadImage( sys.argv[1] ) + +# Modify the image (mean) +mean_image = sitk.BoxMean( image, [3,3,1] ) + +# Save the modified image: +# We do not provide a method that copies all keys blindly. Our intent is +# to force us to remember that we always need to modify the meta-data dicitonary +# keys when we save processed images in DICOM format. +# In case of the DICOM format, amongst other keys we need to set the Image Type (0008,0008), +# the Series Date (0008,0021), and Series Time (0008,0021). Obviously we need to set a +# different series number (0020,0011), series instance UID (0020,000E), etc. - we don't do +# that here. +# Please see the DICOM standard (http://dicom.nema.org/standard.html) for complete details on +# how to create valid DICOM images. + +all_keys = image.GetMetaDataKeys() +for key in all_keys: + mean_image.SetMetaData( key, image.GetMetaData( key ) ) +mean_image.SetMetaData( "0008|0008", "DERIVED\SECONDARY" ) +modification_time = time.strftime("%H%M%S") +modification_date = time.strftime("%Y%m%d") +mean_image.SetMetaData( "0008|0031", modification_time ) +mean_image.SetMetaData( "0008|0021", modification_date ) + +sitk.WriteImage( mean_image, sys.argv[2] ) + +# Finally, read the image back and see that changes were made +modified_image = sitk.ReadImage( sys.argv[2] ) +if modified_image.GetMetaData( "0008|0008" ) != "DERIVED\SECONDARY" or \ + modified_image.GetMetaData( "0008|0031" ) != modification_time or \ + modified_image.GetMetaData( "0008|0021" ) != modification_date: + sys.exit(1) + +sys.exit( 0 ) From 8be3e9bccdcf348cb5397266a25a4c9e158518d0 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 11 Jul 2016 12:18:27 -0400 Subject: [PATCH 345/412] Explict Library only needs default visibility with shared libraries For older versions of GCC only force default visibility with shared libraries as this is the only case where the attribute warning and visibility problem occurs. Change-Id: I2ac46acd85c1ac3f4446135fac8ffec6877f5f81 --- Code/Explicit/src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Explicit/src/CMakeLists.txt b/Code/Explicit/src/CMakeLists.txt index 1b7cc1186..e0fcce2ec 100644 --- a/Code/Explicit/src/CMakeLists.txt +++ b/Code/Explicit/src/CMakeLists.txt @@ -31,7 +31,7 @@ if ( MSVC AND SITK_BUILD_SHARED_LIBS ) set( SimpleITKExplicit_FORCE_LIBRARY_TYPE "STATIC" ) endif() add_library ( SimpleITKExplicit ${SimpleITKExplicit_FORCE_LIBRARY_TYPE} ${SimpleITKExplicitSource} ) -if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9) +if( CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9 AND SITK_BUILD_SHARED_LIBS ) set_target_properties(SimpleITKExplicit PROPERTIES CXX_VISIBILITY_PRESET default) endif() target_link_libraries ( SimpleITKExplicit PUBLIC ${ITK_LIBRARIES} ) From 97a1c5ae1539f9fb6f0df1268d55a6af060a0950 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 11 Jul 2016 13:40:12 -0400 Subject: [PATCH 346/412] Correct CMake module path for independent language projects Change-Id: I61798527e26d572cc04cb05a2fb0ca560e2357e4 --- CMake/sitkProjectLanguageCommon.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMake/sitkProjectLanguageCommon.cmake b/CMake/sitkProjectLanguageCommon.cmake index 41d5b7828..4fe12ec4b 100644 --- a/CMake/sitkProjectLanguageCommon.cmake +++ b/CMake/sitkProjectLanguageCommon.cmake @@ -6,7 +6,7 @@ if (NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK" ) set( SimpleITK_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../.." ) - list(INSERT CMAKE_MODULE_PATH 0 "${CMAKE_CURRENT_SOURCE_DIR}/CMake") + list(INSERT CMAKE_MODULE_PATH 0 "${CMAKE_CURRENT_LIST_DIR}") find_package(SimpleITK REQUIRED) include(${SimpleITK_USE_FILE}) From eb7925217c09e1470557db1122a628e3600f502d Mon Sep 17 00:00:00 2001 From: Ziv Yaniv Date: Mon, 11 Jul 2016 15:35:29 -0400 Subject: [PATCH 347/412] Updated readme to reflect current state of SimpleITK. Change-Id: I1387eb381ccaccb2d0a3289e976c51485dc9d103 --- Readme.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index ed689493a..3adabfac5 100644 --- a/Readme.md +++ b/Readme.md @@ -1,14 +1,20 @@ SimpleITK ========= -The goal of SimpleITK is to provide an abstraction layer to [ITK](https://www.itk.org) that enables developers and users to access the powerful features of the Insight Toolkit in a more simplified manner. SimpleITK's goal is to provide a simple layer to ITK's complicated C++ templeted API to be easily wrap-able in several languages including: +SimpleITK is an image analysis toolkit with a large number of components supporting general filtering operations, image segmentation and registration. It is built on top of the Insight Segmentation and Registration Toolkit [ITK](https://www.itk.org) with the intent of providing a simplified interface to ITK. SimpleITK itself is written in C++ but is available for a large number of programming languages. Currently these include: * [Python](http://www.python.org) +* [R https://www.r-project.org/] * [Java](http://www.java.com) * [C#](http://msdn.microsoft.com/en-us/vcsharp/default.aspx) * [Lua](http://www.lua.org) +* [TCL](https://www.tcl.tk/) +* [Ruby](https://www.ruby-lang.org/en/) -Wrapping is accomplished through [SWIG](http://www.swig.org), in principle, any language wrapped by SWIG should be applicable to SimpleITK. + +Wrapping of the C++ code is accomplished through [SWIG](http://www.swig.org), in principle, any language wrapped by SWIG should be applicable to SimpleITK. + +Unlike ITK's support of n-dimensional spatio-temporal images, SimpleITK supports 2D, 3D and optionally 3D+time. The dimensionality refers to spatio-temporal dimensions, the voxels can be n-dimensional vectors. SimpleITK is licensed under the [Apache License](http://www.opensource.org/licenses/apache2.0.php) in the [same way as ITK](https://www.itk.org/Wiki/ITK_Release_4/Licensing). @@ -17,4 +23,6 @@ Development SimpleITK uses the [Git](http://git-scm.com/) distributed version control system. The main repository is hosted on [itk.org](https://itk.org/SimpleITK.git) and mirrored to [Github](https://blowekamp@github.com/SimpleITK/SimpleITK.git). There are two main branches, master and next. The "master" is a stable branch of the code, and suitable for most users, while "next" contains future features that are unlikely to be stable. -Documentation in maintained in [Doxygen](https://www.itk.org/SimpleITKDoxygen/html/annotated.html). [Development instructions](https://www.itk.org/SimpleITKDoxygen/html/pages.html) are also on this site. There is also the [Wiki](https://www.itk.org/Wiki/ITK_Release_4/SimpleITK) with additional information. SimpleITK requires a recent build of [ITK v4](https://itk.org/), but this can be automatically build along side SimpleITK with the SuperBuild cmake build. +The SimpleITK [Wiki](https://itk.org/Wiki/SimpleITK) is the main site for all things SimpleITK. The site includes information on installing the toolkit's binary distributions, building the toolkit, user support documentation and much more. The API documentation is maintained using [Doxygen](https://www.itk.org/SimpleITKDoxygen/html/annotated.html). + +SimpleITK provides access to most of the ITK components, but not all. If you are looking for something specific and can't find it, ask for support on the [mailing list](https://itk.org/mailman/listinfo/community) (you will need to subscribe to the mailing list before you post). From 0267d942faa977073cc2a2339381b7748ce07336 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Tue, 12 Jul 2016 12:27:39 +0200 Subject: [PATCH 348/412] ENH: Update elastix to revision 5395 --- Code/Elastix/src/sitkSimpleElastix.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Elastix/src/sitkSimpleElastix.cxx b/Code/Elastix/src/sitkSimpleElastix.cxx index f7fbcf243..5f9f7eb05 100644 --- a/Code/Elastix/src/sitkSimpleElastix.cxx +++ b/Code/Elastix/src/sitkSimpleElastix.cxx @@ -869,9 +869,9 @@ ::Execute( void ) { if( this->GetMovingImage( i ).GetPixelID() != MovingImagePixelID ) { - sitkExceptionMacro( "Fixed images must be of same pixel type (fixed image at index 0 is of type " + sitkExceptionMacro( "Moving images must be of same pixel type (moving image at index 0 is of type " << GetPixelIDValueAsElastixParameter( this->GetMovingImage( 0 ).GetPixelID() ) << ", " - << "fixed image at index " << i << " is of type \"" + << "moving image at index " << i << " is of type \"" << GetPixelIDValueAsElastixParameter( this->GetMovingImage( i ).GetPixelID() ) << "\")." ); } From 63039590b461da9209c8b04eb53bd30e0c837d6e Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Tue, 12 Jul 2016 12:29:09 +0200 Subject: [PATCH 349/412] BUG: Remove unneeded typename keyword --- Examples/ElastixFilter.cxx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Examples/ElastixFilter.cxx b/Examples/ElastixFilter.cxx index ed82b50d5..c78976be9 100644 --- a/Examples/ElastixFilter.cxx +++ b/Examples/ElastixFilter.cxx @@ -15,19 +15,19 @@ int main( int argc, char* argv[] ) { typedef itk::Image< float, 2u > ImageType; typedef elastix::ElastixFilter< ImageType, ImageType > ElastixFilterType; - typedef typename ElastixFilterType::Pointer ElastixPointer; + typedef ElastixFilterType::Pointer ElastixPointer; typedef elastix::ParameterObject ParameterObjectType; - typedef typename ParameterObjectType::Pointer ParameterObjectPointer; + typedef ParameterObjectType::Pointer ParameterObjectPointer; typedef itk::ImageFileReader< ImageType > FixedImageReaderType; - typedef typename FixedImageReaderType::Pointer FixedImageReaderPointer; + typedef FixedImageReaderType::Pointer FixedImageReaderPointer; typedef itk::ImageFileReader< ImageType > MovingImageReaderType; - typedef typename MovingImageReaderType::Pointer MovingImageReaderPointer; + typedef MovingImageReaderType::Pointer MovingImageReaderPointer; typedef itk::ImageFileWriter< ImageType > ResultImageWriterType; - typedef typename ResultImageWriterType::Pointer ResultImageWriterPointer; + typedef ResultImageWriterType::Pointer ResultImageWriterPointer; try { From 0a911c3c5019c9f4ad1620447613c6a088cdeb91 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Tue, 12 Jul 2016 16:31:53 +0200 Subject: [PATCH 350/412] GIT: A previous commit '0267d942 ENH: Update elastix to revision 5395' did not include SuperBuild/External_Elastix.cmake as it was supposed to --- SuperBuild/External_Elastix.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_Elastix.cmake b/SuperBuild/External_Elastix.cmake index 7712256d4..b8cb2addd 100644 --- a/SuperBuild/External_Elastix.cmake +++ b/SuperBuild/External_Elastix.cmake @@ -2,7 +2,7 @@ set( proj elastix ) file( WRITE "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" "${ep_common_cache}" ) set( ELASTIX_REPOSITORY http://github.com/kaspermarstal/elastix ) -set( ELASTIX_TAG 25c9dec600979a997faa373d7cd5259f65fac220 ) +set( ELASTIX_TAG 3c7deef6d4f44203207bc198cc27f011ac1222c7 ) ExternalProject_Add( ${proj} GIT_REPOSITORY ${ELASTIX_REPOSITORY} From bc25d94f8491f7a2592dc4698b7267c5042ed9e6 Mon Sep 17 00:00:00 2001 From: Ziv Yaniv Date: Tue, 12 Jul 2016 13:17:41 -0400 Subject: [PATCH 351/412] Added missing curly brace in Cmakelists file. Change-Id: I098eb3bcb822540a1aa9fd9c973670d559b4edad --- Examples/Python/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/Python/CMakeLists.txt b/Examples/Python/CMakeLists.txt index e93015bfc..bed1b082b 100644 --- a/Examples/Python/CMakeLists.txt +++ b/Examples/Python/CMakeLists.txt @@ -285,6 +285,6 @@ sitk_add_python_test(Example.DemonsRegistration2 sitk_add_python_test(Example.DicomModifyTags "${CMAKE_CURRENT_SOURCE_DIR}/DicomModifyTags.py" - DATA{${SimpleITK_DATA_ROOT}/Input/DicomSeries/Image0075.dcm + DATA{${SimpleITK_DATA_ROOT}/Input/DicomSeries/Image0075.dcm} ${TEST_HARNESS_TEMP_DIRECTORY}/modifiedTags.dcm ) From 9d58de4cdc18104c5435fcbd6b74f3cc49d8bb04 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 18 Jul 2016 16:11:43 -0400 Subject: [PATCH 352/412] Updating ITK Superbuild version to include CMP0063 fix for vxl Change-Id: I84443320a077ebe171194bd028544b3e1f3f232e --- SuperBuild/External_ITK.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 6777ac2d2..dd7398b51 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -40,7 +40,7 @@ if("${git_protocol}" STREQUAL "git") endif() # NOTE: it is very important to update the ITK_DIR path with the ITK version -set(ITK_TAG_COMMAND GIT_TAG 0ab6b7b7dbcca3b91a4a4c3a57975d297046ef61 ) # just before 4.10.1 release +set(ITK_TAG_COMMAND GIT_TAG 80178ae516db87aa50d2883c4e090da92c4a502d ) # just before 4.10.1 release if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ITK_BUILD_SHARED_LIBS ON ) From 94bbba0cccbc98e34498219a823124eeaadfa27a Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 20 Jul 2016 16:27:43 -0400 Subject: [PATCH 353/412] Fix MSVC double to float conversion warnings Change-Id: I63aec35068c09b0b55a2e1f391589d091f239dfd --- Testing/Unit/sitkCommonTests.cxx | 4 ++-- Testing/Unit/sitkImportImageTest.cxx | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Testing/Unit/sitkCommonTests.cxx b/Testing/Unit/sitkCommonTests.cxx index f84970cd4..a0aaef9c7 100644 --- a/Testing/Unit/sitkCommonTests.cxx +++ b/Testing/Unit/sitkCommonTests.cxx @@ -289,7 +289,7 @@ TEST( ProcessObject, DeleteCommandActiveProcess ) sitk::Image img(100,100,100, sitk::sitkUInt16); sitk::Command *cmd1 = new sitk::Command(); - DeleteCommandAtCommand cmd2(po, .01, cmd1); + DeleteCommandAtCommand cmd2(po, .01f, cmd1); po.AddCommand(sitk::sitkAnyEvent, *cmd1); po.AddCommand(sitk::sitkProgressEvent, cmd2); @@ -333,7 +333,7 @@ TEST( ProcessObject, RemoveAllCommandsActiveProcess ) sitk::Image img(100,100,100, sitk::sitkUInt16); sitk::Command cmd1; - RemoveAllCommandsAtCommand cmd2(po, .01); + RemoveAllCommandsAtCommand cmd2(po, .01f); po.AddCommand(sitk::sitkAnyEvent, cmd1); po.AddCommand(sitk::sitkProgressEvent, cmd2); diff --git a/Testing/Unit/sitkImportImageTest.cxx b/Testing/Unit/sitkImportImageTest.cxx index 499193b91..351b01acb 100644 --- a/Testing/Unit/sitkImportImageTest.cxx +++ b/Testing/Unit/sitkImportImageTest.cxx @@ -280,7 +280,7 @@ TEST_F(Import,ExhaustiveTypes) { EXPECT_EQ ( "d0a23a11b2f39b46cfc09bd71fc4c9661b68a826" , sitk::Hash( importer.Execute() ) ) << " hash value for int64"; } - float_buffer = std::vector< float >( 16*16, 1.123 ); + float_buffer = std::vector< float >( 16*16, 1.123f ); importer.SetBufferAsFloat( &float_buffer[0] ); EXPECT_EQ ( "8588f5624f56bb55693d54505388dc06b93d2f14", sitk::Hash( importer.Execute() ) ) << " hash value for float"; @@ -327,7 +327,7 @@ TEST_F(Import,ExhaustiveTypes) { EXPECT_EQ ( "91a61e519faf128747bf2d2bbd860d4f05d79ac6" , sitk::Hash( importer.Execute() ) ) << " hash value for vector of int64"; } - float_buffer = std::vector< float >( 16*16*8, 1.123 ); + float_buffer = std::vector< float >( 16*16*8, 1.123f ); importer.SetBufferAsFloat( &float_buffer[0], 8 ); EXPECT_EQ ( "9fb1d83b9c9a5645e7b136761d6924ea7d859284", sitk::Hash( importer.Execute() ) ) << " hash value for vector of float"; @@ -422,7 +422,7 @@ TEST_F(Import,Procedual) { EXPECT_EQ ( img.GetDirection(), direction2D ) << " direction for int32"; - float_buffer = std::vector< float >( 16*16, 1.123 ); + float_buffer = std::vector< float >( 16*16, 1.123f ); img = sitk::ImportAsFloat( &float_buffer[0], size, spacing2, From 1d3b291f75e97c9085ba4b8f6f206d2e2934f0b6 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 20 Jul 2016 16:31:55 -0400 Subject: [PATCH 354/412] Adding wrapper for std::unique_ptr as nsstd::auto_ptr While we would prefer to move forward with the std::unique name and behavior, since c++03 does not allow template alias will can only alias in C++11. Therefor we use the old name with the new behavior. Change-Id: I428ccc3393f29bf8bcde236bfb5409d02da6923f --- CMake/sitkCheckCXX11.cmake | 4 +++ CMake/sitk_check_cxx11.cxx | 16 +++++++++++ Code/Common/include/nsstd/auto_ptr.h | 41 ++++++++++++++++++++++++++++ Code/Common/src/sitkConfigure.h.in | 1 + 4 files changed, 62 insertions(+) create mode 100644 Code/Common/include/nsstd/auto_ptr.h diff --git a/CMake/sitkCheckCXX11.cmake b/CMake/sitkCheckCXX11.cmake index 7faf81c5b..b03a37db4 100644 --- a/CMake/sitkCheckCXX11.cmake +++ b/CMake/sitkCheckCXX11.cmake @@ -6,6 +6,7 @@ # SITK_HAS_CXX11_TYPE_TRAITS # SITK_HAS_CXX11_UNORDERED_MAP # SITK_HAS_CXX11_NULLPTR - True if "nullptr" keyword is supported +# SITK_HAS_CXX11_UNIQUE_PTR # # SITK_HAS_TR1_SUB_INCLUDE # @@ -55,6 +56,9 @@ sitkCXX11Test(SITK_HAS_CXX11_FUNCTIONAL) sitkCXX11Test(SITK_HAS_CXX11_TYPE_TRAITS) sitkCXX11Test(SITK_HAS_CXX11_UNORDERED_MAP) sitkCXX11Test(SITK_HAS_CXX11_NULLPTR) +sitkCXX11Test(SITK_HAS_CXX11_UNIQUE_PTR) + + # Microsoft Visual Studio 2008sp1,2010,2012 don't need tr1 as a path # prefix to tr1 headers, while libc++ diff --git a/CMake/sitk_check_cxx11.cxx b/CMake/sitk_check_cxx11.cxx index 861f00e1c..4751e9797 100644 --- a/CMake/sitk_check_cxx11.cxx +++ b/CMake/sitk_check_cxx11.cxx @@ -51,6 +51,22 @@ return 0; #endif + +//------------------------------------- + +#ifdef SITK_HAS_CXX11_UNIQUE_PTR + +#include + +int main(void) { + std::unique_ptr p1(new int); + return 0; +} + +#endif + + + //------------------------------------- #ifdef SITK_HAS_TR1_FUNCTIONAL diff --git a/Code/Common/include/nsstd/auto_ptr.h b/Code/Common/include/nsstd/auto_ptr.h new file mode 100644 index 000000000..f241898ff --- /dev/null +++ b/Code/Common/include/nsstd/auto_ptr.h @@ -0,0 +1,41 @@ +/*========================================================================= +* +* Copyright Insight Software Consortium +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0.txt +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT 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 __sitk_nsstd_auto_ptr_h +#define __sitk_nsstd_auto_ptr_h + +#include "sitkConfigure.h" + +#include + +namespace itk +{ +namespace simple +{ +namespace nsstd +{ +#if defined SITK_HAS_CXX11_UNIQUE_PTR +template +using auto_ptr = std::unique_ptr; +#else +using std::auto_ptr; +#endif +} +} +} + +#endif //__sitk_nsstd_auto_ptr_h diff --git a/Code/Common/src/sitkConfigure.h.in b/Code/Common/src/sitkConfigure.h.in index 014f9f034..28b9f089c 100644 --- a/Code/Common/src/sitkConfigure.h.in +++ b/Code/Common/src/sitkConfigure.h.in @@ -35,6 +35,7 @@ #cmakedefine SITK_HAS_CXX11_FUNCTIONAL #cmakedefine SITK_HAS_CXX11_TYPE_TRAITS #cmakedefine SITK_HAS_CXX11_UNORDERED_MAP +#cmakedefine SITK_HAS_CXX11_UNIQUE_PTR #cmakedefine SITK_HAS_TR1_SUB_INCLUDE From f3a4d10e18b93ca53f02d1b48f04a9a11459329f Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 20 Jul 2016 16:34:59 -0400 Subject: [PATCH 355/412] Renaming std::auto_ptr to nsstd::auto_ptr This will avoid compilation warnings about using an deprecated class. Change-Id: If062b227234255b9506bd1482ad8ce907188b7a4 --- .../sitkBSplineTransformInitializerFilter.h | 2 +- .../include/sitkCastImageFilter.h | 2 +- .../sitkCenteredTransformInitializerFilter.h | 2 +- ...CenteredVersorTransformInitializerFilter.h | 2 +- .../include/sitkHashImageFilter.h | 2 +- ...kLandmarkBasedTransformInitializerFilter.h | 2 +- .../json/ConvolutionImageFilter.json | 2 +- .../json/FFTConvolutionImageFilter.json | 2 +- Code/BasicFilters/json/FFTPadImageFilter.json | 2 +- .../json/InverseDeconvolutionImageFilter.json | 2 +- .../LandweberDeconvolutionImageFilter.json | 2 +- ...ctedLandweberDeconvolutionImageFilter.json | 2 +- ...ichardsonLucyDeconvolutionImageFilter.json | 2 +- .../TikhonovDeconvolutionImageFilter.json | 2 +- .../json/WienerDeconvolutionImageFilter.json | 2 +- .../src/sitkBoundaryConditions.hxx | 4 +- Code/BasicFilters/src/sitkImageToKernel.hxx | 4 +- .../sitkBinaryFunctorFilterTemplate.h.in | 4 +- .../sitkDualImageFilterTemplate.h.in | 2 +- Code/Common/include/sitkImage.h | 1 + Code/Common/src/sitkImage.cxx | 4 +- Code/Common/src/sitkTransform.cxx | 2 +- Code/IO/include/sitkImageFileReader.h | 2 +- Code/IO/include/sitkImageFileWriter.h | 2 +- Code/IO/include/sitkImageSeriesReader.h | 2 +- Code/IO/include/sitkImageSeriesWriter.h | 2 +- Code/IO/include/sitkImportImageFilter.h | 2 +- .../include/sitkImageRegistrationMethod.h | 4 +- .../MemberFunctionDispatch.h.in | 2 +- Testing/Unit/sitkCommonTests.cxx | 44 +++++++++---------- Testing/Unit/sitkImage4DTests.cxx | 2 +- Testing/Unit/sitkImageTests.cxx | 2 +- Testing/Unit/sitkTransformTests.cxx | 28 ++++++------ 33 files changed, 72 insertions(+), 71 deletions(-) diff --git a/Code/BasicFilters/include/sitkBSplineTransformInitializerFilter.h b/Code/BasicFilters/include/sitkBSplineTransformInitializerFilter.h index 0fd70ca97..034df644c 100644 --- a/Code/BasicFilters/include/sitkBSplineTransformInitializerFilter.h +++ b/Code/BasicFilters/include/sitkBSplineTransformInitializerFilter.h @@ -102,7 +102,7 @@ Nick Tustison friend struct detail::MemberFunctionAddressor; - std::auto_ptr > m_MemberFactory; + nsstd::auto_ptr > m_MemberFactory; std::vector m_TransformDomainMeshSize; diff --git a/Code/BasicFilters/include/sitkCastImageFilter.h b/Code/BasicFilters/include/sitkCastImageFilter.h index c91d25991..5035fb17a 100644 --- a/Code/BasicFilters/include/sitkCastImageFilter.h +++ b/Code/BasicFilters/include/sitkCastImageFilter.h @@ -169,7 +169,7 @@ class SITKBasicFilters_EXPORT CastImageFilter /** @} */ typedef Image (Self::*MemberFunctionType)( const Image& ); - std::auto_ptr > m_DualMemberFactory; + nsstd::auto_ptr > m_DualMemberFactory; }; diff --git a/Code/BasicFilters/include/sitkCenteredTransformInitializerFilter.h b/Code/BasicFilters/include/sitkCenteredTransformInitializerFilter.h index dd071646d..717fe4153 100644 --- a/Code/BasicFilters/include/sitkCenteredTransformInitializerFilter.h +++ b/Code/BasicFilters/include/sitkCenteredTransformInitializerFilter.h @@ -109,7 +109,7 @@ In the second mode, the moments of gray level values are computed for both image friend struct detail::MemberFunctionAddressor; - std::auto_ptr > m_MemberFactory; + nsstd::auto_ptr > m_MemberFactory; OperationModeType m_OperationMode; diff --git a/Code/BasicFilters/include/sitkCenteredVersorTransformInitializerFilter.h b/Code/BasicFilters/include/sitkCenteredVersorTransformInitializerFilter.h index 03982338f..779c756ce 100644 --- a/Code/BasicFilters/include/sitkCenteredVersorTransformInitializerFilter.h +++ b/Code/BasicFilters/include/sitkCenteredVersorTransformInitializerFilter.h @@ -95,7 +95,7 @@ This class derived from the CenteredTransformInitializerand uses it in a more co friend struct detail::MemberFunctionAddressor; - std::auto_ptr > m_MemberFactory; + nsstd::auto_ptr > m_MemberFactory; bool m_ComputeRotation; diff --git a/Code/BasicFilters/include/sitkHashImageFilter.h b/Code/BasicFilters/include/sitkHashImageFilter.h index 71c4416c9..39b167957 100644 --- a/Code/BasicFilters/include/sitkHashImageFilter.h +++ b/Code/BasicFilters/include/sitkHashImageFilter.h @@ -71,7 +71,7 @@ namespace itk { friend struct detail::MemberFunctionAddressor; friend struct detail::ExecuteInternalLabelImageAddressor; - std::auto_ptr > m_MemberFactory; + nsstd::auto_ptr > m_MemberFactory; }; SITKBasicFilters_EXPORT std::string Hash ( const Image& image, HashImageFilter::HashFunction function = HashImageFilter::SHA1 ); diff --git a/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h b/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h index 298d14a0d..88dd0a3ac 100644 --- a/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h +++ b/Code/BasicFilters/include/sitkLandmarkBasedTransformInitializerFilter.h @@ -147,7 +147,7 @@ in ITK" by Kim E.Y., Johnson H., Williams N. available at http://midasjournal.co friend struct detail::MemberFunctionAddressor; - std::auto_ptr > m_MemberFactory; + nsstd::auto_ptr > m_MemberFactory; /* */ diff --git a/Code/BasicFilters/json/ConvolutionImageFilter.json b/Code/BasicFilters/json/ConvolutionImageFilter.json index 3d78468b9..524811993 100644 --- a/Code/BasicFilters/json/ConvolutionImageFilter.json +++ b/Code/BasicFilters/json/ConvolutionImageFilter.json @@ -28,7 +28,7 @@ "PERIODIC_PAD" ], "default" : "itk::simple::ConvolutionImageFilter::ZERO_FLUX_NEUMANN_PAD", - "custom_itk_cast" : "std::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" + "custom_itk_cast" : "nsstd::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" }, { "name" : "OutputRegionMode", diff --git a/Code/BasicFilters/json/FFTConvolutionImageFilter.json b/Code/BasicFilters/json/FFTConvolutionImageFilter.json index 531df1c20..410e394fe 100644 --- a/Code/BasicFilters/json/FFTConvolutionImageFilter.json +++ b/Code/BasicFilters/json/FFTConvolutionImageFilter.json @@ -28,7 +28,7 @@ "PERIODIC_PAD" ], "default" : "itk::simple::FFTConvolutionImageFilter::ZERO_FLUX_NEUMANN_PAD", - "custom_itk_cast" : "std::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" + "custom_itk_cast" : "nsstd::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" }, { "name" : "OutputRegionMode", diff --git a/Code/BasicFilters/json/FFTPadImageFilter.json b/Code/BasicFilters/json/FFTPadImageFilter.json index c1e5bb866..0fdddeb03 100644 --- a/Code/BasicFilters/json/FFTPadImageFilter.json +++ b/Code/BasicFilters/json/FFTPadImageFilter.json @@ -16,7 +16,7 @@ "PERIODIC_PAD" ], "default" : "itk::simple::FFTPadImageFilter::ZERO_FLUX_NEUMANN_PAD", - "custom_itk_cast" : "std::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" + "custom_itk_cast" : "nsstd::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" }, { "name" : "SizeGreatestPrimeFactor", diff --git a/Code/BasicFilters/json/InverseDeconvolutionImageFilter.json b/Code/BasicFilters/json/InverseDeconvolutionImageFilter.json index 524d1c74e..7c6fbd9d5 100644 --- a/Code/BasicFilters/json/InverseDeconvolutionImageFilter.json +++ b/Code/BasicFilters/json/InverseDeconvolutionImageFilter.json @@ -37,7 +37,7 @@ "PERIODIC_PAD" ], "default" : "itk::simple::InverseDeconvolutionImageFilter::ZERO_FLUX_NEUMANN_PAD", - "custom_itk_cast" : "std::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" + "custom_itk_cast" : "nsstd::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" }, { "name" : "OutputRegionMode", diff --git a/Code/BasicFilters/json/LandweberDeconvolutionImageFilter.json b/Code/BasicFilters/json/LandweberDeconvolutionImageFilter.json index 240f603db..ea57d06e7 100644 --- a/Code/BasicFilters/json/LandweberDeconvolutionImageFilter.json +++ b/Code/BasicFilters/json/LandweberDeconvolutionImageFilter.json @@ -46,7 +46,7 @@ "PERIODIC_PAD" ], "default" : "itk::simple::LandweberDeconvolutionImageFilter::ZERO_FLUX_NEUMANN_PAD", - "custom_itk_cast" : "std::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" + "custom_itk_cast" : "nsstd::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" }, { "name" : "OutputRegionMode", diff --git a/Code/BasicFilters/json/ProjectedLandweberDeconvolutionImageFilter.json b/Code/BasicFilters/json/ProjectedLandweberDeconvolutionImageFilter.json index 1948c7451..b253ff9d7 100644 --- a/Code/BasicFilters/json/ProjectedLandweberDeconvolutionImageFilter.json +++ b/Code/BasicFilters/json/ProjectedLandweberDeconvolutionImageFilter.json @@ -46,7 +46,7 @@ "PERIODIC_PAD" ], "default" : "itk::simple::ProjectedLandweberDeconvolutionImageFilter::ZERO_FLUX_NEUMANN_PAD", - "custom_itk_cast" : "std::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" + "custom_itk_cast" : "nsstd::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" }, { "name" : "OutputRegionMode", diff --git a/Code/BasicFilters/json/RichardsonLucyDeconvolutionImageFilter.json b/Code/BasicFilters/json/RichardsonLucyDeconvolutionImageFilter.json index 13213128b..999001454 100644 --- a/Code/BasicFilters/json/RichardsonLucyDeconvolutionImageFilter.json +++ b/Code/BasicFilters/json/RichardsonLucyDeconvolutionImageFilter.json @@ -37,7 +37,7 @@ "PERIODIC_PAD" ], "default" : "itk::simple::RichardsonLucyDeconvolutionImageFilter::ZERO_FLUX_NEUMANN_PAD", - "custom_itk_cast" : "std::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" + "custom_itk_cast" : "nsstd::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" }, { "name" : "OutputRegionMode", diff --git a/Code/BasicFilters/json/TikhonovDeconvolutionImageFilter.json b/Code/BasicFilters/json/TikhonovDeconvolutionImageFilter.json index 0690a1067..02cbc90c5 100644 --- a/Code/BasicFilters/json/TikhonovDeconvolutionImageFilter.json +++ b/Code/BasicFilters/json/TikhonovDeconvolutionImageFilter.json @@ -37,7 +37,7 @@ "PERIODIC_PAD" ], "default" : "itk::simple::TikhonovDeconvolutionImageFilter::ZERO_FLUX_NEUMANN_PAD", - "custom_itk_cast" : "std::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" + "custom_itk_cast" : "nsstd::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" }, { "name" : "OutputRegionMode", diff --git a/Code/BasicFilters/json/WienerDeconvolutionImageFilter.json b/Code/BasicFilters/json/WienerDeconvolutionImageFilter.json index 5eb68d2c7..9f8fa4a99 100644 --- a/Code/BasicFilters/json/WienerDeconvolutionImageFilter.json +++ b/Code/BasicFilters/json/WienerDeconvolutionImageFilter.json @@ -37,7 +37,7 @@ "PERIODIC_PAD" ], "default" : "itk::simple::WienerDeconvolutionImageFilter::ZERO_FLUX_NEUMANN_PAD", - "custom_itk_cast" : "std::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" + "custom_itk_cast" : "nsstd::auto_ptr< ImageBoundaryCondition< InputImageType > > bc( CreateNewBoundaryConditionInstance< Self, FilterType >( m_BoundaryCondition ) ); filter->SetBoundaryCondition( bc.get() );\n" }, { "name" : "OutputRegionMode", diff --git a/Code/BasicFilters/src/sitkBoundaryConditions.hxx b/Code/BasicFilters/src/sitkBoundaryConditions.hxx index 7832da4c8..95cb35c51 100644 --- a/Code/BasicFilters/src/sitkBoundaryConditions.hxx +++ b/Code/BasicFilters/src/sitkBoundaryConditions.hxx @@ -32,10 +32,10 @@ namespace itk { * */ template< class TFilter, class TInternalFilter > - std::auto_ptr > + nsstd::auto_ptr > CreateNewBoundaryConditionInstance(typename TFilter::BoundaryConditionType bc) { - typedef std::auto_ptr > PointerType; + typedef nsstd::auto_ptr > PointerType; switch ( bc ) { diff --git a/Code/BasicFilters/src/sitkImageToKernel.hxx b/Code/BasicFilters/src/sitkImageToKernel.hxx index 48726159d..374016b0f 100644 --- a/Code/BasicFilters/src/sitkImageToKernel.hxx +++ b/Code/BasicFilters/src/sitkImageToKernel.hxx @@ -34,12 +34,12 @@ namespace simple { * */ template -std::auto_ptr< ImageKernelOperator< typename TImageType::PixelType, TImageType::ImageDimension > > +nsstd::auto_ptr< ImageKernelOperator< typename TImageType::PixelType, TImageType::ImageDimension > > CreateOperatorFromImage( const TImageType * image ) { typedef typename TImageType::PixelType KernelImagePixelType; typedef ImageKernelOperator< KernelImagePixelType, TImageType::ImageDimension > KernelType; -typedef std::auto_ptr KernelPointerType; +typedef nsstd::auto_ptr KernelPointerType; typedef typename KernelType::SizeType KernelSizeType; diff --git a/Code/BasicFilters/templates/sitkBinaryFunctorFilterTemplate.h.in b/Code/BasicFilters/templates/sitkBinaryFunctorFilterTemplate.h.in index 1543206ec..a8b152fe4 100644 --- a/Code/BasicFilters/templates/sitkBinaryFunctorFilterTemplate.h.in +++ b/Code/BasicFilters/templates/sitkBinaryFunctorFilterTemplate.h.in @@ -52,12 +52,12 @@ $(include MemberFunctionDispatch.h.in) typedef Image (Self::*MemberFunction1Type)( ${constant_type} constant, const Image& image2 ); template Image ExecuteInternal ( ${constant_type} constant, const Image& image2 ); friend struct detail::MemberFunctionAddressor; - std::auto_ptr > m_MemberFactory1; + nsstd::auto_ptr > m_MemberFactory1; typedef Image (Self::*MemberFunction2Type)( const Image& image1, ${constant_type} constant ); template Image ExecuteInternal ( const Image& image1, ${constant_type} constant ); friend struct detail::MemberFunctionAddressor; - std::auto_ptr > m_MemberFactory2; + nsstd::auto_ptr > m_MemberFactory2; $(include PrivateMemberDeclarations.h.in)$(include ClassEnd.h.in) diff --git a/Code/BasicFilters/templates/sitkDualImageFilterTemplate.h.in b/Code/BasicFilters/templates/sitkDualImageFilterTemplate.h.in index 2e8a30b25..552676c2f 100644 --- a/Code/BasicFilters/templates/sitkDualImageFilterTemplate.h.in +++ b/Code/BasicFilters/templates/sitkDualImageFilterTemplate.h.in @@ -48,7 +48,7 @@ OUT=[[ template Image DualExecuteInternalVector ( $(include ImageParameters.in) );]] end) - std::auto_ptr > m_DualMemberFactory; + nsstd::auto_ptr > m_DualMemberFactory; $(include PrivateMemberDeclarations.h.in)$(include ClassEnd.h.in) diff --git a/Code/Common/include/sitkImage.h b/Code/Common/include/sitkImage.h index 796678e43..557590542 100644 --- a/Code/Common/include/sitkImage.h +++ b/Code/Common/include/sitkImage.h @@ -25,6 +25,7 @@ #include "sitkEnableIf.h" #include "nsstd/type_traits.h" +#include "nsstd/auto_ptr.h" #include #include diff --git a/Code/Common/src/sitkImage.cxx b/Code/Common/src/sitkImage.cxx index 592bbfef3..a6e3d47c9 100644 --- a/Code/Common/src/sitkImage.cxx +++ b/Code/Common/src/sitkImage.cxx @@ -51,7 +51,7 @@ namespace itk { // note: If img and this are this same, the following statement // will still be safe. It is also exception safe. - std::auto_ptr temp( img.m_PimpleImage->ShallowCopy() ); + nsstd::auto_ptr temp( img.m_PimpleImage->ShallowCopy() ); delete this->m_PimpleImage; this->m_PimpleImage = temp.release(); return *this; @@ -721,7 +721,7 @@ namespace itk if ( this->m_PimpleImage->GetReferenceCountOfImage() > 1 ) { // note: care is take here to be exception safe with memory allocation - std::auto_ptr temp( this->m_PimpleImage->DeepCopy() ); + nsstd::auto_ptr temp( this->m_PimpleImage->DeepCopy() ); delete this->m_PimpleImage; this->m_PimpleImage = temp.release(); } diff --git a/Code/Common/src/sitkTransform.cxx b/Code/Common/src/sitkTransform.cxx index 9bb8eded6..0a4c44af2 100644 --- a/Code/Common/src/sitkTransform.cxx +++ b/Code/Common/src/sitkTransform.cxx @@ -587,7 +587,7 @@ void Transform::SetPimpleTransform( PimpleTransformBase *pimpleTransform ) bool Transform::SetInverse() { assert( m_PimpleTransform ); - std::auto_ptr temp; + nsstd::auto_ptr temp; { // See if a new pimple transform can be created PimpleTransformBase *p = NULL; diff --git a/Code/IO/include/sitkImageFileReader.h b/Code/IO/include/sitkImageFileReader.h index 5664542fb..0d58ac81a 100644 --- a/Code/IO/include/sitkImageFileReader.h +++ b/Code/IO/include/sitkImageFileReader.h @@ -65,7 +65,7 @@ namespace itk { // friend to get access to executeInternal member friend struct detail::MemberFunctionAddressor; - std::auto_ptr > m_MemberFactory; + nsstd::auto_ptr > m_MemberFactory; std::string m_FileName; }; diff --git a/Code/IO/include/sitkImageFileWriter.h b/Code/IO/include/sitkImageFileWriter.h index 44a6379c4..db2f80f37 100644 --- a/Code/IO/include/sitkImageFileWriter.h +++ b/Code/IO/include/sitkImageFileWriter.h @@ -87,7 +87,7 @@ namespace itk { // friend to get access to executeInternal member friend struct detail::MemberFunctionAddressor; - std::auto_ptr > m_MemberFactory; + nsstd::auto_ptr > m_MemberFactory; }; diff --git a/Code/IO/include/sitkImageSeriesReader.h b/Code/IO/include/sitkImageSeriesReader.h index 63a9f6f82..6206d077d 100644 --- a/Code/IO/include/sitkImageSeriesReader.h +++ b/Code/IO/include/sitkImageSeriesReader.h @@ -118,7 +118,7 @@ namespace itk { // friend to get access to executeInternal member friend struct detail::MemberFunctionAddressor; - std::auto_ptr > m_MemberFactory; + nsstd::auto_ptr > m_MemberFactory; std::vector m_FileNames; }; diff --git a/Code/IO/include/sitkImageSeriesWriter.h b/Code/IO/include/sitkImageSeriesWriter.h index 9dacd07d4..00acc9ab6 100644 --- a/Code/IO/include/sitkImageSeriesWriter.h +++ b/Code/IO/include/sitkImageSeriesWriter.h @@ -84,7 +84,7 @@ namespace itk { // friend to get access to executeInternal member friend struct detail::MemberFunctionAddressor; - std::auto_ptr > m_MemberFactory; + nsstd::auto_ptr > m_MemberFactory; bool m_UseCompression; std::vector m_FileNames; diff --git a/Code/IO/include/sitkImportImageFilter.h b/Code/IO/include/sitkImportImageFilter.h index 53f57abf7..583a66c20 100644 --- a/Code/IO/include/sitkImportImageFilter.h +++ b/Code/IO/include/sitkImportImageFilter.h @@ -104,7 +104,7 @@ namespace itk { // friend to get access to executeInternal member friend struct detail::MemberFunctionAddressor; - std::auto_ptr > m_MemberFactory; + nsstd::auto_ptr > m_MemberFactory; unsigned int m_NumberOfComponentsPerPixel; PixelIDValueType m_PixelIDValue; diff --git a/Code/Registration/include/sitkImageRegistrationMethod.h b/Code/Registration/include/sitkImageRegistrationMethod.h index 19807883b..0f54f039d 100644 --- a/Code/Registration/include/sitkImageRegistrationMethod.h +++ b/Code/Registration/include/sitkImageRegistrationMethod.h @@ -589,8 +589,8 @@ namespace simple typedef Transform (ImageRegistrationMethod::*MemberFunctionType)( const Image &fixed, const Image &moving ); typedef double (ImageRegistrationMethod::*EvaluateMemberFunctionType)( const Image &fixed, const Image &moving ); friend struct detail::MemberFunctionAddressor; - std::auto_ptr > m_MemberFactory; - std::auto_ptr > m_EvaluateMemberFactory; + nsstd::auto_ptr > m_MemberFactory; + nsstd::auto_ptr > m_EvaluateMemberFactory; InterpolatorEnum m_Interpolator; Transform m_InitialTransform; diff --git a/TemplateComponents/MemberFunctionDispatch.h.in b/TemplateComponents/MemberFunctionDispatch.h.in index 87d4c94c3..2f303b5d0 100644 --- a/TemplateComponents/MemberFunctionDispatch.h.in +++ b/TemplateComponents/MemberFunctionDispatch.h.in @@ -2,4 +2,4 @@ $(if vector_pixel_types_by_component then OUT=[[ friend struct detail::ExecuteInternalVectorImageAddressor;]] end) - std::auto_ptr > m_MemberFactory; + nsstd::auto_ptr > m_MemberFactory; diff --git a/Testing/Unit/sitkCommonTests.cxx b/Testing/Unit/sitkCommonTests.cxx index f84970cd4..2cbba22aa 100644 --- a/Testing/Unit/sitkCommonTests.cxx +++ b/Testing/Unit/sitkCommonTests.cxx @@ -101,8 +101,8 @@ TEST( ProcessObject, Command_Register ) { // Case 1a: single command, command deleted first { - std::auto_ptr po1(new sitk::CastImageFilter()); - std::auto_ptr cmd(new sitk::Command()); + nsstd::auto_ptr po1(new sitk::CastImageFilter()); + nsstd::auto_ptr cmd(new sitk::Command()); po1->AddCommand(sitk::sitkAnyEvent, *cmd); EXPECT_TRUE(po1->HasCommand(sitk::sitkAnyEvent)); @@ -112,19 +112,19 @@ TEST( ProcessObject, Command_Register ) { // Case 1b: single command, process deleted first { - std::auto_ptr po1( new sitk::CastImageFilter()); - std::auto_ptr cmd(new sitk::Command()); + nsstd::auto_ptr po1( new sitk::CastImageFilter()); + nsstd::auto_ptr cmd(new sitk::Command()); po1->AddCommand(sitk::sitkAnyEvent, *cmd); po1.reset(); } // Case 2a: single command, multiple processes, command deleted first { - std::auto_ptr po1(new sitk::CastImageFilter()); - std::auto_ptr po2(new sitk::CastImageFilter()); - std::auto_ptr po3(new sitk::CastImageFilter()); + nsstd::auto_ptr po1(new sitk::CastImageFilter()); + nsstd::auto_ptr po2(new sitk::CastImageFilter()); + nsstd::auto_ptr po3(new sitk::CastImageFilter()); - std::auto_ptr cmd(new sitk::Command()); + nsstd::auto_ptr cmd(new sitk::Command()); po1->AddCommand(sitk::sitkAnyEvent, *cmd); po2->AddCommand(sitk::sitkStartEvent, *cmd); po3->AddCommand(sitk::sitkEndEvent, *cmd); @@ -133,11 +133,11 @@ TEST( ProcessObject, Command_Register ) { // Case 2b: single command, multiple processes, processes mostly deleted first { - std::auto_ptr po1(new sitk::CastImageFilter()); - std::auto_ptr po2(new sitk::CastImageFilter()); - std::auto_ptr po3(new sitk::CastImageFilter()); + nsstd::auto_ptr po1(new sitk::CastImageFilter()); + nsstd::auto_ptr po2(new sitk::CastImageFilter()); + nsstd::auto_ptr po3(new sitk::CastImageFilter()); - std::auto_ptr cmd(new sitk::Command()); + nsstd::auto_ptr cmd(new sitk::Command()); po1->AddCommand(sitk::sitkAnyEvent, *cmd); po2->AddCommand(sitk::sitkStartEvent, *cmd); po3->AddCommand(sitk::sitkEndEvent, *cmd); @@ -157,10 +157,10 @@ TEST( ProcessObject, Command_Register ) { // Case 3a: multiple commands, command deleted mostly first { - std::auto_ptr po1(new sitk::CastImageFilter()); - std::auto_ptr cmd1(new sitk::Command()); - std::auto_ptr cmd2(new sitk::Command()); - std::auto_ptr cmd3(new sitk::Command()); + nsstd::auto_ptr po1(new sitk::CastImageFilter()); + nsstd::auto_ptr cmd1(new sitk::Command()); + nsstd::auto_ptr cmd2(new sitk::Command()); + nsstd::auto_ptr cmd3(new sitk::Command()); po1->AddCommand(sitk::sitkAnyEvent, *cmd1); po1->AddCommand(sitk::sitkStartEvent, *cmd2); @@ -183,10 +183,10 @@ TEST( ProcessObject, Command_Register ) { // Case 3b: multiple commands, process object deleted first { - std::auto_ptr po1(new sitk::CastImageFilter()); - std::auto_ptr cmd1(new sitk::Command()); - std::auto_ptr cmd2(new sitk::Command()); - std::auto_ptr cmd3(new sitk::Command()); + nsstd::auto_ptr po1(new sitk::CastImageFilter()); + nsstd::auto_ptr cmd1(new sitk::Command()); + nsstd::auto_ptr cmd2(new sitk::Command()); + nsstd::auto_ptr cmd3(new sitk::Command()); po1->AddCommand(sitk::sitkAnyEvent, *cmd1); po1->AddCommand(sitk::sitkStartEvent, *cmd2); po1->AddCommand(sitk::sitkEndEvent, *cmd3); @@ -476,8 +476,8 @@ TEST( ProcessObject, Command_Ownership ) { // case 2 // cmd registered to multiple PO { - std::auto_ptr po1(new sitk::CastImageFilter()); - std::auto_ptr po2(new sitk::CastImageFilter()); + nsstd::auto_ptr po1(new sitk::CastImageFilter()); + nsstd::auto_ptr po2(new sitk::CastImageFilter()); HeapCommand *cmd = new HeapCommand(); cmd->OwnedByProcessObjectsOn(); diff --git a/Testing/Unit/sitkImage4DTests.cxx b/Testing/Unit/sitkImage4DTests.cxx index 37f48b2fd..5043f7f97 100644 --- a/Testing/Unit/sitkImage4DTests.cxx +++ b/Testing/Unit/sitkImage4DTests.cxx @@ -52,7 +52,7 @@ using itk::simple::InstantiatedPixelIDTypeList; class Image4D : public ::testing::Test { public: - typedef std::auto_ptr sitkAutoImagePointer; + typedef nsstd::auto_ptr sitkAutoImagePointer; virtual void SetUp() { itk::ImageBase<4>::IndexType index; diff --git a/Testing/Unit/sitkImageTests.cxx b/Testing/Unit/sitkImageTests.cxx index 7c6029e89..ae3502515 100644 --- a/Testing/Unit/sitkImageTests.cxx +++ b/Testing/Unit/sitkImageTests.cxx @@ -49,7 +49,7 @@ using itk::simple::InstantiatedPixelIDTypeList; class Image : public ::testing::Test { public: - typedef std::auto_ptr sitkAutoImagePointer; + typedef nsstd::auto_ptr sitkAutoImagePointer; virtual void SetUp() { itk::ImageBase<3>::IndexType index; diff --git a/Testing/Unit/sitkTransformTests.cxx b/Testing/Unit/sitkTransformTests.cxx index 72ea45a54..0a709c8cc 100644 --- a/Testing/Unit/sitkTransformTests.cxx +++ b/Testing/Unit/sitkTransformTests.cxx @@ -480,7 +480,7 @@ TEST(TransformTest,AffineTransform) const std::vector scale2d = v2(1,2); const std::vector scale3d = v3(1,1.2,1.3); - std::auto_ptr tx; + nsstd::auto_ptr tx; // 2d EXPECT_NO_THROW( tx.reset( new sitk::AffineTransform(2) ) ); @@ -622,7 +622,7 @@ TEST(TransformTest,BSplineTransform) { // test BSplineTransform - std::auto_ptr tx(new sitk::BSplineTransform(2)); + nsstd::auto_ptr tx(new sitk::BSplineTransform(2)); std::cout << tx->ToString() << std::endl; EXPECT_EQ( tx->GetParameters().size(), 32u ); EXPECT_EQ( tx->GetFixedParameters().size(), 10u ); @@ -700,7 +700,7 @@ TEST(TransformTest,BSplineTransform_order) EXPECT_THROW(sitk::BSplineTransform(3,4), sitk::GenericException); EXPECT_THROW(sitk::BSplineTransform(3,99), sitk::GenericException); - std::auto_ptr tx; + nsstd::auto_ptr tx; EXPECT_NO_THROW(tx.reset(new sitk::BSplineTransform(3))); EXPECT_EQ(3u, tx->GetOrder()); EXPECT_NO_THROW( tx.reset(new sitk::BSplineTransform(3,0))); @@ -741,7 +741,7 @@ TEST(TransformTest,DisplacementFieldTransform) const std::vector size(2,10u); const std::vector idx(2,1u); - std::auto_ptr tx(new sitk::DisplacementFieldTransform(2)); + nsstd::auto_ptr tx(new sitk::DisplacementFieldTransform(2)); std::cout << tx->ToString() << std::endl; EXPECT_EQ( tx->GetParameters().size(), 0u ); EXPECT_EQ( tx->GetFixedParameters().size(), 10u ); @@ -874,7 +874,7 @@ TEST(TransformTest,Euler2DTransform) const std::vector zeros(2,0.0); const std::vector trans(2, 2.2); - std::auto_ptr tx(new sitk::Euler2DTransform()); + nsstd::auto_ptr tx(new sitk::Euler2DTransform()); std::cout << tx->ToString() << std::endl; EXPECT_EQ( tx->GetParameters().size(), 3u ); EXPECT_EQ( tx->GetFixedParameters().size(), 2u ); @@ -1010,7 +1010,7 @@ TEST(TransformTest,Euler3DTransform) const unsigned int numberOfFixedParameters = numberOfFixedParameters; #endif - std::auto_ptr tx(new sitk::Euler3DTransform()); + nsstd::auto_ptr tx(new sitk::Euler3DTransform()); std::cout << tx->ToString() << std::endl; EXPECT_EQ( tx->GetParameters().size(), 6u ); EXPECT_EQ( tx->GetFixedParameters().size(), numberOfFixedParameters ); @@ -1149,7 +1149,7 @@ TEST(TransformTest,Similarity2DTransform) const std::vector zeros(2,0.0); const std::vector trans(2, 2.2); - std::auto_ptr tx(new sitk::Similarity2DTransform()); + nsstd::auto_ptr tx(new sitk::Similarity2DTransform()); std::cout << tx->ToString() << std::endl; EXPECT_EQ( tx->GetParameters().size(), 4u ); EXPECT_EQ( tx->GetFixedParameters().size(), 2u ); @@ -1267,7 +1267,7 @@ TEST(TransformTest,ScaleTransform) const std::vector zeros(3,0.0); - std::auto_ptr tx(new sitk::ScaleTransform(2)); + nsstd::auto_ptr tx(new sitk::ScaleTransform(2)); std::cout << tx->ToString() << std::endl; ASSERT_EQ( tx->GetParameters().size(), 2u ); ASSERT_EQ( tx->GetFixedParameters().size(), 2u ); @@ -1368,7 +1368,7 @@ TEST(TransformTest,ScaleSkewVersor3DTransform) const std::vector trans(3, 2.2); const std::vector skew(6,2.7); - std::auto_ptr tx(new sitk::ScaleSkewVersor3DTransform()); + nsstd::auto_ptr tx(new sitk::ScaleSkewVersor3DTransform()); std::cout << tx->ToString() << std::endl; EXPECT_EQ( tx->GetParameters().size(), 15u ); EXPECT_EQ( tx->GetFixedParameters().size(), 3u ); @@ -1496,7 +1496,7 @@ TEST(TransformTest,ScaleVersor3DTransform) const std::vector zeros(3,0.0); const std::vector trans(3, 2.2); - std::auto_ptr tx(new sitk::ScaleVersor3DTransform()); + nsstd::auto_ptr tx(new sitk::ScaleVersor3DTransform()); EXPECT_EQ( tx->GetParameters().size(), 9u ); EXPECT_EQ( tx->GetFixedParameters().size(), 3u ); EXPECT_EQ( tx->GetTranslation(), v3(0.0,0.0,0.0) ); @@ -1665,7 +1665,7 @@ TEST(TransformTest,Similarity3DTransform) const std::vector zeros(3,0.0); const std::vector trans(3, 2.2); - std::auto_ptr tx(new sitk::Similarity3DTransform()); + nsstd::auto_ptr tx(new sitk::Similarity3DTransform()); std::cout << tx->ToString() << std::endl; EXPECT_EQ( tx->GetParameters().size(), 7u ); EXPECT_EQ( tx->GetFixedParameters().size(), 3u ); @@ -1816,7 +1816,7 @@ TEST(TransformTest,TranslationTransform) const std::vector trans2d(2, 2.2); const std::vector trans3d(3, 3.3); - std::auto_ptr tx; + nsstd::auto_ptr tx; EXPECT_NO_THROW( tx.reset( new sitk::TranslationTransform(2) ) ); std::cout << tx->ToString() << std::endl; @@ -1880,7 +1880,7 @@ TEST(TransformTest,VersorRigid3DTransform) const std::vector zeros(3,0.0); const std::vector trans(3, 2.2); - std::auto_ptr tx(new sitk::VersorRigid3DTransform()); + nsstd::auto_ptr tx(new sitk::VersorRigid3DTransform()); std::cout << tx->ToString() << std::endl; EXPECT_EQ( tx->GetParameters().size(), 6u ); EXPECT_EQ( tx->GetFixedParameters().size(), 3u ); @@ -2038,7 +2038,7 @@ TEST(TransformTest,VersorTransform) const std::vector zeros(3,0.0); const std::vector trans(3, 2.2); - std::auto_ptr tx(new sitk::VersorTransform()); + nsstd::auto_ptr tx(new sitk::VersorTransform()); std::cout << tx->ToString() << std::endl; EXPECT_EQ( tx->GetParameters().size(), 3u ); EXPECT_EQ( tx->GetFixedParameters().size(), 3u ); From 23c641e309886678d3f394192b843205482c9210 Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Thu, 21 Jul 2016 23:00:18 +1000 Subject: [PATCH 356/412] Improvements to Rd file generation The usages for the procedural interface have been combined into a single usage section - the previous strategy of multiple usage sections is not legal in R documentation. The class documentation is now based around the recommended style for S4 classes. This is not a perfect match for the wrapping style, but better than previously. It now has a methods section which is used to document c++ methods. There are very few errors/warnings when creating the package. Those remaining - AntiAliasBinaryImageFilter - come from the latex maths messing up the markup. Change-Id: Iabd221e2c3a55dae4454113e7089a2a0a4bcf9b3 --- Utilities/GenerateDocs/doxy2swig.py | 21 ++++++++++++++++----- Utilities/GenerateDocs/doxyall.py | 11 ++++++++++- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/Utilities/GenerateDocs/doxy2swig.py b/Utilities/GenerateDocs/doxy2swig.py index 84cc78ba0..291a71548 100755 --- a/Utilities/GenerateDocs/doxy2swig.py +++ b/Utilities/GenerateDocs/doxy2swig.py @@ -438,6 +438,7 @@ def do_compoundname(self, node): self.add_text('\n\n') data = node.firstChild.data self.add_text('\\name{%s}\n'%data) + self.add_text('\\Rdversion{1.1}\n\\docType{class}\n') self.sitkClassName=data def do_compounddef(self, node): @@ -542,7 +543,7 @@ def do_memberdef(self, node): else: returnType = returnType.firstChild.nodeValue - self.add_text('%s %s%s'%(returnType, name, arguments)) + self.add_text('%s %s%s:}{'%(returnType, name, arguments)) for n in node.childNodes: if n not in list(first.values()): @@ -553,9 +554,9 @@ def do_memberdef(self, node): def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func'): - self.add_text('\\arguments{\n') + self.add_text('\\section{Methods}{\n\describe{') self.generic_parse(node) - self.add_text('}\n') + self.add_text('}\n}\n') def do_doxygenindex(self, node): self.multi = 1 @@ -587,6 +588,7 @@ def __init__(self, src, javaFlag=0): self.EmptyText = False self.piecesdict = dict() self.currentFunc='' + self.Usage=dict() def parse_Text(self, node): txt = node.data @@ -679,20 +681,29 @@ def do_memberdef(self, node): self.add_text('\n}\n\n') # now the potentially repeated bits (overloading) + # Rd doesn't allow multiple usage statements, so + # collect them usage=defn + argstring - self.add_text('\\usage{\n%s\n}\n' %(usage)) + if not name in self.Usage: + self.Usage[self.currentname]="" + + self.Usage[self.currentname] = self.Usage[self.currentname] + '\n\n' + usage def do_sectiondef(self, node): kind = node.attributes['kind'].value if kind in ('public-func', 'func'): self.generic_parse(node) - def write(self, fname, mode='w'): ## fname is the destination folder if os.path.isdir(fname): for FuncName in self.piecesdict: outname=os.path.join(fname, FuncName + ".Rd") + ## add the usage to the end + if FuncName in self.Usage: + self.currentname=FuncName + usage = '\\usage{\n%s\n}\n' % self.Usage[FuncName] + self.add_text(usage) self.pieces = self.piecesdict[FuncName] Doxy2SWIG.write(self,outname) else: diff --git a/Utilities/GenerateDocs/doxyall.py b/Utilities/GenerateDocs/doxyall.py index 51ebba187..7cc028fc6 100755 --- a/Utilities/GenerateDocs/doxyall.py +++ b/Utilities/GenerateDocs/doxyall.py @@ -87,6 +87,9 @@ def usage(): ThisClassName = ThisClassName.replace("itk::simple::", "") ThisClassName = ThisClassName.replace("itk::Functor::", "") + ## Get rid of the ITK classes + if ThisClassName.find("itk::") >=0 or ThisClassName.find("<") >=0: + continue outfile=outdir + "/" + ThisClassName + ".Rd" fout = open(outfile, "w") @@ -96,8 +99,14 @@ def usage(): fin = open(tmpfile, "r") for line in fin: - line2 = line.replace("itk::simple::detail::", "itk::simple::") + if (rFlag): + line2 = line.replace("itk::simple::detail::", "") + line2 = line.replace("itk::simple::", "") + else: + line2 = line.replace("itk::simple::detail::", "itk::simple::") line2 = line2.rstrip() + if line in ('\n', '\r\n'): + continue fout.write(line2) fout.write('\n') if (rFlag): From bd25dd2aebb62d1456b75936f27ca0bf6bec1740 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 21 Jul 2016 10:26:20 -0400 Subject: [PATCH 357/412] Adding alias for nsstd namespace in testing Change-Id: Ia4f9f151dfb254611bc8b0931b8780a2ae2b29ef --- Testing/Unit/sitkCommonTests.cxx | 2 ++ Testing/Unit/sitkImageTests.cxx | 2 ++ Testing/Unit/sitkTransformTests.cxx | 1 + 3 files changed, 5 insertions(+) diff --git a/Testing/Unit/sitkCommonTests.cxx b/Testing/Unit/sitkCommonTests.cxx index 2cbba22aa..a2e4efbbd 100644 --- a/Testing/Unit/sitkCommonTests.cxx +++ b/Testing/Unit/sitkCommonTests.cxx @@ -24,6 +24,8 @@ #include +namespace nsstd = itk::simple::nsstd; + TEST( ConditionalTest, ConditionalTest1 ) { // a quick check to make sure the conditional works diff --git a/Testing/Unit/sitkImageTests.cxx b/Testing/Unit/sitkImageTests.cxx index ae3502515..f234710b8 100644 --- a/Testing/Unit/sitkImageTests.cxx +++ b/Testing/Unit/sitkImageTests.cxx @@ -45,6 +45,8 @@ const double adir[] = {0.0, 0.0, 1.0, 0.0, -1.0, 0.0}; using itk::simple::InstantiatedPixelIDTypeList; +namespace nsstd = itk::simple::nsstd; + class Image : public ::testing::Test { diff --git a/Testing/Unit/sitkTransformTests.cxx b/Testing/Unit/sitkTransformTests.cxx index 0a709c8cc..0a62b5003 100644 --- a/Testing/Unit/sitkTransformTests.cxx +++ b/Testing/Unit/sitkTransformTests.cxx @@ -39,6 +39,7 @@ #include "itkMath.h" namespace sitk = itk::simple; +namespace nsstd = itk::simple::nsstd; TEST(TransformTest, Construction) { From 2a6e885b40a9b47e8dee73209bed3d71ec1f66c0 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 21 Jul 2016 14:57:50 -0400 Subject: [PATCH 358/412] Update the Swig docs from generation scripts Change-Id: I723595751f63523fc198c5c21e24092ff238c501 --- Wrapping/Java/JavaDoc.i | 25 ++++++++++++++++++++++++- Wrapping/Python/PythonDocstrings.i | 21 ++++++++++++++++++++- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/Wrapping/Java/JavaDoc.i b/Wrapping/Java/JavaDoc.i index ec1e66bde..d757cc23c 100644 --- a/Wrapping/Java/JavaDoc.i +++ b/Wrapping/Java/JavaDoc.i @@ -18681,7 +18681,7 @@ Copy common meta-data from an image to this one. Copies the Origin, Spacing, and Direction from the source image to -this image. +this image. The meta-data dictionary is not copied. It is required for the source Image's dimension and size to match, this image's attributes, otherwise an exception will be generated. @@ -18689,6 +18689,18 @@ exception will be generated. */ public "; +%javamethodmodifiers itk::simple::Image::EraseMetaData "/** +bool itk::simple::Image::EraseMetaData(const std::string &key) + +Remove an entry from the meta-data dictionary. + + +Returns true, when the value exists in the dictionary and is removed, +false otherwise. + +*/ +public "; + %javamethodmodifiers itk::simple::Image::GetDepth "/** unsigned int itk::simple::Image::GetDepth(void) const */ @@ -18800,6 +18812,17 @@ make sure that coping actually happens to the itk::Image pointed to is only poin */ public "; +%javamethodmodifiers itk::simple::Image::SetMetaData "/** +void itk::simple::Image::SetMetaData(const std::string &key, const std::string &value) + +Set an entry in the meta-data dictionary. + + +Replaces or creates an entry in the image's meta-data dictionary. + +*/ +public "; + %javamethodmodifiers itk::simple::Image::ToString "/** std::string itk::simple::Image::ToString(void) const */ diff --git a/Wrapping/Python/PythonDocstrings.i b/Wrapping/Python/PythonDocstrings.i index c8da50afb..fb0578733 100644 --- a/Wrapping/Python/PythonDocstrings.i +++ b/Wrapping/Python/PythonDocstrings.i @@ -14983,13 +14983,23 @@ Copy common meta-data from an image to this one. Copies the Origin, Spacing, and Direction from the source image to -this image. +this image. The meta-data dictionary is not copied. It is required for the source Image's dimension and size to match, this image's attributes, otherwise an exception will be generated. "; +%feature("docstring") itk::simple::Image::EraseMetaData " + +Remove an entry from the meta-data dictionary. + + +Returns true, when the value exists in the dictionary and is removed, +false otherwise. + +"; + %feature("docstring") itk::simple::Image::GetDepth " "; @@ -15071,6 +15081,15 @@ make sure that coping actually happens to the itk::Image pointed to is only poin "; +%feature("docstring") itk::simple::Image::SetMetaData " + +Set an entry in the meta-data dictionary. + + +Replaces or creates an entry in the image's meta-data dictionary. + +"; + %feature("docstring") itk::simple::Image::ToString " "; From c90cffd32a5ec6026733967408efbddbfd2512a4 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Thu, 21 Jul 2016 15:16:16 -0400 Subject: [PATCH 359/412] Update to use python from future for py3 compatibility Change-Id: I0ebf8bdb771971fa6dc6f640b950db61eb274da5 --- Utilities/CSVtoTable.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Utilities/CSVtoTable.py b/Utilities/CSVtoTable.py index cdf657a7b..c15da0d7f 100755 --- a/Utilities/CSVtoTable.py +++ b/Utilities/CSVtoTable.py @@ -16,7 +16,7 @@ # limitations under the License. # #========================================================================= - +from __future__ import print_function import sys, csv, getopt, re import os, os.path @@ -33,12 +33,12 @@ class bcolors: def usage(): """How to use this script""" - print "" - print "CSVtoTable.py [options] [input_file [output_file]]" - print "" - print " -h This help message" - print " -d Make a Doxygen file" - print "" + print("") + print("CSVtoTable.py [options] [input_file [output_file]]") + print("") + print(" -h This help message") + print(" -d Make a Doxygen file") + print("") # Variables # @@ -56,8 +56,8 @@ def usage(): try: opts, args = getopt.getopt(sys.argv[1:], "hd", [ "help", "doxygen" ] ) -except getopt.GetoptError, err: - print str(err) +except getopt.GetoptError as err: + print(str(err)) usage() sys.exit(2) @@ -77,7 +77,7 @@ def usage(): outname = args[1] -print inname, outname +print( inname, outname ) # if outname includes a path that doesn't exist, create that path if not os.path.isdir( os.path.dirname( outname ) ): @@ -148,8 +148,8 @@ def usage(): outfile.write( "\n" ) except: - print "Failed to read input file ", inname - print sys.exc_info()[0] + print("Failed to read input file ", inname) + print(sys.exc_info()[0]) sys.exit(1) outfile.write( "\n" ) From 2c6f25948b359d5996b2b85ac03707abb3643d92 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Fri, 22 Jul 2016 09:00:16 -0400 Subject: [PATCH 360/412] Updated filter.csv Re-generated the filter table that compares SimpleITK's filters with ITK's. Change-Id: I186a2a4f38f4f089164c10a9964ad2869691cb73 --- Utilities/filters.csv | 288 ++++++++++++++++++++---------------------- 1 file changed, 140 insertions(+), 148 deletions(-) diff --git a/Utilities/filters.csv b/Utilities/filters.csv index 1bbeb5c71..ba7c8692c 100644 --- a/Utilities/filters.csv +++ b/Utilities/filters.csv @@ -1,26 +1,24 @@ Filter,ITK,SITK,Remark,ToDo AbsImageFilter,True,True,,False AbsoluteValueDifferenceImageFilter,True,True,,False -AccumulateImageFilter,True,False,Duplicate of Projection filters,False +AccumulateImageFilter,True,False,,False AcosImageFilter,True,True,,False -AdaptiveHistogramEqualizationImageFilter,True,True,,True +AdaptiveHistogramEqualizationImageFilter,True,True,,False AddImageFilter,True,True,,False AdditiveGaussianNoiseImageFilter,True,True,,False AndImageFilter,True,True,,False -AnisotropicDiffusionImageFilter,True,False,base class,False -AnisotropicFourthOrderLevelSetImageFilter,True,False,,True -AntiAliasBinaryImageFilter,True,True,,True +AnisotropicDiffusionImageFilter,True,False,,False +AnisotropicFourthOrderLevelSetImageFilter,True,False,,False +AntiAliasBinaryImageFilter,True,True,,False ApproximateSignedDistanceMapImageFilter,True,True,,False -AreaClosingImageFilter,True,False,,True -AreaOpeningImageFilter,True,False,,True AsinImageFilter,True,True,,False Atan2ImageFilter,True,True,,False AtanImageFilter,True,True,,False -BSplineDecompositionImageFilter,True,False,,True -BSplineDownsampleImageFilter,True,False,,True -BSplineUpsampleImageFilter,True,False,,True -BayesianClassifierImageFilter,True,False,,True -BayesianClassifierInitializationImageFilter,True,False,,True +BSplineDecompositionImageFilter,True,False,,False +BSplineDownsampleImageFilter,True,False,,False +BSplineUpsampleImageFilter,True,False,,False +BayesianClassifierImageFilter,True,False,,False +BayesianClassifierInitializationImageFilter,True,False,,False BilateralImageFilter,True,True,,False BinShrinkImageFilter,True,True,,False BinaryClosingByReconstructionImageFilter,True,True,,False @@ -34,36 +32,36 @@ BinaryMedianImageFilter,True,True,,False BinaryMinMaxCurvatureFlowImageFilter,True,True,,False BinaryMorphologicalClosingImageFilter,True,True,,False BinaryMorphologicalOpeningImageFilter,True,True,,False -BinaryNotImageFilter,True,True,,True +BinaryNotImageFilter,True,True,,False BinaryOpeningByReconstructionImageFilter,True,True,,False BinaryProjectionImageFilter,True,True,,False -BinaryPruningImageFilter,True,False,Check functionality in 3D,True +BinaryPruningImageFilter,True,False,,False BinaryReconstructionByDilationImageFilter,True,True,,False BinaryReconstructionByErosionImageFilter,True,True,,False -BinaryShapeKeepNObjectsImageFilter,True,False,,True -BinaryShapeOpeningImageFilter,True,False,,True -BinaryStatisticsKeepNObjectsImageFilter,True,False,,True -BinaryStatisticsOpeningImageFilter,True,False,,True +BinaryShapeKeepNObjectsImageFilter,True,False,,False +BinaryShapeOpeningImageFilter,True,False,,False +BinaryStatisticsKeepNObjectsImageFilter,True,False,,False +BinaryStatisticsOpeningImageFilter,True,False,,False BinaryThinningImageFilter,True,True,,False BinaryThresholdImageFilter,True,True,,False -BinaryThresholdProjectionImageFilter,True,True,,True +BinaryThresholdProjectionImageFilter,True,True,,False BinomialBlurImageFilter,True,True,,False BitwiseNotImageFilter,False,True,,False BlackTopHatImageFilter,True,True,,False BlockMatchingImageFilter,True,False,,False BoundedReciprocalImageFilter,True,True,,False -BoxImageFilter,True,False,base class,False -BoxMeanImageFilter,True,True,,False -BoxSigmaImageFilter,True,True,,False +BoxImageFilter,True,False,,False +BoxMeanImageFilter,False,True,,False +BoxSigmaImageFilter,False,True,,False CannyEdgeDetectionImageFilter,True,True,,False -CannySegmentationLevelSetImageFilter,True,False,This filter has a large number of parameters,True +CannySegmentationLevelSetImageFilter,True,False,,False CastImageFilter,True,True,,False -ChangeInformationImageFilter,True,False,No need for a filter to do this in SimpleITK,False -ChangeLabelImageFilter,True,True,,True +ChangeInformationImageFilter,True,False,,False +ChangeLabelImageFilter,True,True,,False CheckerBoardImageFilter,True,True,,False -ClampImageFilter,True,True,,True +ClampImageFilter,True,True,,False ClosingByReconstructionImageFilter,True,True,,False -CollidingFrontsImageFilter,True,True,,True +CollidingFrontsImageFilter,True,True,,False ComparisonImageFilter,True,False,,False ComplexToComplexFFTImageFilter,True,False,,False ComplexToImaginaryImageFilter,True,True,,False @@ -75,53 +73,51 @@ ConfidenceConnectedImageFilter,True,True,,False ConnectedComponentImageFilter,True,True,,False ConnectedThresholdImageFilter,True,True,,False ConstantPadImageFilter,True,True,,False -ConstrainedValueAdditionImageFilter,True,False,,True -ConstrainedValueDifferenceImageFilter,True,False,,True -ContourDirectedMeanDistanceImageFilter,True,False,,True -ContourExtractor2DImageFilter,True,False,,True -ContourMeanDistanceImageFilter,True,False,,True +ConstrainedValueAdditionImageFilter,True,False,,False +ConstrainedValueDifferenceImageFilter,True,False,,False +ContourDirectedMeanDistanceImageFilter,True,False,,False +ContourMeanDistanceImageFilter,True,False,,False ConvolutionImageFilter,True,True,,False CosImageFilter,True,True,,False CropImageFilter,True,True,,False CurvatureAnisotropicDiffusionImageFilter,True,True,,False CurvatureFlowImageFilter,True,True,,False -CurvesLevelSetImageFilter,True,False,,True -CyclicShiftImageFilter,True,True,,True +CurvesLevelSetImageFilter,True,False,,False +CyclicShiftImageFilter,True,True,,False DanielssonDistanceMapImageFilter,True,True,,False -DenseFiniteDifferenceImageFilter,True,False,base class,False +DenseFiniteDifferenceImageFilter,True,False,,False DerivativeImageFilter,True,True,,False -DifferenceOfGaussiansGradientImageFilter,True,False,,True +DifferenceOfGaussiansGradientImageFilter,True,False,,False DilateObjectMorphologyImageFilter,True,True,,False -DirectFourierReconstructionImageToImageFilter,True,False,,True -DirectedHausdorffDistanceImageFilter,True,False,,True -DiscreteGaussianDerivativeImageFilter,True,True,,True +DirectedHausdorffDistanceImageFilter,True,False,,False +DiscreteGaussianDerivativeImageFilter,False,True,,False DiscreteGaussianImageFilter,True,True,,False DivideFloorImageFilter,False,True,,False DivideImageFilter,True,True,,False DivideRealImageFilter,False,True,,False DoubleThresholdImageFilter,True,True,,False EdgePotentialImageFilter,True,True,,False -EigenAnalysis2DImageFilter,True,False,,True +EigenAnalysis2DImageFilter,True,False,,False EqualImageFilter,False,True,,False ErodeObjectMorphologyImageFilter,True,True,,False ExpImageFilter,True,True,,False ExpNegativeImageFilter,True,True,,False -ExpandImageFilter,True,True,,True +ExpandImageFilter,True,True,,False ExtractImageFilter,True,True,,False FFTConvolutionImageFilter,True,True,,False -FFTNormalizedCorrelationImageFilter,False,True,,False -FFTPadImageFilter,True,False,,False +FFTNormalizedCorrelationImageFilter,True,True,,False +FFTPadImageFilter,True,True,,False FFTShiftImageFilter,True,True,,False -FastApproximateRankImageFilter,True,True,,True -FastChamferDistanceImageFilter,True,False,,True +FastApproximateRankImageFilter,False,True,,False +FastChamferDistanceImageFilter,True,False,,False FastMarchingBaseImageFilter,False,True,,False -FastMarchingExtensionImageFilter,True,False,,True +FastMarchingExtensionImageFilter,True,False,,False FastMarchingImageFilter,True,True,,False -FastMarchingUpwindGradientImageFilter,True,True,,True -FiniteDifferenceImageFilter,True,False,base class,False +FastMarchingUpwindGradientImageFilter,True,True,,False +FiniteDifferenceImageFilter,True,False,,False FlipImageFilter,True,True,,False ForwardFFTImageFilter,True,True,,False -FullToHalfHermitianImageFilter,True,False,,True +FullToHalfHermitianImageFilter,True,False,,False GaborImageSource,True,False,,False GaussianImageSource,True,False,,False GenerateImageSource,True,False,,False @@ -129,17 +125,17 @@ GeodesicActiveContourLevelSetImageFilter,True,True,,False GeodesicActiveContourShapePriorLevelSetImageFilter,True,False,,False GradientAnisotropicDiffusionImageFilter,True,True,,False GradientImageFilter,True,True,,False -GradientMagnitudeImageFilter,True,True,,True +GradientMagnitudeImageFilter,True,True,,False GradientMagnitudeRecursiveGaussianImageFilter,True,True,,False -GradientRecursiveGaussianImageFilter,True,True,,True -GradientVectorFlowImageFilter,True,False,,True -GrayscaleConnectedClosingImageFilter,True,True,,True -GrayscaleConnectedOpeningImageFilter,True,True,,True +GradientRecursiveGaussianImageFilter,True,True,,False +GradientVectorFlowImageFilter,True,False,,False +GrayscaleConnectedClosingImageFilter,True,True,,False +GrayscaleConnectedOpeningImageFilter,True,True,,False GrayscaleDilateImageFilter,True,True,,False GrayscaleErodeImageFilter,True,True,,False GrayscaleFillholeImageFilter,True,True,,False -GrayscaleFunctionDilateImageFilter,True,False,,True -GrayscaleFunctionErodeImageFilter,True,False,,True +GrayscaleFunctionDilateImageFilter,True,False,,False +GrayscaleFunctionErodeImageFilter,True,False,,False GrayscaleGeodesicDilateImageFilter,True,True,,False GrayscaleGeodesicErodeImageFilter,True,True,,False GrayscaleGrindPeakImageFilter,True,True,,False @@ -147,35 +143,33 @@ GrayscaleMorphologicalClosingImageFilter,True,True,,False GrayscaleMorphologicalOpeningImageFilter,True,True,,False GreaterEqualImageFilter,False,True,,False GreaterImageFilter,False,True,,False -GridForwardWarpImageFilter,True,False,,True GridImageSource,True,False,,False HConcaveImageFilter,True,True,,False HConvexImageFilter,True,True,,False HMaximaImageFilter,True,True,,False HMinimaImageFilter,True,True,,False -HalfHermitianToRealInverseFFTImageFilter,True,True,,True -HalfToFullHermitianImageFilter,True,False,,True -HardConnectedComponentImageFilter,True,False,,True +HalfHermitianToRealInverseFFTImageFilter,True,True,,False +HalfToFullHermitianImageFilter,True,False,,False +HardConnectedComponentImageFilter,True,False,,False HashImageFilter,False,True,,False HausdorffDistanceImageFilter,True,True,,False -Hessian3DToVesselnessMeasureImageFilter,True,False,,True -HessianRecursiveGaussianImageFilter,True,False,,True -HessianToObjectnessMeasureImageFilter,True,False,,True +Hessian3DToVesselnessMeasureImageFilter,True,False,,False +HessianRecursiveGaussianImageFilter,True,False,,False HistogramMatchingImageFilter,True,True,,False -HistogramThresholdImageFilter,True,False,base class,False -HistogramToEntropyImageFilter,True,False,Requires ITK histogram,False -HistogramToIntensityImageFilter,True,False,Requires ITK histogram,False -HistogramToLogProbabilityImageFilter,True,False,Requires ITK histogram,False -HistogramToProbabilityImageFilter,True,False,Requires ITK histogram,False -HoughTransform2DCirclesImageFilter,True,False,A solution is needed for the spacial object output,False -HoughTransform2DLinesImageFilter,True,False,A solution is needed for the spacial object output,False +HistogramThresholdImageFilter,True,False,,False +HistogramToEntropyImageFilter,True,False,,False +HistogramToIntensityImageFilter,True,False,,False +HistogramToLogProbabilityImageFilter,True,False,,False +HistogramToProbabilityImageFilter,True,False,,False +HoughTransform2DCirclesImageFilter,True,False,,False +HoughTransform2DLinesImageFilter,True,False,,False HuangThresholdImageFilter,True,True,,False -ImageToImageFilter,True,False,base class,False -ImportImageFilter,True,False,Currently manually implemented in SimpleITK,False -InPlaceImageFilter,True,False,base class,False +ImageToImageFilter,True,False,,False +ImportImageFilter,True,False,,False +InPlaceImageFilter,True,False,,False IntensityWindowingImageFilter,True,True,,False IntermodesThresholdImageFilter,True,True,,False -InterpolateImageFilter,True,False,,True +InterpolateImageFilter,True,False,,False InverseDeconvolutionImageFilter,True,True,,False InverseDisplacementFieldImageFilter,False,True,,False InverseFFTImageFilter,True,True,,False @@ -185,15 +179,15 @@ IsoContourDistanceImageFilter,True,True,,False IsoDataThresholdImageFilter,True,True,,False IsolatedConnectedImageFilter,True,True,,False IsolatedWatershedImageFilter,True,True,,False -IsotropicFourthOrderLevelSetImageFilter,True,False,,True +IsotropicFourthOrderLevelSetImageFilter,True,False,,False IterativeDeconvolutionImageFilter,True,False,,False JoinSeriesImageFilter,True,True,,False -KappaSigmaThresholdImageFilter,True,False,,True -KernelImageFilter,True,False,base class?,False +KappaSigmaThresholdImageFilter,True,False,,False +KernelImageFilter,True,False,,False KittlerIllingworthThresholdImageFilter,True,True,,False LabelContourImageFilter,True,True,,False -LabelGeometryImageFilter,True,False,Duplicate with LabelMaps?,False -LabelMapContourOverlayImageFilter,True,True,,True +LabelIntensityStatisticsImageFilter,False,True,,False +LabelMapContourOverlayImageFilter,True,True,,False LabelMapMaskImageFilter,True,True,,False LabelMapOverlayImageFilter,True,True,,False LabelMapToBinaryImageFilter,True,True,,False @@ -201,14 +195,14 @@ LabelMapToLabelImageFilter,True,True,,False LabelMapToRGBImageFilter,True,True,,False LabelOverlapMeasuresImageFilter,False,True,,False LabelOverlayImageFilter,True,True,,False -LabelShapeKeepNObjectsImageFilter,True,False,,True -LabelShapeOpeningImageFilter,True,False,,True +LabelShapeKeepNObjectsImageFilter,True,False,,False +LabelShapeOpeningImageFilter,True,False,,False LabelShapeStatisticsImageFilter,False,True,,False LabelStatisticsImageFilter,True,True,,False -LabelStatisticsKeepNObjectsImageFilter,True,False,,True -LabelStatisticsOpeningImageFilter,True,False,,True +LabelStatisticsKeepNObjectsImageFilter,True,False,,False +LabelStatisticsOpeningImageFilter,True,False,,False LabelToRGBImageFilter,True,True,,False -LabelVotingImageFilter,True,True,,True +LabelVotingImageFilter,True,True,,False LandweberDeconvolutionImageFilter,True,True,,False LaplacianImageFilter,True,True,,False LaplacianRecursiveGaussianImageFilter,True,True,,False @@ -223,7 +217,6 @@ MagnitudeAndPhaseToComplexImageFilter,True,True,,False MaskImageFilter,True,True,,False MaskNegatedImageFilter,True,True,,False MaskedFFTNormalizedCorrelationImageFilter,True,True,,False -MaskedRankImageFilter,True,False,,True MaximumEntropyThresholdImageFilter,True,True,,False MaximumImageFilter,True,True,,False MaximumProjectionImageFilter,True,True,,False @@ -239,17 +232,18 @@ MirrorPadImageFilter,True,True,,False ModulusImageFilter,True,True,,False MomentsThresholdImageFilter,True,True,,False MorphologicalGradientImageFilter,True,True,,False -MorphologicalWatershedFromMarkersImageFilter,True,True,,True -MorphologicalWatershedImageFilter,True,True,,True -MultiResolutionPyramidImageFilter,True,False,How can the multiple output be delt with?,False -MultiScaleHessianBasedMeasureImageFilter,True,False,,False +MorphologicalWatershedFromMarkersImageFilter,False,True,,False +MorphologicalWatershedImageFilter,False,True,,False +MovingHistogramImageFilter,True,False,,False +MultiLabelSTAPLEImageFilter,False,True,,False +MultiResolutionPyramidImageFilter,True,False,,False MultiplyImageFilter,True,True,,False N4BiasFieldCorrectionImageFilter,False,True,,False -NarrowBandCurvesLevelSetImageFilter,True,False,,True -NarrowBandLevelSetImageFilter,True,False,,True -NarrowBandThresholdSegmentationLevelSetImageFilter,True,False,,True -NaryAddImageFilter,True,True,,True -NaryMaximumImageFilter,True,True,,True +NarrowBandCurvesLevelSetImageFilter,True,False,,False +NarrowBandLevelSetImageFilter,True,False,,False +NarrowBandThresholdSegmentationLevelSetImageFilter,True,False,,False +NaryAddImageFilter,True,True,,False +NaryMaximumImageFilter,True,True,,False NeighborhoodConnectedImageFilter,True,True,,False NoiseBaseImageFilter,True,False,,False NoiseImageFilter,True,True,,False @@ -260,77 +254,75 @@ NotEqualImageFilter,False,True,,False NotImageFilter,True,True,,False OpeningByReconstructionImageFilter,True,True,,False OrImageFilter,True,True,,False -OrientImageFilter,True,False,,True -OtsuMultipleThresholdsImageFilter,True,True,,True +OrientImageFilter,True,False,,False +OtsuMultipleThresholdsImageFilter,True,True,,False OtsuThresholdImageFilter,True,True,,False -PadImageFilter,True,False,,True -ParallelSparseFieldLevelSetImageFilter,True,False,base class,False +PadImageFilter,True,False,,False +ParallelSparseFieldLevelSetImageFilter,True,False,,False ParametricImageSource,True,False,,False PasteImageFilter,True,True,,False PatchBasedDenoisingImageFilter,False,True,,False PermuteAxesImageFilter,True,True,,False PhysicalPointImageSource,True,False,,False +PipelineMonitorImageFilter,True,False,,False PowImageFilter,True,True,,False ProjectedLandweberDeconvolutionImageFilter,True,True,,False PyImageFilter,True,False,,False -RGBToLuminanceImageFilter,True,False,,True -RandomImageSource,True,False,in itk::Testing namespace,False -RankImageFilter,True,True,,True +RGBToLuminanceImageFilter,True,False,,False +RandomImageSource,True,False,,False +RankImageFilter,False,True,,False RealAndImaginaryToComplexImageFilter,False,True,,False -RealToHalfHermitianForwardFFTImageFilter,True,True,,True -ReconstructionByDilationImageFilter,True,True,,True -ReconstructionByErosionImageFilter,True,True,,True +RealToHalfHermitianForwardFFTImageFilter,True,True,,False +ReconstructionByDilationImageFilter,True,True,,False +ReconstructionByErosionImageFilter,True,True,,False RecursiveGaussianImageFilter,True,True,,False -RecursiveMultiResolutionPyramidImageFilter,True,False,How can the multiple output be delt with?,False -RecursiveSeparableImageFilter,True,False,base class,False +RecursiveMultiResolutionPyramidImageFilter,True,False,,False +RecursiveSeparableImageFilter,True,False,,False RegionOfInterestImageFilter,True,True,,False -RegionalMaximaImageFilter,True,True,,True -RegionalMinimaImageFilter,True,True,,True -ReinitializeLevelSetImageFilter,True,False,,True +RegionalMaximaImageFilter,False,True,,False +RegionalMinimaImageFilter,False,True,,False +ReinitializeLevelSetImageFilter,True,False,,False RelabelComponentImageFilter,True,True,,False RenyiEntropyThresholdImageFilter,True,True,,False ResampleImageFilter,True,True,,False RescaleIntensityImageFilter,True,True,,False RichardsonLucyDeconvolutionImageFilter,True,True,,False -RobustAutomaticThresholdImageFilter,True,False,,True RoundImageFilter,True,False,,False -STAPLEImageFilter,True,True,,True +STAPLEImageFilter,True,True,,False SaltAndPepperNoiseImageFilter,True,True,,False -ScalarChanAndVeseDenseLevelSetImageFilter,True,True,,True -ScalarChanAndVeseSparseLevelSetImageFilter,True,False,,True +ScalarChanAndVeseDenseLevelSetImageFilter,False,True,,False ScalarConnectedComponentImageFilter,True,True,,False ScalarImageKmeansImageFilter,True,True,,False ScalarToRGBColormapImageFilter,True,True,,False -SegmentationLevelSetImageFilter,True,False,base class?,False +SegmentationLevelSetImageFilter,True,False,,False ShanbhagThresholdImageFilter,True,True,,False ShapeDetectionLevelSetImageFilter,True,True,,False -ShapePriorSegmentationLevelSetImageFilter,True,False,,True -ShapeRelabelImageFilter,True,False,,True +ShapePriorSegmentationLevelSetImageFilter,True,False,,False +ShapeRelabelImageFilter,True,False,,False ShiftScaleImageFilter,True,True,,False ShotNoiseImageFilter,True,True,,False ShrinkImageFilter,True,True,,False SigmoidImageFilter,True,True,,False SignedDanielssonDistanceMapImageFilter,True,True,,False SignedMaurerDistanceMapImageFilter,True,True,,False -SimilarityIndexImageFilter,True,True,,True +SimilarityIndexImageFilter,True,True,,False SimpleContourExtractorImageFilter,True,True,,False SinImageFilter,True,True,,False -SliceBySliceImageFilter,True,False,This is for pipelines,False +SliceBySliceImageFilter,True,False,,False SliceImageFilter,False,True,,False SmoothingRecursiveGaussianImageFilter,True,True,,False SobelEdgeDetectionImageFilter,True,True,,False -SparseFieldFourthOrderLevelSetImageFilter,True,False,,True -SparseFieldLevelSetImageFilter,True,False,base class?,False -SpatialObjectToImageFilter,True,False,A solution is needed for spacial object input,False +SparseFieldFourthOrderLevelSetImageFilter,True,False,,False +SparseFieldLevelSetImageFilter,True,False,,False +SpatialObjectToImageFilter,True,False,,False SpeckleNoiseImageFilter,True,True,,False SqrtImageFilter,True,True,,False SquareImageFilter,True,True,,False SquaredDifferenceImageFilter,True,True,,False StandardDeviationProjectionImageFilter,True,True,,False StatisticsImageFilter,True,True,,False -StatisticsRelabelImageFilter,True,False,,True -StochasticFractalDimensionImageFilter,True,False,,True -StreamingImageFilter,True,False,This is for pipelines,False +StatisticsRelabelImageFilter,True,False,,False +StreamingImageFilter,True,False,,False SubtractImageFilter,True,True,,False SumProjectionImageFilter,True,True,,False TanImageFilter,True,True,,False @@ -338,41 +330,41 @@ TernaryAddImageFilter,True,True,,False TernaryMagnitudeImageFilter,True,True,,False TernaryMagnitudeSquaredImageFilter,True,True,,False ThresholdImageFilter,True,True,,False -ThresholdLabelerImageFilter,True,False,,True +ThresholdLabelerImageFilter,True,False,,False ThresholdMaximumConnectedComponentsImageFilter,True,True,,False ThresholdSegmentationLevelSetImageFilter,True,True,,False TikhonovDeconvolutionImageFilter,True,True,,False -TileImageFilter,True,True,,True -TobogganImageFilter,True,False,,True +TileImageFilter,True,True,,False +TobogganImageFilter,True,False,,False TriangleThresholdImageFilter,True,True,,False UnaryMinusImageFilter,False,True,,False -UnsharpMaskLevelSetImageFilter,True,False,,True -ValuedRegionalMaximaImageFilter,True,True,,True -ValuedRegionalMinimaImageFilter,True,True,,True -VectorCastImageFilter,True,False,Already integrated into the Cast image filter,False -VectorConfidenceConnectedImageFilter,True,True,,True +UnsharpMaskLevelSetImageFilter,True,False,,False +ValuedRegionalMaximaImageFilter,False,True,,False +ValuedRegionalMinimaImageFilter,False,True,,False +VectorCastImageFilter,True,False,,False +VectorConfidenceConnectedImageFilter,True,True,,False VectorConnectedComponentImageFilter,True,True,,False -VectorCurvatureAnisotropicDiffusionImageFilter,True,False,,True -VectorExpandImageFilter,True,False,,True -VectorGradientAnisotropicDiffusionImageFilter,True,False,,True -VectorGradientMagnitudeImageFilter,True,False,,True +VectorCurvatureAnisotropicDiffusionImageFilter,True,False,,False +VectorExpandImageFilter,True,False,,False +VectorGradientAnisotropicDiffusionImageFilter,True,False,,False +VectorGradientMagnitudeImageFilter,True,False,,False VectorIndexSelectionCastImageFilter,True,True,,False VectorMagnitudeImageFilter,True,True,,False -VectorResampleImageFilter,True,False,Same functionality exists in ResampleImageFilter,False -VectorRescaleIntensityImageFilter,True,False,,True -VectorThresholdSegmentationLevelSetImageFilter,True,False,,True +VectorResampleImageFilter,True,False,,False +VectorRescaleIntensityImageFilter,True,False,,False +VectorThresholdSegmentationLevelSetImageFilter,True,False,,False VnlComplexToComplexFFTImageFilter,True,False,,False -VnlForwardFFTImageFilter,True,False,Internal FFT filter,False -VnlHalfHermitianToRealInverseFFTImageFilter,True,False,Internal FFT filter,False -VnlInverseFFTImageFilter,True,False,Internal FFT filter,False -VnlRealToHalfHermitianForwardFFTImageFilter,True,False,Internal FFT filter,False -VoronoiSegmentationImageFilter,True,False,`,True +VnlForwardFFTImageFilter,True,False,,False +VnlHalfHermitianToRealInverseFFTImageFilter,True,False,,False +VnlInverseFFTImageFilter,True,False,,False +VnlRealToHalfHermitianForwardFFTImageFilter,True,False,,False +VoronoiSegmentationImageFilter,True,False,,False VotingBinaryHoleFillingImageFilter,True,True,,False VotingBinaryImageFilter,True,True,,False VotingBinaryIterativeHoleFillingImageFilter,True,True,,False -WarpImageFilter,True,True,,True -WatershedImageFilter,True,False,,True -WeightedAddImageFilter,True,False,,True +WarpImageFilter,True,True,,False +WatershedImageFilter,True,False,,False +WeightedAddImageFilter,True,False,,False WhiteTopHatImageFilter,True,True,,False WienerDeconvolutionImageFilter,True,True,,False WrapPadImageFilter,True,True,,False @@ -380,4 +372,4 @@ XorImageFilter,True,True,,False YenThresholdImageFilter,True,True,,False ZeroCrossingBasedEdgeDetectionImageFilter,True,True,,False ZeroCrossingImageFilter,True,True,,False -ZeroFluxNeumannPadImageFilter,True,True,,True +ZeroFluxNeumannPadImageFilter,True,True,,False From e33fb30d455672f533dd50a8cbf0ff9bf87976f5 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 22 Jul 2016 10:33:21 -0400 Subject: [PATCH 361/412] Fix disabling using virtualenv from superbuild Disable "building" virtualenv from superbuild when SITK_PYTHON_USE_VIRTUALENV is set. When SITK_PYTHON_USE_VIRTUALENV is set don't add it as a dependency for the dist target. Change-Id: I78ff5ee42b6580d2aec44f1e6690c74ae633754a --- SuperBuild/SuperBuild.cmake | 16 +++++++++------- Wrapping/Python/dist/CMakeLists.txt | 6 ++++-- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/SuperBuild/SuperBuild.cmake b/SuperBuild/SuperBuild.cmake index 6de9b069e..973e30f8a 100644 --- a/SuperBuild/SuperBuild.cmake +++ b/SuperBuild/SuperBuild.cmake @@ -290,15 +290,17 @@ endif() #------------------------------------------------------------------------------ option( USE_SYSTEM_VIRTUALENV "Use a system version of Python's virtualenv. " OFF ) mark_as_advanced(USE_SYSTEM_VIRTUALENV) -if ( USE_SYSTEM_VIRTUALENV ) - find_package( PythonVirtualEnv REQUIRED) -else() - include(External_virtualenv) - if ( WRAP_PYTHON ) - list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES virtualenv) +if( NOT DEFINED SITK_PYTHON_USE_VIRTUALENV OR SITK_PYTHON_USE_VIRTUALENV ) + if ( USE_SYSTEM_VIRTUALENV ) + find_package( PythonVirtualEnv REQUIRED) + else() + include(External_virtualenv) + if ( WRAP_PYTHON ) + list(APPEND ${CMAKE_PROJECT_NAME}_DEPENDENCIES virtualenv) + endif() endif() + list(APPEND SimpleITK_VARS PYTHON_VIRTUALENV_SCRIPT) endif() -list(APPEND SimpleITK_VARS PYTHON_VIRTUALENV_SCRIPT) #------------------------------------------------------------------------------ # ITK diff --git a/Wrapping/Python/dist/CMakeLists.txt b/Wrapping/Python/dist/CMakeLists.txt index d5a6d4bd5..2a50b08d0 100644 --- a/Wrapping/Python/dist/CMakeLists.txt +++ b/Wrapping/Python/dist/CMakeLists.txt @@ -3,7 +3,7 @@ # if( SimpleITK_PYTHON_EGG OR SimpleITK_PYTHON_WHEEL ) if( NOT SITK_PYTHON_USE_VIRTUALENV ) - message( STATUS "Not using SimpleITK's virtualenv for distribution!\ + message( STATUS "Not using SimpleITK's virtualenv for distribution!\n Using unknown versions of pip, setuptools and/or wheel packages/" ) endif() @@ -24,7 +24,9 @@ Using unknown versions of pip, setuptools and/or wheel packages/" ) DEPENDS ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} COMMENT "Creating Python binary distribution" ) - add_dependencies( dist.Python PythonVirtualEnv) + if( NOT SITK_PYTHON_USE_VIRTUALENV ) + add_dependencies( dist.Python PythonVirtualEnv) + endif() add_dependencies( dist dist.Python ) elseif() message( STATUS "Not creating dist.Python target since SITK_FORBID_DOWNLOADS is enabled" ) From e9ab6dcbcfb575c813bd16dbd6ab299dc7fab886 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 22 Jul 2016 11:14:17 -0400 Subject: [PATCH 362/412] Fix missing arguments when setting CMake CACHE variable Change-Id: I0c970c88b2fec32dda0bef27e79dcc8de3b12a8e --- CMake/sitkGenerateFilterSource.cmake | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/CMake/sitkGenerateFilterSource.cmake b/CMake/sitkGenerateFilterSource.cmake index 6f8cf4c96..fba444919 100644 --- a/CMake/sitkGenerateFilterSource.cmake +++ b/CMake/sitkGenerateFilterSource.cmake @@ -3,12 +3,19 @@ # if ( NOT SITK_LUA_EXECUTABLE ) set ( SAVE_LUA_EXECUTABLE ${LUA_EXECUTABLE} ) + get_property( SAVE_LUA_EXECUTABLE_TYPE CACHE LUA_EXECUTABLE PROPERTY TYPE ) + get_property( SAVE_LUA_EXECUTABLE_DOCSTRING CACHE LUA_EXECUTABLE PROPERTY HELPSTRING ) find_package( LuaInterp REQUIRED 5.1 ) set( SITK_LUA_EXECUTABLE ${LUA_EXECUTABLE} CACHE PATH "Lua executable used for code generation." ) if (DEFINED SAVE_LUA_EXECUTABLE) - set( LUA_EXECUTABLE ${SAVE_LUA_EXECUTABLE} CACHE ) + set( LUA_EXECUTABLE ${SAVE_LUA_EXECUTABLE} + CACHE + ${SAVE_LUA_EXECUTABLE_TYPE} + ${SAVE_LUA_EXECUTABLE_DOCSTRING} + FORCED + ) else() unset( LUA_EXECUTABLE CACHE ) endif() From 431b02f566f5495165b73e4e4ab7d3d0838fbe39 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 22 Jul 2016 11:59:27 -0400 Subject: [PATCH 363/412] Enable policies to be set in sitkProjectLanguageCommon Fix warning about CMP0063 not being set with Tcl executable. When a file is included it must be specified to enable policies to be scoped from the included cmake file. Change-Id: I393b694f65bcd2b5b21a198f31186d15732d24a4 --- Wrapping/CSharp/CMakeLists.txt | 2 +- Wrapping/Java/CMakeLists.txt | 2 +- Wrapping/Lua/CMakeLists.txt | 2 +- Wrapping/Python/CMakeLists.txt | 2 +- Wrapping/R/CMakeLists.txt | 2 +- Wrapping/Ruby/CMakeLists.txt | 2 +- Wrapping/Tcl/CMakeLists.txt | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Wrapping/CSharp/CMakeLists.txt b/Wrapping/CSharp/CMakeLists.txt index 5178f6725..7e9e5fe5f 100644 --- a/Wrapping/CSharp/CMakeLists.txt +++ b/Wrapping/CSharp/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) project( SimpleITK_CSharp ) -include(../../CMake/sitkProjectLanguageCommon.cmake) +include(../../CMake/sitkProjectLanguageCommon.cmake NO_POLICY_SCOPE) # Find C# diff --git a/Wrapping/Java/CMakeLists.txt b/Wrapping/Java/CMakeLists.txt index 6e2c47be5..74641d1b5 100644 --- a/Wrapping/Java/CMakeLists.txt +++ b/Wrapping/Java/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) project( SimpleITK_Java ) -include(../../CMake/sitkProjectLanguageCommon.cmake) +include(../../CMake/sitkProjectLanguageCommon.cmake NO_POLICY_SCOPE) find_package ( Java REQUIRED ) find_package ( JNI REQUIRED ) diff --git a/Wrapping/Lua/CMakeLists.txt b/Wrapping/Lua/CMakeLists.txt index c63a6e48f..63d4fb1ec 100644 --- a/Wrapping/Lua/CMakeLists.txt +++ b/Wrapping/Lua/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) project( SimpleITK_Lua ) -include(../../CMake/sitkProjectLanguageCommon.cmake) +include(../../CMake/sitkProjectLanguageCommon.cmake NO_POLICY_SCOPE) if (CMAKE_VERSION VERSION_LESS "3") diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index c3533ce07..e8381f1dc 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -12,7 +12,7 @@ if(POLICY CMP0026) cmake_policy(SET CMP0026 OLD) endif() -include(../../CMake/sitkProjectLanguageCommon.cmake) +include(../../CMake/sitkProjectLanguageCommon.cmake NO_POLICY_SCOPE) if ( SITK_UNDEFINED_SYMBOLS_ALLOWED ) set( _QUIET_LIBRARY "QUIET" ) diff --git a/Wrapping/R/CMakeLists.txt b/Wrapping/R/CMakeLists.txt index 87753adc1..5c085d30b 100644 --- a/Wrapping/R/CMakeLists.txt +++ b/Wrapping/R/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) project( SimpleITK_R ) -include(../../CMake/sitkProjectLanguageCommon.cmake) +include(../../CMake/sitkProjectLanguageCommon.cmake NO_POLICY_SCOPE) find_package ( R REQUIRED ) include_directories ( ${R_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/Wrapping/Ruby/CMakeLists.txt b/Wrapping/Ruby/CMakeLists.txt index bc959d75c..d828d6290 100644 --- a/Wrapping/Ruby/CMakeLists.txt +++ b/Wrapping/Ruby/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) project( SimpleITK_Lua ) -include(../../CMake/sitkProjectLanguageCommon.cmake) +include(../../CMake/sitkProjectLanguageCommon.cmake NO_POLICY_SCOPE) find_package( Ruby REQUIRED ) include_directories( ${RUBY_INCLUDE_DIRS} ) diff --git a/Wrapping/Tcl/CMakeLists.txt b/Wrapping/Tcl/CMakeLists.txt index 6dcfc268c..ca5df7104 100644 --- a/Wrapping/Tcl/CMakeLists.txt +++ b/Wrapping/Tcl/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required ( VERSION 2.8.1 FATAL_ERROR ) project( SimpleITK_TCL ) -include(../../CMake/sitkProjectLanguageCommon.cmake) +include(../../CMake/sitkProjectLanguageCommon.cmake NO_POLICY_SCOPE) find_package ( TCL REQUIRED ) include_directories ( ${TCL_INCLUDE_PATH} ) From d0312ff859d7ecff9c8e29874b91674c687bc901 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 22 Jul 2016 13:31:55 -0400 Subject: [PATCH 364/412] Add check for alias template to use unique_ptr Change-Id: I50bd93cbdd55e2fa097544403f3fa4cf5bdc8847 --- CMake/sitkCheckCXX11.cmake | 2 ++ CMake/sitk_check_cxx11.cxx | 13 +++++++++++++ Code/Common/include/nsstd/auto_ptr.h | 2 +- Code/Common/src/sitkConfigure.h.in | 1 + 4 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CMake/sitkCheckCXX11.cmake b/CMake/sitkCheckCXX11.cmake index b03a37db4..e873e1dd4 100644 --- a/CMake/sitkCheckCXX11.cmake +++ b/CMake/sitkCheckCXX11.cmake @@ -7,6 +7,7 @@ # SITK_HAS_CXX11_UNORDERED_MAP # SITK_HAS_CXX11_NULLPTR - True if "nullptr" keyword is supported # SITK_HAS_CXX11_UNIQUE_PTR +# SITK_HAS_CXX11_ALIAS_TEMPLATE - Able to use alias templates # # SITK_HAS_TR1_SUB_INCLUDE # @@ -57,6 +58,7 @@ sitkCXX11Test(SITK_HAS_CXX11_TYPE_TRAITS) sitkCXX11Test(SITK_HAS_CXX11_UNORDERED_MAP) sitkCXX11Test(SITK_HAS_CXX11_NULLPTR) sitkCXX11Test(SITK_HAS_CXX11_UNIQUE_PTR) +sitkCXX11Test(SITK_HAS_CXX11_ALIAS_TEMPLATE) diff --git a/CMake/sitk_check_cxx11.cxx b/CMake/sitk_check_cxx11.cxx index 4751e9797..950e416cc 100644 --- a/CMake/sitk_check_cxx11.cxx +++ b/CMake/sitk_check_cxx11.cxx @@ -50,7 +50,20 @@ return 0; #endif +//------------------------------------- + +#ifdef SITK_HAS_CXX11_ALIAS_TEMPLATE + +template +using ptr = T*; +int main(void) +{ +ptr x; +return 0; +} + +#endif //------------------------------------- diff --git a/Code/Common/include/nsstd/auto_ptr.h b/Code/Common/include/nsstd/auto_ptr.h index f241898ff..d24fdf466 100644 --- a/Code/Common/include/nsstd/auto_ptr.h +++ b/Code/Common/include/nsstd/auto_ptr.h @@ -28,7 +28,7 @@ namespace simple { namespace nsstd { -#if defined SITK_HAS_CXX11_UNIQUE_PTR +#if defined SITK_HAS_CXX11_UNIQUE_PTR && defined SITK_HAS_CXX11_ALIAS_TEMPLATE template using auto_ptr = std::unique_ptr; #else diff --git a/Code/Common/src/sitkConfigure.h.in b/Code/Common/src/sitkConfigure.h.in index 28b9f089c..01855ac5c 100644 --- a/Code/Common/src/sitkConfigure.h.in +++ b/Code/Common/src/sitkConfigure.h.in @@ -36,6 +36,7 @@ #cmakedefine SITK_HAS_CXX11_TYPE_TRAITS #cmakedefine SITK_HAS_CXX11_UNORDERED_MAP #cmakedefine SITK_HAS_CXX11_UNIQUE_PTR +#cmakedefine SITK_HAS_CXX11_ALIAS_TEMPLATE #cmakedefine SITK_HAS_TR1_SUB_INCLUDE From 2d52e1d236a0b4fb86625ddc26bb673cf79f3a6e Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 22 Jul 2016 15:29:15 -0400 Subject: [PATCH 365/412] Prefer C++11 over tr1 Fix a conflict occurring with gcc 6.1 with tr1::tuple and C++11 tuple when using GTest and SimpleITK. Prefer the use of C++ types over the tr1 types. Change-Id: I81641d0c7eeb76b3b06318518f0435404e948200 --- Code/Common/include/nsstd/functional.h | 13 ++++++------- Code/Common/include/nsstd/type_traits.h | 14 +++++++------- Code/Common/include/nsstd/unordered_map.h | 16 ++++++++-------- 3 files changed, 21 insertions(+), 22 deletions(-) diff --git a/Code/Common/include/nsstd/functional.h b/Code/Common/include/nsstd/functional.h index dea1b22e0..4362efc18 100644 --- a/Code/Common/include/nsstd/functional.h +++ b/Code/Common/include/nsstd/functional.h @@ -20,15 +20,14 @@ #include "sitkConfigure.h" +#if !defined SITK_HAS_TR1_FUNCTIONAL && !defined SITK_HAS_CXX11_FUNCTIONAL +#error "No system (tr1/c++11) functional header available!" +#endif -#if defined SITK_HAS_TR1_FUNCTIONAL || defined SITK_HAS_CXX11_FUNCTIONAL -#if defined SITK_HAS_TR1_SUB_INCLUDE -#include -#else +#if defined SITK_HAS_CXX11_FUNCTIONAL || !defined SITK_HAS_TR1_SUB_INCLUDE #include -#endif #else -#error "No system (tr1) functional header available!" +#include #endif namespace itk @@ -37,7 +36,7 @@ namespace simple { namespace nsstd { -#if defined SITK_HAS_TR1_FUNCTIONAL +#if defined SITK_HAS_TR1_FUNCTIONAL && !defined SITK_HAS_CXX11_FUNCTIONAL using std::tr1::function; using std::tr1::bind; namespace placeholders = std::tr1::placeholders; diff --git a/Code/Common/include/nsstd/type_traits.h b/Code/Common/include/nsstd/type_traits.h index 4bbf7a2b9..0c3ebfa0d 100644 --- a/Code/Common/include/nsstd/type_traits.h +++ b/Code/Common/include/nsstd/type_traits.h @@ -20,14 +20,14 @@ #include "sitkConfigure.h" -#if defined SITK_HAS_TR1_TYPE_TRAITS || defined SITK_HAS_CXX11_TYPE_TRAITS -#if defined SITK_HAS_TR1_SUB_INCLUDE -#include -#else -#include +#if !defined SITK_HAS_TR1_TYPE_TRAITS && !defined SITK_HAS_CXX11_TYPE_TRAITS +#error "No system (tr1/c++11) type_traits header available!" #endif + +#if defined SITK_HAS_CXX11_TYPE_TRAITS || !defined SITK_HAS_TR1_SUB_INCLUDE +#include #else -#error "No system (tr1) type_traits header available!" +#include #endif @@ -37,7 +37,7 @@ namespace simple { namespace nsstd { -#if defined SITK_HAS_TR1_TYPE_TRAITS +#if defined SITK_HAS_TR1_TYPE_TRAITS && !defined SITK_HAS_CXX11_TYPE_TRAITS using std::tr1::is_same; using std::tr1::true_type; using std::tr1::false_type; diff --git a/Code/Common/include/nsstd/unordered_map.h b/Code/Common/include/nsstd/unordered_map.h index 9052fc3dd..3e88ad60b 100644 --- a/Code/Common/include/nsstd/unordered_map.h +++ b/Code/Common/include/nsstd/unordered_map.h @@ -20,15 +20,15 @@ #include "sitkConfigure.h" +#if !defined SITK_HAS_TR1_UNORDERED_MAP && !defined SITK_HAS_CXX11_UNORDERED_MAP +#error "No system (tr1/c++11) unordered_map header available!" +#endif -#if defined SITK_HAS_TR1_UNORDERED_MAP || defined SITK_HAS_CXX11_UNORDERED_MAP -#if defined SITK_HAS_TR1_SUB_INCLUDE -#include -#elif + +#if defined SITK_HAS_CXX11_UNORDERED_MAP && !defined SITK_HAS_TR1_SUB_INCLUDE #include -#endif -#else -#error "No system (tr1) unordered_map header available!" +#elif +#include #endif namespace itk @@ -37,7 +37,7 @@ namespace simple { namespace nsstd { -#if defined SITK_HAS_TR1_SUB_INCLUDE +#if defined SITK_HAS_TR1_UNORDERED_MAP && !defined SITK_HAS_CXX11_UNORDERED_MAP using std::tr1::unordered_map; #else using std::unordered_map; From 1d0a5b6d2e4733630e85d82fbeb913c2830c8bea Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Fri, 22 Jul 2016 16:20:30 -0400 Subject: [PATCH 366/412] Explicitly add GTest libraries to avoid pthread linking issue. The imported GTest library is missing the pthread dependency. By moving the ordering before ITK it ensures gtest has the pthread linkage. Change-Id: Ia997dc35a9fb67eca402f8f8cd3c821a109f2743 --- Testing/Unit/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Testing/Unit/CMakeLists.txt b/Testing/Unit/CMakeLists.txt index 431a65b74..4a0ef6b1a 100644 --- a/Testing/Unit/CMakeLists.txt +++ b/Testing/Unit/CMakeLists.txt @@ -248,7 +248,7 @@ if(MSVC_VERSION EQUAL 1700) endif() add_executable(sitkShowTest sitkShowTest.cxx ) -target_link_libraries ( sitkShowTest ${SimpleITK_LIBRARIES} SimpleITKUnitTestBase ) +target_link_libraries ( sitkShowTest ${GTEST_LIBRARIES} ${SimpleITK_LIBRARIES} SimpleITKUnitTestBase ) add_executable( sitkSystemInformationTest sitkSystemInformationTest.cxx ) target_link_libraries( sitkSystemInformationTest ${SimpleITK_LIBRARIES} ${ITK_LIBRARIES}) From 22c212f96ee14b0817b84998e8ed17433a97291c Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Tue, 19 Jul 2016 15:04:07 -0400 Subject: [PATCH 367/412] Update the SimpleDerivative.lua example Added a "--help" command line option, a Usage message, and a call to the Show function to display the results. This example is pulled into the SimpleITK rock that I've created for Luarocks, so I wanted to make it more readable. Change-Id: I44398ab10dec89c92b08b9b3eaf46b42f27d8040 --- Examples/Lua/SimpleDerivative.lua | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/Examples/Lua/SimpleDerivative.lua b/Examples/Lua/SimpleDerivative.lua index 0a938b9c8..eae726a0f 100644 --- a/Examples/Lua/SimpleDerivative.lua +++ b/Examples/Lua/SimpleDerivative.lua @@ -19,33 +19,54 @@ require "SimpleITK" -local sitk = {} -sitk = SimpleITK +local sitk = {}; +sitk = SimpleITK; -outfile = "sitk-lua-test.png" +outfile = "sitk-lua-test.png"; -if #arg>0 then - outfile = arg[1] +-- parse the command line options +n = #arg; +for i=1,n do + if ( (arg[i] == "--help") or (arg[i] == "-h") ) then + print ("Usage: SimpleDerivative.lua [--help|-h] [output_image]"); + os.exit(); + else + outfile = arg[i]; + end end +-- setup the parameters for the Gaussian source image +-- pixel dimensions of the Gaussian image image size = sitk.VectorUInt32(); size:push_back(128); size:push_back(128); +-- sigma of the Gaussian sigma = sitk.VectorDouble(); sigma:push_back(32.0); sigma:push_back(32.0); +-- center of the Gaussian center = sitk.VectorDouble(); center:push_back(64.0); center:push_back(64.0); +-- create Gaussian image gauss = sitk.GaussianSource (sitk.sitkFloat32, size, sigma, center); +-- take the first derivative in the X direction of the Gaussian deriv = sitk.Derivative(gauss); +-- rescale the intensities to [0, 255] result = sitk.RescaleIntensity(deriv, 0, 255.0); +-- convert the float image pixels to unsigned char result = sitk.Cast(result, sitk.sitkUInt8); +-- write the resulting image sitk.WriteImage(result, outfile); + +-- display the image via the Show function, which invokes ImageJ, by default. +if (os.getenv("SITK_NOSHOW") == nil) then + sitk.Show(result); +end From cea6a2fcc1a313501ee0cc2704b1ae571f619bb2 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Mon, 25 Jul 2016 10:17:29 -0400 Subject: [PATCH 368/412] Set SITK_NOSHOW env var for Lua tests Set the SITK_NOSHOW environment variable when running Lua tests. That way Lua tests know not to call the sitk Show function. Change-Id: Ib0370bb9b5a533d7330163169721017117f5594b --- CMake/sitkAddTest.cmake | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index d5bfeb549..39fab4b75 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -99,6 +99,9 @@ function(sitk_add_lua_test name) set_property(TEST Lua.${name} PROPERTY ENVIRONMENT LUA_CPATH=$ ) + set_property(TEST Lua.${name} + PROPERTY ENVIRONMENT SITK_NOSHOW=YES + ) endfunction() From 187d3d0fca7c2095705fb75674ae4704f467d349 Mon Sep 17 00:00:00 2001 From: Richard Beare Date: Thu, 21 Jul 2016 23:00:18 +1000 Subject: [PATCH 369/412] Remove extra new lines generated in Python and Java Swig Docs file. The new lines are only added to the R documentation now. Change-Id: I3bc1dee775d0cd7ef54d5ff2b970421f6e3e77de --- Utilities/GenerateDocs/doxyall.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Utilities/GenerateDocs/doxyall.py b/Utilities/GenerateDocs/doxyall.py index 7cc028fc6..aa010909d 100755 --- a/Utilities/GenerateDocs/doxyall.py +++ b/Utilities/GenerateDocs/doxyall.py @@ -1,3 +1,4 @@ + #!/usr/bin/env python @@ -100,13 +101,13 @@ def usage(): for line in fin: if (rFlag): + if line in ('\n', '\r\n'): + continue line2 = line.replace("itk::simple::detail::", "") line2 = line.replace("itk::simple::", "") else: line2 = line.replace("itk::simple::detail::", "itk::simple::") line2 = line2.rstrip() - if line in ('\n', '\r\n'): - continue fout.write(line2) fout.write('\n') if (rFlag): From 466ce24c1154978f4f2d90dee65fbd2d343562ab Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Mon, 25 Jul 2016 10:53:23 -0400 Subject: [PATCH 370/412] Added Lua sub-directory The Lua sub-directory was missing, so the Lua example tests were not being included. Change-Id: Iac04870fdd5c7968b9a7618e658704495eb921dd --- Examples/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index f649afcf7..e02e404a7 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -78,6 +78,7 @@ if ( BUILD_TESTING ) add_language_subdirectory( CSharp ) add_language_subdirectory( Java ) + add_language_subdirectory( Lua ) add_language_subdirectory( Python ) add_language_subdirectory( R ) add_language_subdirectory( Ruby ) From 1eec308457243c4c8919965e456eb03ca30e6d97 Mon Sep 17 00:00:00 2001 From: "David T. Chen" Date: Mon, 25 Jul 2016 10:54:18 -0400 Subject: [PATCH 371/412] Added SimpleDerivative example test. Now SimpleDerivative.lua is executed in the testing process. Change-Id: I9d73aa937d5dc03bbfcb1dd9f187492db8178947 --- Examples/Lua/CMakeLists.txt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Examples/Lua/CMakeLists.txt b/Examples/Lua/CMakeLists.txt index 20d9c4809..6fbbc6779 100644 --- a/Examples/Lua/CMakeLists.txt +++ b/Examples/Lua/CMakeLists.txt @@ -27,3 +27,10 @@ sitk_add_lua_test( Example.ImageRegistrationMethod1 0.02 ) +sitk_add_lua_test( Example.SimpleDerivative + "${CMAKE_CURRENT_SOURCE_DIR}/SimpleDerivative.lua" + --compare + "${TEST_HARNESS_TEMP_DIRECTORY}/Lua.SimpleDerivative.nrrd" + DATA{${SimpleITK_DATA_ROOT}/Baseline/Example_SimpleDerivative.nrrd} + "${TEST_HARNESS_TEMP_DIRECTORY}/Lua.SimpleDerivative.nrrd" + ) From ad5f2aa70b0f87a7b74e1bcb3bcc8248175454bc Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 25 Jul 2016 17:00:29 -0400 Subject: [PATCH 372/412] Append LUA test ENVIRONMENT instead of overwriting in Change-Id: I4aff296664a8af652142f8334141936cb5a5f9c1 --- CMake/sitkAddTest.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index 39fab4b75..70d2df797 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -100,7 +100,7 @@ function(sitk_add_lua_test name) PROPERTY ENVIRONMENT LUA_CPATH=$ ) set_property(TEST Lua.${name} - PROPERTY ENVIRONMENT SITK_NOSHOW=YES + APPEND PROPERTY ENVIRONMENT SITK_NOSHOW=YES ) endfunction() From 3fb2d60419c37f097d2703431dcb7d54deed4e49 Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 25 Jul 2016 17:31:37 -0400 Subject: [PATCH 373/412] Fix incorrect logic for dist target dependency on virtualenv Change-Id: I2e072cf20fbced97cbfb43c3992b992692dfe836 --- Wrapping/Python/dist/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Wrapping/Python/dist/CMakeLists.txt b/Wrapping/Python/dist/CMakeLists.txt index 2a50b08d0..15661d457 100644 --- a/Wrapping/Python/dist/CMakeLists.txt +++ b/Wrapping/Python/dist/CMakeLists.txt @@ -24,7 +24,7 @@ Using unknown versions of pip, setuptools and/or wheel packages/" ) DEPENDS ${SWIG_MODULE_SimpleITKPython_TARGET_NAME} COMMENT "Creating Python binary distribution" ) - if( NOT SITK_PYTHON_USE_VIRTUALENV ) + if( SITK_PYTHON_USE_VIRTUALENV ) add_dependencies( dist.Python PythonVirtualEnv) endif() add_dependencies( dist dist.Python ) From 0e1ed57969b439c424aeb4aa70d29ccb227eccbf Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Mon, 25 Jul 2016 17:32:15 -0400 Subject: [PATCH 374/412] Correct PYTHONPATH when not using virtualenv Use append as not to over write other environment variables. Change-Id: Ie8f1f76adb0b4706efa3d50e1d56fb36c2cf06fa --- CMake/sitkAddTest.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMake/sitkAddTest.cmake b/CMake/sitkAddTest.cmake index d5bfeb549..311c150d1 100644 --- a/CMake/sitkAddTest.cmake +++ b/CMake/sitkAddTest.cmake @@ -67,7 +67,7 @@ function(sitk_add_python_test name) ) if (NOT SITK_PYTHON_USE_VIRTUALENV) set_property(TEST Python.${name} - PROPERTY ENVIRONMENT PYTHONPATH=${SimpleITK_BINARY_DIR}/Wrapping + APPEND PROPERTY ENVIRONMENT PYTHONPATH=${SimpleITK_BINARY_DIR}/Wrapping/Python ) endif() From e7f4b10c92f3842439412ded36a15893aef39baa Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 27 Jul 2016 11:20:05 -0400 Subject: [PATCH 375/412] Add missing language file extensions to example glob This was causing the following Doxygen warning: CommandsAndEvents.dox:47: warning: included file FilterProgressReporting.rb is not found. Check your EXAMPLE_PATH Change-Id: I320b32bd46fea4976614e4666c987be3301bf5e4 --- Utilities/Doxygen/doxygen.config.in | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Utilities/Doxygen/doxygen.config.in b/Utilities/Doxygen/doxygen.config.in index bb297c5a9..6edf7c411 100644 --- a/Utilities/Doxygen/doxygen.config.in +++ b/Utilities/Doxygen/doxygen.config.in @@ -842,7 +842,10 @@ EXAMPLE_PATTERNS = "*.cxx" \ "*.R" \ "*.py" \ "*.java" \ - "*.lua" + "*.lua" \ + "*.rb" \ + "*.cs" \ + "*.tcl" # 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 From 4c36d14f72b168f12f986fd75865c5e9b24684ab Mon Sep 17 00:00:00 2001 From: Bradley Lowekamp Date: Wed, 27 Jul 2016 11:22:27 -0400 Subject: [PATCH 376/412] Only conditionally add ITK tag dependency Ninja was producing a warning about this unknown file dependency when USE_ITK_DOXYGEN_TAGS was disabled. Change-Id: I281cbd343d2fe4c5b20c969887184b4c6f4735d5 --- Utilities/Doxygen/Doxygen.cmake | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Utilities/Doxygen/Doxygen.cmake b/Utilities/Doxygen/Doxygen.cmake index 6c4b798fb..d249c9ddd 100644 --- a/Utilities/Doxygen/Doxygen.cmake +++ b/Utilities/Doxygen/Doxygen.cmake @@ -50,10 +50,14 @@ if (BUILD_DOXYGEN) MAIN_DEPENDENCY ${PROJECT_BINARY_DIR}/Utilities/Doxygen/doxygen.config DEPENDS "${PROJECT_BINARY_DIR}/Documentation/Doxygen/Examples.dox" DEPENDS "${PROJECT_BINARY_DIR}/Documentation/Doxygen/FilterCoverage.dox" - DEPENDS "${PROJECT_BINARY_DIR}/Documentation/Doxygen/InsightDoxygen.tag" WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/Utilities/Doxygen ) + if (USE_ITK_DOXYGEN_TAGS) + add_dependencies( Documentation + "${PROJECT_BINARY_DIR}/Documentation/Doxygen/InsightDoxygen.tag" ) + endif () + message( STATUS "To generate Doxygen's documentation, you need to build the Documentation target" ) From 053f90158668e4cc994cd2f34b16040b05c03413 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 24 Aug 2016 10:36:12 +0200 Subject: [PATCH 377/412] ENH: Change name of transformix input point set from moving to fixed to be consistent with mathematical definition and transformation direction --- Code/Elastix/include/sitkSimpleTransformix.h | 10 +++++----- Code/Elastix/include/sitkSimpleTransformix.hxx | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Code/Elastix/include/sitkSimpleTransformix.h b/Code/Elastix/include/sitkSimpleTransformix.h index e60d4d9bc..f59430f0b 100644 --- a/Code/Elastix/include/sitkSimpleTransformix.h +++ b/Code/Elastix/include/sitkSimpleTransformix.h @@ -40,9 +40,9 @@ class SITKCommon_EXPORT SimpleTransformix Image& GetMovingImage( void ); Self& RemoveMovingImage( void ); - Self& SetMovingPointSetFileName( const std::string movingPointSetFileName ); - std::string GetMovingPointSetFileName( void ); - Self& RemoveMovingPointSetFileName( void ); + Self& SetFixedPointSetFileName( const std::string movingPointSetFileName ); + std::string GetFixedPointSetFileName( void ); + Self& RemoveFixedPointSetFileName( void ); Self& SetComputeSpatialJacobian( const bool ); bool GetComputeSpatialJacobian( void ); @@ -111,8 +111,8 @@ class SITKCommon_EXPORT SimpleTransformix bool IsEmpty( const Image& image ); // Definitions for SimpleITK member factory - typedef Image (Self::*MemberFunctionType)( void ); - template< class TMovingImage > Image ExecuteInternal ( void ); + typedef Image ( Self::*MemberFunctionType )( void ); + template< class TMovingImage > Image ExecuteInternal( void ); friend struct detail::MemberFunctionAddressor< MemberFunctionType >; std::auto_ptr< detail::MemberFunctionFactory< MemberFunctionType > > m_MemberFactory; diff --git a/Code/Elastix/include/sitkSimpleTransformix.hxx b/Code/Elastix/include/sitkSimpleTransformix.hxx index daae212ce..d53f6bab9 100644 --- a/Code/Elastix/include/sitkSimpleTransformix.hxx +++ b/Code/Elastix/include/sitkSimpleTransformix.hxx @@ -21,7 +21,7 @@ SimpleTransformix::ExecuteInternal( void ) transformixFilter->SetInput( static_cast< TMovingImage* >( this->GetMovingImage().GetITKBase() ) ); } - transformixFilter->SetInputPointSetFileName( this->GetMovingPointSetFileName() ); + transformixFilter->SetInputPointSetFileName( this->GetFixedPointSetFileName() ); transformixFilter->SetComputeSpatialJacobian( this->GetComputeSpatialJacobian() ); transformixFilter->SetComputeDeterminantOfSpatialJacobian( this->GetComputeDeterminantOfSpatialJacobian() ); transformixFilter->SetComputeDeformationField( this->GetComputeDeformationField() ); From 10765dce348294fe34fbe116b924db48fa977dea Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 24 Aug 2016 10:37:24 +0200 Subject: [PATCH 378/412] ENH: Include ITK in CMake wrapping script needed by elastix --- Wrapping/CMakeLists.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Wrapping/CMakeLists.txt b/Wrapping/CMakeLists.txt index 898fd1e25..8f4dba34b 100644 --- a/Wrapping/CMakeLists.txt +++ b/Wrapping/CMakeLists.txt @@ -1,3 +1,7 @@ +# Include ITK needed by elastix +set( ITK_NO_IO_FACTORY_REGISTER_MANAGER 1 ) +include( ${ITK_USE_FILE} ) + # A general packaging target, not built by default, to build packages for each # language. This should depend on all language specific targets. From 991323192522e37f065506a385938fa38d28ec37 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 24 Aug 2016 10:56:52 +0200 Subject: [PATCH 379/412] ENH: Change name of TransformixFilter's InputPointSet to FixedPointSet to be consistent with mathematical definition and transformation direction --- Code/Elastix/include/sitkSimpleTransformix.hxx | 2 +- Code/Elastix/src/sitkSimpleTransformix.cxx | 6 +++--- Testing/Unit/sitkTransformixFilterTests.cxx | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Code/Elastix/include/sitkSimpleTransformix.hxx b/Code/Elastix/include/sitkSimpleTransformix.hxx index d53f6bab9..f45454d67 100644 --- a/Code/Elastix/include/sitkSimpleTransformix.hxx +++ b/Code/Elastix/include/sitkSimpleTransformix.hxx @@ -21,7 +21,7 @@ SimpleTransformix::ExecuteInternal( void ) transformixFilter->SetInput( static_cast< TMovingImage* >( this->GetMovingImage().GetITKBase() ) ); } - transformixFilter->SetInputPointSetFileName( this->GetFixedPointSetFileName() ); + transformixFilter->SetFixedPointSetFileName( this->GetFixedPointSetFileName() ); transformixFilter->SetComputeSpatialJacobian( this->GetComputeSpatialJacobian() ); transformixFilter->SetComputeDeterminantOfSpatialJacobian( this->GetComputeDeterminantOfSpatialJacobian() ); transformixFilter->SetComputeDeformationField( this->GetComputeDeformationField() ); diff --git a/Code/Elastix/src/sitkSimpleTransformix.cxx b/Code/Elastix/src/sitkSimpleTransformix.cxx index 422739218..018428375 100644 --- a/Code/Elastix/src/sitkSimpleTransformix.cxx +++ b/Code/Elastix/src/sitkSimpleTransformix.cxx @@ -76,7 +76,7 @@ ::RemoveMovingImage( void ) SimpleTransformix::Self& SimpleTransformix -::SetMovingPointSetFileName( const std::string movingPointSetFileName ) +::SetFixedPointSetFileName( const std::string movingPointSetFileName ) { this->m_MovingPointSetFileName = movingPointSetFileName; return *this; @@ -84,14 +84,14 @@ ::SetMovingPointSetFileName( const std::string movingPointSetFileName ) std::string SimpleTransformix -::GetMovingPointSetFileName( void ) +::GetFixedPointSetFileName( void ) { return this->m_MovingPointSetFileName; } SimpleTransformix::Self& SimpleTransformix -::RemoveMovingPointSetFileName( void ) +::RemoveFixedPointSetFileName( void ) { this->m_MovingPointSetFileName = std::string(); return *this; diff --git a/Testing/Unit/sitkTransformixFilterTests.cxx b/Testing/Unit/sitkTransformixFilterTests.cxx index 3d39e2cea..ee839328c 100644 --- a/Testing/Unit/sitkTransformixFilterTests.cxx +++ b/Testing/Unit/sitkTransformixFilterTests.cxx @@ -181,9 +181,9 @@ TEST( TransformixFilterTest, TransformPointSet ) ImageFileReaderType::Pointer movingImageReader = ImageFileReaderType::New(); movingImageReader->SetFileName( dataFinder.GetFile( "Input/BrainProtonDensitySliceR10X13Y17.png" ) ); - const std::string inputPointSetFileName = dataFinder.GetOutputFile( "InputPoints.pts" ); + const std::string fixedPointSetFileName = dataFinder.GetOutputFile( "InputPoints.pts" ); std::ofstream fixedMeshFile; - fixedMeshFile.open( inputPointSetFileName.c_str() ); + fixedMeshFile.open( fixedPointSetFileName.c_str() ); fixedMeshFile << "point\n"; fixedMeshFile << "1\n"; fixedMeshFile << "128.0 128.0\n"; @@ -199,7 +199,7 @@ TEST( TransformixFilterTest, TransformPointSet ) EXPECT_NO_THROW( transformixFilter = TransformixFilterType::New() ); EXPECT_NO_THROW( transformixFilter->SetOutputDirectory( dataFinder.GetOutputDirectory() ) ); EXPECT_NO_THROW( transformixFilter->SetTransformParameterObject( elastixFilter->GetTransformParameterObject() ) ); - EXPECT_NO_THROW( transformixFilter->SetInputPointSetFileName( dataFinder.GetOutputFile( "InputPoints.pts" ) ) ); + EXPECT_NO_THROW( transformixFilter->SetFixedPointSetFileName( dataFinder.GetOutputFile( "InputPoints.pts" ) ) ); EXPECT_NO_THROW( transformixFilter->Update() ); } From 168aba0713f84bbe34edbff307d705158be52efd Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 24 Aug 2016 11:31:15 +0200 Subject: [PATCH 380/412] ENH: Add examples from SimpleITK v0.10.0rc2 --- Examples/CMakeLists.txt | 35 +++- Examples/ITKIntegration/CMakeLists.txt | 12 ++ .../{ => ITKIntegration}/ElastixFilter.cxx | 0 Examples/ITKIntegration/ITKIntegration.cxx | 181 ++++++++++++++++++ Examples/ITKIntegration/TransformixFilter.cxx | 56 ++++++ Examples/Segmentation/CMakeLists.txt | 7 + .../ConnectedThresholdImageFilter.cxx | 100 ++++++++++ .../NeighborhoodConnectedImageFilter.cxx | 110 +++++++++++ 8 files changed, 495 insertions(+), 6 deletions(-) create mode 100644 Examples/ITKIntegration/CMakeLists.txt rename Examples/{ => ITKIntegration}/ElastixFilter.cxx (100%) create mode 100644 Examples/ITKIntegration/ITKIntegration.cxx create mode 100644 Examples/ITKIntegration/TransformixFilter.cxx create mode 100644 Examples/Segmentation/CMakeLists.txt create mode 100644 Examples/Segmentation/ConnectedThresholdImageFilter.cxx create mode 100644 Examples/Segmentation/NeighborhoodConnectedImageFilter.cxx diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index ac6d1695e..cd1d6908d 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -22,14 +22,36 @@ if(NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") endif() -add_executable( ElastixFilter ElastixFilter.cxx ) -target_link_libraries( ElastixFilter ${SimpleITK_LIBRARIES} ) +# Add individual cxx executables +add_executable ( SimpleElastix1 SimpleElastix.cxx ) +target_link_libraries ( SimpleElastix1 ${SimpleITK_LIBRARIES} ) -add_executable( SimpleElastixCxx SimpleElastix.cxx ) -target_link_libraries( SimpleElastixCxx ${SimpleITK_LIBRARIES} ) +add_executable ( SimpleTransformix1 SimpleTransformix.cxx ) +target_link_libraries ( SimpleTransformix1 ${SimpleITK_LIBRARIES} ) -add_executable( SimpleTransformixCxx SimpleTransformix.cxx ) -target_link_libraries( SimpleTransformixCxx ${SimpleITK_LIBRARIES} ) +add_executable ( SimpleGaussian SimpleGaussian.cxx ) +target_link_libraries ( SimpleGaussian ${SimpleITK_LIBRARIES} ) + +add_executable ( SimpleGaussianFunctional SimpleGaussianFunctional.cxx ) +target_link_libraries ( SimpleGaussianFunctional ${SimpleITK_LIBRARIES} ) + +add_executable ( BufferImportExport BufferImportExport.cxx ) +target_link_libraries ( BufferImportExport ${SimpleITK_LIBRARIES} ) + +add_executable ( FilterProgressReporting FilterProgressReporting.cxx ) +target_link_libraries ( FilterProgressReporting ${SimpleITK_LIBRARIES} ) + +add_executable ( DicomSeriesReader DicomSeriesReader.cxx ) +target_link_libraries ( DicomSeriesReader ${SimpleITK_LIBRARIES} ) + +add_executable ( ImageRegistrationMethod1 ImageRegistrationMethod1.cxx ) +target_link_libraries ( ImageRegistrationMethod1 ${SimpleITK_LIBRARIES} ) + +add_executable ( ImageRegistrationMethod2 ImageRegistrationMethod2.cxx ) +target_link_libraries ( ImageRegistrationMethod2 ${SimpleITK_LIBRARIES} ) + +add_executable ( ImageRegistrationMethodBSpline1 ImageRegistrationMethodBSpline1.cxx ) +target_link_libraries ( ImageRegistrationMethodBSpline1 ${SimpleITK_LIBRARIES} ) add_executable ( ImageRegistrationMethodDisplacement1 ImageRegistrationMethodDisplacement1.cxx ) target_link_libraries ( ImageRegistrationMethodDisplacement1 ${SimpleITK_LIBRARIES} ) @@ -42,6 +64,7 @@ target_link_libraries ( DemonsRegistration2 ${SimpleITK_LIBRARIES} ) # Add subdirectories add_subdirectory(Segmentation) +add_subdirectory(ITKIntegration) # Test data directory set(TEST_HARNESS_TEMP_DIRECTORY ${SimpleITK_BINARY_DIR}/Testing/Temporary) diff --git a/Examples/ITKIntegration/CMakeLists.txt b/Examples/ITKIntegration/CMakeLists.txt new file mode 100644 index 000000000..de791673f --- /dev/null +++ b/Examples/ITKIntegration/CMakeLists.txt @@ -0,0 +1,12 @@ + +find_package(ITK REQUIRED ) +include(${ITK_USE_FILE}) + +add_executable ( ITKIntegration ITKIntegration.cxx ) +target_link_libraries ( ITKIntegration ${SimpleITK_LIBRARIES} ) + +add_executable( ElastixFilter ElastixFilter.cxx ) +target_link_libraries( ElastixFilter ${SimpleITK_LIBRARIES} ) + +add_executable( TransformixFilter TransformixFilter.cxx ) +target_link_libraries( TransformixFilter ${SimpleITK_LIBRARIES} ) diff --git a/Examples/ElastixFilter.cxx b/Examples/ITKIntegration/ElastixFilter.cxx similarity index 100% rename from Examples/ElastixFilter.cxx rename to Examples/ITKIntegration/ElastixFilter.cxx diff --git a/Examples/ITKIntegration/ITKIntegration.cxx b/Examples/ITKIntegration/ITKIntegration.cxx new file mode 100644 index 000000000..18397015e --- /dev/null +++ b/Examples/ITKIntegration/ITKIntegration.cxx @@ -0,0 +1,181 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#if defined(_MSC_VER) +#pragma warning ( disable : 4786 ) +#endif + +// SimpleITK includes +#include "SimpleITK.h" + +// ITK includes +#include "itkImage.h" +#include "itkCurvatureFlowImageFilter.h" + +// create convenient namespace alias +namespace sitk = itk::simple; + +/** + * This example shows how ITK and SimpleITK can be used together to work + * on the same data. We use the same example application as the one presented + * in the Segmentation/ConnectedThresholdImageFilter.cxx example, but we + * replace the SimpleITK version of CurvatureFlowImageFilter with the + * corresponding ITK version. While not terribly useful in this situation since + * CurvatureFlowImageFilter is already available in SimpleITK this demonstrates + * how ITK filters that have not been converted for SimpleITK can still be used + * in a SimpleITK context + */ +int main( int argc, char *argv[]) +{ + + // + // Check command line parameters + // + if( argc < 7 ) + { + std::cerr << "Missing Parameters " << std::endl; + std::cerr << "Usage: " << argv[0]; + std::cerr << " inputImage outputImage lowerThreshold upperThreshold " + "seedX seedY [seed2X seed2Y ... ]" << std::endl; + return 1; + } + + + // + // Read the image + // + sitk::ImageFileReader reader; + reader.SetFileName( std::string( argv[1] ) ); + sitk::Image image = reader.Execute(); + + + // + // Set up writer + // + sitk::ImageFileWriter writer; + writer.SetFileName( std::string( argv[2] ) ); + + ////// + // Blur using CurvatureFlowImageFilter + // + // Here we demonstrate the use of the ITK version of CurvatureFlowImageFilter + // instead of the SimpleITK version. + ////// + + // + // First, define the typedefs that correspond to the types of the input + // image. This requires foreknowlege of the data type of the input image. + // + const unsigned int Dimension = 2; + typedef float InternalPixelType; + typedef itk::Image< InternalPixelType, Dimension > InternalImageType; + + // + // We must check the the image dimension and the pixel type of the + // SimpleITK image match the ITK image we will cast to.s + // + if ( image.GetDimension() != Dimension ) + { + std::cerr << "Input image is not a " << Dimension << " dimensional image as expected!" << std::endl; + return 1; + } + + // + // The read sitk::Image could be any pixel type. Cast the image, to + // float so we know what type we have. + // + sitk::CastImageFilter caster; + caster.SetOutputPixelType( sitk::sitkFloat32 ); + image = caster.Execute( image ); + + // + // Extract the itk image from the SimpleITK image + // + InternalImageType::Pointer itkImage = + dynamic_cast ( image.GetITKBase() ); + + // + // Always check the results of dynamic_casts + // + if ( itkImage.IsNull() ) + { + std::cerr << "Unexpected error converting SimpleITK image to ITK image!" << std::endl; + return 1; + } + + // + // Set up the blur filter and attach it to the pipeline. + // + typedef itk::CurvatureFlowImageFilter< InternalImageType, InternalImageType > + BlurFilterType; + BlurFilterType::Pointer blurFilter = BlurFilterType::New(); + blurFilter->SetInput( itkImage ); + blurFilter->SetNumberOfIterations( 5 ); + blurFilter->SetTimeStep( 0.125 ); + + + + // + // Execute the Blur pipeline by calling Update() on the blur filter. + // + blurFilter->Update(); + + + // + // Return to the simpleITK setting by making a SimpleITK image using the + // output of the blur filter. + // + sitk::Image blurredImage = sitk::Image( blurFilter->GetOutput() ); + + + ////// + // Now that we have finished the ITK section, we return to the SimpleITK API + ////// + + + // + // Set up ConnectedThresholdImageFilter for segmentation + // + sitk::ConnectedThresholdImageFilter segmentationFilter; + segmentationFilter.SetLower( atof( argv[3] ) ); + segmentationFilter.SetUpper( atof( argv[4] ) ); + segmentationFilter.SetReplaceValue( 255 ); + + for (int i = 5; i+1 < argc; i+=2) + { + std::vector seed; + seed.push_back(atoi(argv[i])); + seed.push_back(atoi(argv[i+1])); + segmentationFilter.AddSeed(seed); + std::cout << "Adding a seed at "; + for( unsigned int j = 0; j < seed.size(); ++i ) + { + std::cout << seed[j] << " "; + } + std::cout << std::endl; + } + + sitk::Image outImage = segmentationFilter.Execute(blurredImage); + + + // + // Write out the resulting file + // + writer.Execute(outImage); + + return 0; +} diff --git a/Examples/ITKIntegration/TransformixFilter.cxx b/Examples/ITKIntegration/TransformixFilter.cxx new file mode 100644 index 000000000..12810d0ba --- /dev/null +++ b/Examples/ITKIntegration/TransformixFilter.cxx @@ -0,0 +1,56 @@ +#include +#include + +#include "elxTransformixFilter.h" +#include "itkImageFileReader.h" +#include "itkImageFileWriter.h" + +int main( int argc, char* argv[] ) { + + if ( argc < 3 ) { + std::cerr << "Usage: " << argv[0] << " \n"; + return 1; + } + + typedef itk::Image< float, 2u > ImageType; + + typedef elastix::TransformixFilter< ImageType > TransformixFilterType; + typedef TransformixFilterType::Pointer TransformixPointer; + + typedef elastix::ParameterObject ParameterObjectType; + typedef ParameterObjectType::Pointer ParameterObjectPointer; + + typedef itk::ImageFileReader< ImageType > InputImageReaderType; + typedef InputImageReaderType::Pointer InputImageReaderPointer; + + typedef itk::ImageFileWriter< ImageType > OutputImageWriterType; + typedef OutputImageWriterType::Pointer OutputImageWriterPointer; + + try + { + InputImageReaderPointer imageReader = InputImageReaderType::New(); + imageReader->SetFileName( argv[1] ); + + ParameterObjectPointer parameterObject = ParameterObjectType::New(); + parameterObject->ReadParameterFile( argv[2] ); + + TransformixPointer transformixFilter = TransformixFilterType::New(); + transformixFilter->SetMovingImage( imageReader->GetOutput() ); + transformixFilter->SetTransformParameterObject( parameterObject ); + transformixFilter->LogToConsoleOn(); + + OutputImageWriterPointer outputImageWriter = OutputImageWriterType::New(); + outputImageWriter->SetFileName( argv[3] ); + outputImageWriter->SetInput( transformixFilter->GetOutput() ); + outputImageWriter->Update(); + } + catch( itk::ExceptionObject &e ) + { + std::cerr << "Errors occured during transformation: "; + std::cerr << e << std::endl; + return EXIT_FAILURE; + } + + return 0; + +} diff --git a/Examples/Segmentation/CMakeLists.txt b/Examples/Segmentation/CMakeLists.txt new file mode 100644 index 000000000..018599c61 --- /dev/null +++ b/Examples/Segmentation/CMakeLists.txt @@ -0,0 +1,7 @@ + +# Add executable example targets +add_executable ( ConnectedThresholdImageFilter ConnectedThresholdImageFilter.cxx ) +target_link_libraries ( ConnectedThresholdImageFilter ${SimpleITK_LIBRARIES} ) + +add_executable ( NeighborhoodConnectedImageFilter NeighborhoodConnectedImageFilter.cxx ) +target_link_libraries ( NeighborhoodConnectedImageFilter ${SimpleITK_LIBRARIES} ) diff --git a/Examples/Segmentation/ConnectedThresholdImageFilter.cxx b/Examples/Segmentation/ConnectedThresholdImageFilter.cxx new file mode 100644 index 000000000..38f8d3437 --- /dev/null +++ b/Examples/Segmentation/ConnectedThresholdImageFilter.cxx @@ -0,0 +1,100 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#if defined(_MSC_VER) +#pragma warning ( disable : 4786 ) +#endif + + +#include "sitkImage.h" +#include "sitkCurvatureFlowImageFilter.h" +#include "sitkConnectedThresholdImageFilter.h" +#include "sitkImageFileReader.h" +#include "sitkImageFileWriter.h" + +#include +#include + +namespace sitk = itk::simple; + +int main( int argc, char *argv[]) +{ + + // + // Check command line parameters + // + if( argc < 7 ) + { + std::cerr << "Missing Parameters " << std::endl; + std::cerr << "Usage: " << argv[0]; + std::cerr << " inputImage outputImage lowerThreshold upperThreshold seedX seedY [seed2X seed2Y ... ]" << std::endl; + return 1; + } + + + // + // Read the image + // + + sitk::ImageFileReader reader; + reader.SetFileName( std::string( argv[1] ) ); + sitk::Image image = reader.Execute(); + + + // + // Blur using CurvatureFlowImageFilter + // + sitk::CurvatureFlowImageFilter blurFilter; + blurFilter.SetNumberOfIterations( 5 ); + blurFilter.SetTimeStep( 0.125 ); + image = blurFilter.Execute( image ); + + + // + // Set up ConnectedThresholdImageFilter for segmentation + // + sitk::ConnectedThresholdImageFilter segmentationFilter; + segmentationFilter.SetLower( atof( argv[3] ) ); + segmentationFilter.SetUpper( atof( argv[4] ) ); + segmentationFilter.SetReplaceValue( 255 ); + + for (int i = 5; i+1 < argc; i+=2) + { + std::vector seed; + seed.push_back(atoi(argv[i])); + seed.push_back(atoi(argv[i+1])); + segmentationFilter.AddSeed(seed); + std::cout << "Adding a seed at: "; + for( unsigned int j = 0; j < seed.size(); ++j ) + { + std::cout << seed[j] << " "; + } + std::cout << std::endl; + } + + sitk::Image outImage = segmentationFilter.Execute(image); + + + // + // Write out the resulting file + // + sitk::ImageFileWriter writer; + writer.SetFileName( std::string( argv[2] ) ); + writer.Execute(outImage); + + return 0; +} diff --git a/Examples/Segmentation/NeighborhoodConnectedImageFilter.cxx b/Examples/Segmentation/NeighborhoodConnectedImageFilter.cxx new file mode 100644 index 000000000..807bc6fc6 --- /dev/null +++ b/Examples/Segmentation/NeighborhoodConnectedImageFilter.cxx @@ -0,0 +1,110 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#if defined(_MSC_VER) +#pragma warning ( disable : 4786 ) +#endif + + +#include "sitkImage.h" +#include "sitkCurvatureFlowImageFilter.h" +#include "sitkNeighborhoodConnectedImageFilter.h" +#include "sitkImageFileReader.h" +#include "sitkImageFileWriter.h" + +#include +#include + +namespace sitk = itk::simple; + +int main( int argc, char *argv[]) +{ + + // + // Check command line parameters + // + if( argc < 7 ) + { + std::cerr << "Missing Parameters " << std::endl; + std::cerr << "Usage: " << argv[0]; + std::cerr << " inputImage outputImage lowerThreshold upperThreshold seedX seedY [seed2X seed2Y ... ]" << std::endl; + return 1; + } + + + // + // Read the image + // + + sitk::ImageFileReader reader; + reader.SetFileName( std::string( argv[1] ) ); + sitk::Image image = reader.Execute(); + + + // + // Set up writer + // + sitk::ImageFileWriter writer; + writer.SetFileName( std::string( argv[2] ) ); + + + // + // Blur using CurvatureFlowImageFilter + // + sitk::CurvatureFlowImageFilter blurFilter; + blurFilter.SetNumberOfIterations( 5 ); + blurFilter.SetTimeStep( 0.125 ); + image = blurFilter.Execute( image ); + + + // + // Set up NeighborhoodConnectedImageFilter for segmentation + // + sitk::NeighborhoodConnectedImageFilter segmentationFilter; + segmentationFilter.SetLower( atof( argv[3] ) ); + segmentationFilter.SetUpper( atof( argv[4] ) ); + segmentationFilter.SetReplaceValue( 255 ); + + std::vector radius; + radius.push_back( 2 ); + radius.push_back( 2 ); + segmentationFilter.SetRadius( radius ); + + for (int i = 5; i+1 < argc; i+=2) + { + std::vector seed; + seed.push_back(atoi(argv[i])); + seed.push_back(atoi(argv[i+1])); + segmentationFilter.AddSeed(seed); + std::cout << "Adding a seed at "; + for( unsigned int j = 0; j < seed.size(); ++j ) + { + std::cout << seed[j] << " "; + } + std::cout << std::endl; + } + + sitk::Image outImage = segmentationFilter.Execute(image); + + + // + // Write out the resulting file + // + writer.Execute(outImage); + + return 0; +} From cd758cd34d31fa09af6961fca09086defff2d97c Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 24 Aug 2016 11:34:42 +0200 Subject: [PATCH 381/412] ENH: Update elastix to revision --- SuperBuild/External_Elastix.cmake | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/SuperBuild/External_Elastix.cmake b/SuperBuild/External_Elastix.cmake index b8cb2addd..5a6b3f439 100644 --- a/SuperBuild/External_Elastix.cmake +++ b/SuperBuild/External_Elastix.cmake @@ -1,12 +1,21 @@ set( proj elastix ) +get_cmake_property( _varNames VARIABLES )# + +if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) + set( ELASTIX_BUILD_SHARED_LIBS ON ) +else() + set( ELASTIX_BUILD_SHARED_LIBS OFF ) +endif() + file( WRITE "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" "${ep_common_cache}" ) -set( ELASTIX_REPOSITORY http://github.com/kaspermarstal/elastix ) -set( ELASTIX_TAG 3c7deef6d4f44203207bc198cc27f011ac1222c7 ) + +set( ELASTIX_GIT_REPOSITORY ${git_protocol}://github.com/kaspermarstal/elastix ) +set( ELASTIX_GIT_TAG 098f973472f3a51bbffbe2967440fae970518001 ) ExternalProject_Add( ${proj} - GIT_REPOSITORY ${ELASTIX_REPOSITORY} - GIT_TAG ${ELASTIX_TAG} + GIT_REPOSITORY ${ELASTIX_GIT_REPOSITORY} + GIT_TAG ${ELASTIX_GIT_TAG} UPDATE_COMMAND "" SOURCE_DIR ${proj} BINARY_DIR ${proj}-build @@ -14,9 +23,11 @@ ExternalProject_Add( ${proj} CMAKE_ARGS --no-warn-unused-cli -C "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" + ${ep_common_args} + -DCMAKE_POSITION_INDEPENDENT_CODE:BOOL=ON -DELASTIX_BUILD_TESTING:BOOL=OFF -DELASTIX_BUILD_EXECUTABLE:BOOL=OFF - -DELASTIX_BUILD_SHARED_LIBS:BOOL=${BUILD_SHARED_LIBS} + -DELASTIX_BUILD_SHARED_LIBS:BOOL=${ELASTIX_BUILD_SHARED_LIBS} -DCMAKE_INSTALL_PREFIX:PATH= -DITK_DIR:PATH=${ITK_DIR} -DUSE_ALL_PIXELTYPES:BOOL=ON @@ -85,7 +96,7 @@ ExternalProject_Add( ${proj} -DUSE_RayCastInterpolator:BOOL=ON -DUSE_RayCastResampleInterpolator:BOOL=ON -DUSE_ReducedDimensionBSplineInterpolator:BOOL=ON - -DUSE_ReducedDimensionBSplineResampleInterpolator:BOOL=ON + -DUSE_ReducedDimensionBSplineResampleInterpolator:BOOL=ON -DUSE_RegularStepGradientDescent:BOOL=ON -DUSE_SimilarityTransformElastix:BOOL=ON -DUSE_Simplex:BOOL=ON From bd4dbcd3b9bc65cd0b445ddd5fca002dbd3b083d Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 24 Aug 2016 11:35:28 +0200 Subject: [PATCH 382/412] GIT: Remove merge conflict markers --- SuperBuild/External_ITK.cmake | 5 ----- 1 file changed, 5 deletions(-) diff --git a/SuperBuild/External_ITK.cmake b/SuperBuild/External_ITK.cmake index 44bd0251c..1a00d9945 100644 --- a/SuperBuild/External_ITK.cmake +++ b/SuperBuild/External_ITK.cmake @@ -98,10 +98,5 @@ ExternalProject_Add(${proj} ExternalProject_Get_Property(ITK install_dir) -<<<<<<< HEAD -set(ITK_DIR "${install_dir}/lib/cmake/ITK-4.8" ) -set(WrapITK_DIR "${install_dir}/lib/cmake/ITK-4.8/WrapITK") -======= set(ITK_DIR "${install_dir}/lib/cmake/ITK-4.10" ) set(WrapITK_DIR "${ITK_DIR}/WrapITK") ->>>>>>> v0.10rc1 From 5d66d5ac0373f1205ec5d02985ee12c6bfc9201e Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 24 Aug 2016 12:31:58 +0200 Subject: [PATCH 383/412] ENH: Update elastix to revision 5414 --- SuperBuild/External_Elastix.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_Elastix.cmake b/SuperBuild/External_Elastix.cmake index 5a6b3f439..b33300753 100644 --- a/SuperBuild/External_Elastix.cmake +++ b/SuperBuild/External_Elastix.cmake @@ -11,7 +11,7 @@ endif() file( WRITE "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" "${ep_common_cache}" ) set( ELASTIX_GIT_REPOSITORY ${git_protocol}://github.com/kaspermarstal/elastix ) -set( ELASTIX_GIT_TAG 098f973472f3a51bbffbe2967440fae970518001 ) +set( ELASTIX_GIT_TAG 41c558e3d4c33421451d2498059f0c3cf1a4da75 ) ExternalProject_Add( ${proj} GIT_REPOSITORY ${ELASTIX_GIT_REPOSITORY} From ca3e2efec188b14969e16a9d2722547deb7710f3 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 24 Aug 2016 12:33:10 +0200 Subject: [PATCH 384/412] ENH: Update SimpleTransformix for new TransformixFilter revision --- Code/Elastix/include/sitkSimpleTransformix.hxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Elastix/include/sitkSimpleTransformix.hxx b/Code/Elastix/include/sitkSimpleTransformix.hxx index f45454d67..f5138f85b 100644 --- a/Code/Elastix/include/sitkSimpleTransformix.hxx +++ b/Code/Elastix/include/sitkSimpleTransformix.hxx @@ -18,7 +18,7 @@ SimpleTransformix::ExecuteInternal( void ) TransforimxFilterPointer transformixFilter = TransformixFilterType::New(); if( !this->IsEmpty( this->m_MovingImage ) ) { - transformixFilter->SetInput( static_cast< TMovingImage* >( this->GetMovingImage().GetITKBase() ) ); + transformixFilter->SetMovingImage( static_cast< TMovingImage* >( this->GetMovingImage().GetITKBase() ) ); } transformixFilter->SetFixedPointSetFileName( this->GetFixedPointSetFileName() ); From 34c41acc4ccb5d274207e1eec2f33f282785fe24 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Mon, 5 Sep 2016 19:24:23 +0200 Subject: [PATCH 385/412] ENH: Update elastix This update fixes linking issues as discussed in kaspermarstal/SimpleElastix#47 --- .travis.yml | 2 +- SuperBuild/External_Elastix.cmake | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index f4967ecf5..13edd4e84 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,5 +20,5 @@ before_script: - cd SimpleElastix-build script: - - cmake ../SimpleElastix/SuperBuild + - cmake ../SimpleElastix/SuperBuild -DBUILD_TESTING=OFF # Not enough time - make --jobs=2 diff --git a/SuperBuild/External_Elastix.cmake b/SuperBuild/External_Elastix.cmake index b33300753..bacb6df36 100644 --- a/SuperBuild/External_Elastix.cmake +++ b/SuperBuild/External_Elastix.cmake @@ -11,7 +11,7 @@ endif() file( WRITE "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" "${ep_common_cache}" ) set( ELASTIX_GIT_REPOSITORY ${git_protocol}://github.com/kaspermarstal/elastix ) -set( ELASTIX_GIT_TAG 41c558e3d4c33421451d2498059f0c3cf1a4da75 ) +set( ELASTIX_GIT_TAG 54e5a7c4513bb36374c18d05951de7354f5837ca ) ExternalProject_Add( ${proj} GIT_REPOSITORY ${ELASTIX_GIT_REPOSITORY} From 3742ce1f3f18c396148c9d1668c596f06f863769 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Mon, 5 Sep 2016 19:27:30 +0200 Subject: [PATCH 386/412] ENH: Compile elastix only for float to reduce compile time and binary size This is a relatively large commit that changes compilation of elastix to include only the float pixel type. Instead of compiling elastix for all pixel types, images will automatically casted to and from float. This SIGNIFICANTLY reduces compile time and binary size. TODO: Make elastix pixel type configurable from CMake. --- Code/Common/include/sitkPixelIDTypeLists.h | 6 +++ Code/Common/include/sitkPixelIDValues.h | 1 + Code/Common/src/sitkPixelIDValues.cxx | 48 +++++++++++++++++++ Code/Elastix/include/sitkSimpleElastix.h | 4 +- Code/Elastix/include/sitkSimpleElastix.hxx | 24 +++++++--- Code/Elastix/include/sitkSimpleTransformix.h | 2 +- .../Elastix/include/sitkSimpleTransformix.hxx | 20 +++++--- Code/Elastix/src/CMakeLists.txt | 16 ++----- Code/Elastix/src/sitkSimpleElastix.cxx | 6 +-- Code/Elastix/src/sitkSimpleTransformix.cxx | 6 +-- Examples/CMakeLists.txt | 9 +++- Examples/ITKIntegration/CMakeLists.txt | 4 -- Examples/ITKIntegration/ElastixFilter.cxx | 2 +- .../{SimpleElastix.cxx => SimpleElastix1.cxx} | 4 +- ...Transformix.cxx => SimpleTransformix1.cxx} | 4 +- SuperBuild/External_Elastix.cmake | 11 ++++- 16 files changed, 122 insertions(+), 45 deletions(-) rename Examples/{SimpleElastix.cxx => SimpleElastix1.cxx} (97%) rename Examples/{SimpleTransformix.cxx => SimpleTransformix1.cxx} (98%) diff --git a/Code/Common/include/sitkPixelIDTypeLists.h b/Code/Common/include/sitkPixelIDTypeLists.h index 2fdafd6d7..b971ee8b5 100644 --- a/Code/Common/include/sitkPixelIDTypeLists.h +++ b/Code/Common/include/sitkPixelIDTypeLists.h @@ -217,6 +217,12 @@ typedef AllPixelIDTypeList InstantiatedPixelIDTypeList; #endif +/** SimpleElastix and SimpleTransformix is compiled with float pixel type only for + * saving compile time and reducing binary size. Images are automacially casted to + * and from float before and after registration. + */ +typedef typelist::MakeTypeList< BasicPixelID< float > >::Type FloatPixelIDTypeList; + } } diff --git a/Code/Common/include/sitkPixelIDValues.h b/Code/Common/include/sitkPixelIDValues.h index b87d1b76c..4c5bb85c4 100644 --- a/Code/Common/include/sitkPixelIDValues.h +++ b/Code/Common/include/sitkPixelIDValues.h @@ -130,6 +130,7 @@ const std::string SITKCommon_EXPORT GetPixelIDValueAsElastixParameter( PixelIDVa * changes to PixelIDValueEnum - i.e. if a new pixel type is added. */ PixelIDValueType SITKCommon_EXPORT GetPixelIDValueFromString(const std::string &enumString ); +PixelIDValueType SITKCommon_EXPORT GetPixelIDValueFromElastixString(const std::string &enumString ); #ifndef SWIG SITKCommon_EXPORT std::ostream& operator<<(std::ostream& os, const PixelIDValueEnum id); diff --git a/Code/Common/src/sitkPixelIDValues.cxx b/Code/Common/src/sitkPixelIDValues.cxx index 75e562c28..a1a0aac52 100644 --- a/Code/Common/src/sitkPixelIDValues.cxx +++ b/Code/Common/src/sitkPixelIDValues.cxx @@ -326,6 +326,54 @@ PixelIDValueType GetPixelIDValueFromString(const std::string &enumString ) } +PixelIDValueType GetPixelIDValueFromElastixString(const std::string &enumString ) +{ + + if ( enumString == "sitkUnknown" ) + { + // Unknow must be first because other enums may be -1 if they are + // not instantiated + return sitkUnknown; + } + else if ( enumString == "unsigned char" ) + { + return sitkUInt8; + } + else if ( enumString == "char" ) + { + return sitkInt8; + } + else if ( enumString == "unsigned short" ) + { + return sitkUInt16; + } + else if ( enumString == "short" ) + { + return sitkInt16; + } + else if ( enumString == "unsigned int" ) + { + return sitkUInt32; + } + else if ( enumString == "int" ) + { + return sitkInt32; + } + else if ( enumString == "float" ) + { + return sitkFloat32; + } + else if ( enumString == "double" ) + { + return sitkFloat64; + } + else + { + return -99; + } +} + + std::ostream& operator<<(std::ostream& os, const PixelIDValueEnum id) { return (os << GetPixelIDValueAsString(id)); diff --git a/Code/Elastix/include/sitkSimpleElastix.h b/Code/Elastix/include/sitkSimpleElastix.h index 52b1a934f..7c0031559 100644 --- a/Code/Elastix/include/sitkSimpleElastix.h +++ b/Code/Elastix/include/sitkSimpleElastix.h @@ -149,9 +149,9 @@ class SITKCommon_EXPORT SimpleElastix // Definitions for SimpleITK member factory typedef Image ( Self::*MemberFunctionType )( void ); + template< class TFixedImage, class TMovingImage > Image DualExecuteInternal( void ); friend struct detail::DualExecuteInternalAddressor< MemberFunctionType >; - template< class TFixedImage, class TMovingImage > Image DualExecuteInternal ( void ); - std::auto_ptr< detail::DualMemberFunctionFactory< MemberFunctionType > > m_DualMemberFactory; + nsstd::auto_ptr< detail::DualMemberFunctionFactory< MemberFunctionType > > m_DualMemberFactory; VectorOfImage m_FixedImages; VectorOfImage m_MovingImages; diff --git a/Code/Elastix/include/sitkSimpleElastix.hxx b/Code/Elastix/include/sitkSimpleElastix.hxx index 21384fa71..ec9975b4e 100644 --- a/Code/Elastix/include/sitkSimpleElastix.hxx +++ b/Code/Elastix/include/sitkSimpleElastix.hxx @@ -1,7 +1,8 @@ #ifndef __sitksimpleelastix_hxx_ #define __sitksimpleelastix_hxx_ -#include "sitkSimpleElastix.h" +#include "sitkPixelIDValues.h" +#include "sitkCastImageFilter.h" namespace itk { namespace simple { @@ -21,12 +22,12 @@ SimpleElastix::DualExecuteInternal( void ) for( unsigned int i = 0; i < this->GetNumberOfFixedImages(); ++i ) { - elastixFilter->AddFixedImage( itkDynamicCastInDebugMode< TFixedImage* >( this->GetFixedImage( i ).GetITKBase() ) ); + elastixFilter->AddFixedImage( itkDynamicCastInDebugMode< TFixedImage* >( Cast( this->GetFixedImage( i ), static_cast< PixelIDValueEnum >( GetPixelIDValueFromElastixString( "float" ) ) ).GetITKBase() ) ); } for( unsigned int i = 0; i < this->GetNumberOfMovingImages(); ++i ) { - elastixFilter->AddMovingImage( itkDynamicCastInDebugMode< TMovingImage* >( this->GetMovingImage( i ).GetITKBase() ) ); + elastixFilter->AddMovingImage( itkDynamicCastInDebugMode< TMovingImage* >( Cast( this->GetMovingImage( i ), static_cast< PixelIDValueEnum >( GetPixelIDValueFromElastixString( "float" ) ) ).GetITKBase() ) ); } for( unsigned int i = 0; i < this->GetNumberOfFixedMasks(); ++i ) @@ -48,13 +49,25 @@ SimpleElastix::DualExecuteInternal( void ) elastixFilter->SetLogToFile( this->GetLogToFile() ); elastixFilter->SetLogToConsole( this->GetLogToConsole() ); + ParameterMapVectorType parameterMapVector = this->m_ParameterMapVector; + for( unsigned int i = 0; i < parameterMapVector.size(); i++ ) + { + parameterMapVector[ i ][ "FixedInternalImagePixelType" ] + = ParameterValueVectorType( 1, "float" ); + parameterMapVector[ i ][ "MovingInternalImagePixelType" ] + = ParameterValueVectorType( 1, "float" ); + parameterMapVector[ i ][ "ResultImagePixelType" ] + = ParameterValueVectorType( 1, "float" ); + } + ParameterObjectPointer parameterObject = ParameterObjectType::New(); - parameterObject->SetParameterMap( this->m_ParameterMapVector ); + parameterObject->SetParameterMap( parameterMapVector ); elastixFilter->SetParameterObject( parameterObject ); elastixFilter->Update(); - this->m_ResultImage = Image( elastixFilter->GetOutput() ); + // Cast DataObject -> itk::Image< ResultImagePixelType, ImageDimension > -> sitk::Image + this->m_ResultImage = Cast( Image( itkDynamicCastInDebugMode< TFixedImage * >( elastixFilter->GetOutput() ) ), this->GetFixedImage( 0 ).GetPixelID() ); this->m_ResultImage.MakeUnique(); this->m_TransformParameterMapVector = elastixFilter->GetTransformParameterObject()->GetParameterMap(); } @@ -66,7 +79,6 @@ SimpleElastix::DualExecuteInternal( void ) return this->m_ResultImage; } - } // end namespace simple } // end namespace itk diff --git a/Code/Elastix/include/sitkSimpleTransformix.h b/Code/Elastix/include/sitkSimpleTransformix.h index f59430f0b..558634015 100644 --- a/Code/Elastix/include/sitkSimpleTransformix.h +++ b/Code/Elastix/include/sitkSimpleTransformix.h @@ -114,7 +114,7 @@ class SITKCommon_EXPORT SimpleTransformix typedef Image ( Self::*MemberFunctionType )( void ); template< class TMovingImage > Image ExecuteInternal( void ); friend struct detail::MemberFunctionAddressor< MemberFunctionType >; - std::auto_ptr< detail::MemberFunctionFactory< MemberFunctionType > > m_MemberFactory; + nsstd::auto_ptr< detail::MemberFunctionFactory< MemberFunctionType > > m_MemberFactory; Image m_MovingImage; Image m_ResultImage; diff --git a/Code/Elastix/include/sitkSimpleTransformix.hxx b/Code/Elastix/include/sitkSimpleTransformix.hxx index f5138f85b..270563f35 100644 --- a/Code/Elastix/include/sitkSimpleTransformix.hxx +++ b/Code/Elastix/include/sitkSimpleTransformix.hxx @@ -1,8 +1,8 @@ #ifndef __sitksimpletransformix_hxx_ #define __sitksimpletransformix_hxx_ -#include "sitkSimpleTransformix.h" - +#include "sitkCastImageFilter.h" + namespace itk { namespace simple { @@ -18,7 +18,7 @@ SimpleTransformix::ExecuteInternal( void ) TransforimxFilterPointer transformixFilter = TransformixFilterType::New(); if( !this->IsEmpty( this->m_MovingImage ) ) { - transformixFilter->SetMovingImage( static_cast< TMovingImage* >( this->GetMovingImage().GetITKBase() ) ); + transformixFilter->SetMovingImage( itkDynamicCastInDebugMode< TMovingImage* >( Cast( this->GetMovingImage(), static_cast< PixelIDValueEnum >( GetPixelIDValueFromElastixString( "float" ) ) ).GetITKBase() ) ); } transformixFilter->SetFixedPointSetFileName( this->GetFixedPointSetFileName() ); @@ -31,15 +31,23 @@ SimpleTransformix::ExecuteInternal( void ) transformixFilter->SetLogToFile( this->GetLogToFile() ); transformixFilter->SetLogToConsole( this->GetLogToConsole() ); + ParameterMapVectorType transformParameterMapVector = this->m_TransformParameterMapVector; + for( unsigned int i = 0; i < transformParameterMapVector.size(); i++ ) + { + transformParameterMapVector[ i ][ "FixedInternalImagePixelType" ] = ParameterValueVectorType( 1, "float" ); + transformParameterMapVector[ i ][ "MovingInternalImagePixelType" ] = ParameterValueVectorType( 1, "float" ); + transformParameterMapVector[ i ][ "ResultImagePixelType" ] = ParameterValueVectorType( 1, "float" ); + } + ParameterObjectPointer parameterObject = ParameterObjectType::New(); - parameterObject->SetParameterMap( this->m_TransformParameterMapVector ); + parameterObject->SetParameterMap( transformParameterMapVector ); transformixFilter->SetTransformParameterObject( parameterObject ); - transformixFilter->Update(); if( !this->IsEmpty( this->GetMovingImage() ) ) { - this->m_ResultImage = Image( transformixFilter->GetOutput() ); + // Cast DataObject -> itk::Image< ResultImagePixelType, ImageDimension -> sitk::Image + this->m_ResultImage = Cast( Image( itkDynamicCastInDebugMode< TMovingImage* >( transformixFilter->GetOutput() ) ), this->GetMovingImage().GetPixelID() ); this->m_ResultImage.MakeUnique(); } } diff --git a/Code/Elastix/src/CMakeLists.txt b/Code/Elastix/src/CMakeLists.txt index 4206bd633..93a9b75e3 100644 --- a/Code/Elastix/src/CMakeLists.txt +++ b/Code/Elastix/src/CMakeLists.txt @@ -1,20 +1,12 @@ -set ( ITK_NO_IO_FACTORY_REGISTER_MANAGER 1 ) +set( ITK_NO_IO_FACTORY_REGISTER_MANAGER 1 ) include( ${ITK_USE_FILE} ) -set( SimpleElastixSource - sitkSimpleElastix.cxx -) - -add_library( SimpleElastix ${SimpleElastixSource} ) +add_library( SimpleElastix sitkSimpleElastix.cxx ) set_target_properties( SimpleElastix PROPERTIES SKIP_BUILD_RPATH TRUE ) target_link_libraries( SimpleElastix elastix SimpleITKCommon ) sitk_install_exported_target( SimpleElastix ) -set( SimpleTransformixSource - sitkSimpleTransformix.cxx -) - -add_library( SimpleTransformix ${SimpleTransformixSource} ) +add_library( SimpleTransformix sitkSimpleTransformix.cxx ) set_target_properties( SimpleTransformix PROPERTIES SKIP_BUILD_RPATH TRUE ) target_link_libraries( SimpleTransformix transformix SimpleITKCommon ) -sitk_install_exported_target( SimpleTransformix ) +sitk_install_exported_target( SimpleTransformix ) diff --git a/Code/Elastix/src/sitkSimpleElastix.cxx b/Code/Elastix/src/sitkSimpleElastix.cxx index 5f9f7eb05..72ef00992 100644 --- a/Code/Elastix/src/sitkSimpleElastix.cxx +++ b/Code/Elastix/src/sitkSimpleElastix.cxx @@ -12,11 +12,11 @@ ::SimpleElastix( void ) { // Register this class with SimpleITK this->m_DualMemberFactory.reset( new detail::DualMemberFunctionFactory< MemberFunctionType >( this ) ); - this->m_DualMemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, BasicPixelIDTypeList, 2 >(); - this->m_DualMemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, BasicPixelIDTypeList, 3 >(); + this->m_DualMemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, FloatPixelIDTypeList, 2 >(); + this->m_DualMemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, FloatPixelIDTypeList, 3 >(); #ifdef SITK_4D_IMAGES - this->m_DualMemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, BasicPixelIDTypeList, 4 >(); + this->m_DualMemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, FloatPixelIDTypeList, 4 >(); #endif m_FixedImages = VectorOfImage(); diff --git a/Code/Elastix/src/sitkSimpleTransformix.cxx b/Code/Elastix/src/sitkSimpleTransformix.cxx index 018428375..7ea625f3c 100644 --- a/Code/Elastix/src/sitkSimpleTransformix.cxx +++ b/Code/Elastix/src/sitkSimpleTransformix.cxx @@ -14,11 +14,11 @@ ::SimpleTransformix( void ) { // Register this class with SimpleITK this->m_MemberFactory.reset( new detail::MemberFunctionFactory< MemberFunctionType >( this ) ); - this->m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 2 >(); - this->m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 3 >(); + this->m_MemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, 2 >(); + this->m_MemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, 3 >(); #ifdef SITK_4D_IMAGES - m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 4 >(); + m_MemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, 4 >(); #endif this->m_MovingImage = Image(); diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index b6f2ee7b7..2f96999c7 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -14,6 +14,11 @@ if(NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK") find_package(SimpleITK REQUIRED) include(${SimpleITK_USE_FILE}) + # SimpleElastix further requires ITK + find_package(ITK) + set(ITK_NO_IO_FACTORY_REGISTER_MANAGER 1) + include(${ITK_USE_FILE}) + # Add compiler flags needed to use SimpleITK. set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SimpleITK_REQUIRED_C_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SimpleITK_REQUIRED_CXX_FLAGS}") @@ -23,10 +28,10 @@ if(NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK") endif() # Add individual cxx executables -add_executable ( SimpleElastix1 SimpleElastix.cxx ) +add_executable ( SimpleElastix1 SimpleElastix1.cxx ) target_link_libraries ( SimpleElastix1 ${SimpleITK_LIBRARIES} ) -add_executable ( SimpleTransformix1 SimpleTransformix.cxx ) +add_executable ( SimpleTransformix1 SimpleTransformix1.cxx ) target_link_libraries ( SimpleTransformix1 ${SimpleITK_LIBRARIES} ) add_executable ( SimpleGaussian SimpleGaussian.cxx ) diff --git a/Examples/ITKIntegration/CMakeLists.txt b/Examples/ITKIntegration/CMakeLists.txt index de791673f..73aa7ed6b 100644 --- a/Examples/ITKIntegration/CMakeLists.txt +++ b/Examples/ITKIntegration/CMakeLists.txt @@ -1,7 +1,3 @@ - -find_package(ITK REQUIRED ) -include(${ITK_USE_FILE}) - add_executable ( ITKIntegration ITKIntegration.cxx ) target_link_libraries ( ITKIntegration ${SimpleITK_LIBRARIES} ) diff --git a/Examples/ITKIntegration/ElastixFilter.cxx b/Examples/ITKIntegration/ElastixFilter.cxx index c78976be9..c6822abe8 100644 --- a/Examples/ITKIntegration/ElastixFilter.cxx +++ b/Examples/ITKIntegration/ElastixFilter.cxx @@ -27,7 +27,7 @@ int main( int argc, char* argv[] ) { typedef MovingImageReaderType::Pointer MovingImageReaderPointer; typedef itk::ImageFileWriter< ImageType > ResultImageWriterType; - typedef ResultImageWriterType::Pointer ResultImageWriterPointer; + typedef ResultImageWriterType::Pointer ResultImageWriterPointer; try { diff --git a/Examples/SimpleElastix.cxx b/Examples/SimpleElastix1.cxx similarity index 97% rename from Examples/SimpleElastix.cxx rename to Examples/SimpleElastix1.cxx index 2c95ae7c2..9e5392d06 100644 --- a/Examples/SimpleElastix.cxx +++ b/Examples/SimpleElastix1.cxx @@ -23,9 +23,9 @@ int main ( int argc, char* argv[] ) { reader.SetFileName( std::string( argv[2] ) ); elastix.SetMovingImage( reader.Execute() ); elastix.SetParameterMap( sitk::ReadParameterFile( std::string( argv[3] ) ) ); - - // Perform registration elastix.LogToConsoleOn(); + + // Run registration elastix.Execute(); // Write result image diff --git a/Examples/SimpleTransformix.cxx b/Examples/SimpleTransformix1.cxx similarity index 98% rename from Examples/SimpleTransformix.cxx rename to Examples/SimpleTransformix1.cxx index 34ec15633..769e1782e 100644 --- a/Examples/SimpleTransformix.cxx +++ b/Examples/SimpleTransformix1.cxx @@ -26,14 +26,14 @@ int main ( int argc, char* argv[] ) { // Instantiate transformix sitk::SimpleTransformix transformix; + transformix.LogToConsoleOn(); // Read input reader.SetFileName( std::string( argv[4] ) ); transformix.SetMovingImage( reader.Execute() ); transformix.SetTransformParameterMap( elastix.GetTransformParameterMap() ); - // Perform warp - transformix.LogToConsoleOn(); + // Run warp transformix.Execute(); // Write result image diff --git a/SuperBuild/External_Elastix.cmake b/SuperBuild/External_Elastix.cmake index bacb6df36..1e26f5213 100644 --- a/SuperBuild/External_Elastix.cmake +++ b/SuperBuild/External_Elastix.cmake @@ -13,6 +13,13 @@ file( WRITE "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" "${ep set( ELASTIX_GIT_REPOSITORY ${git_protocol}://github.com/kaspermarstal/elastix ) set( ELASTIX_GIT_TAG 54e5a7c4513bb36374c18d05951de7354f5837ca ) +if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) + set( ELASTIX_BUILD_SHARED_LIBS ON ) +else() + set( ELASTIX_BUILD_SHARED_LIBS OFF ) + list( APPEND ep_itk_args"-DCMAKE_C_VISIBILITY_PRESET:BOOL=hidden" "-DCMAKE_CXX_VISIBILITY_PRESET:BOOL=hidden" ) +endif() + ExternalProject_Add( ${proj} GIT_REPOSITORY ${ELASTIX_GIT_REPOSITORY} GIT_TAG ${ELASTIX_GIT_TAG} @@ -30,7 +37,9 @@ ExternalProject_Add( ${proj} -DELASTIX_BUILD_SHARED_LIBS:BOOL=${ELASTIX_BUILD_SHARED_LIBS} -DCMAKE_INSTALL_PREFIX:PATH= -DITK_DIR:PATH=${ITK_DIR} - -DUSE_ALL_PIXELTYPES:BOOL=ON + -DELASTIX_IMAGE_2D_PIXELTYPES:STRING=float + -DELASTIX_IMAGE_3D_PIXELTYPES:STRING=float + -DELASTIX_IMAGE_4D_PIXELTYPES:STRING=float -DUSE_AdaptiveStochasticGradientDescent:BOOL=ON -DUSE_AdvancedAffineTransformElastix:BOOL=ON -DUSE_AdvancedBSplineTransform:BOOL=ON From bce38b7e2c51c4d0258d738a527316c28307ca20 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Tue, 6 Sep 2016 16:06:07 +0200 Subject: [PATCH 387/412] BUG: Update tests for filter interface changes --- Testing/Unit/sitkElastixFilterTests.cxx | 2 +- Testing/Unit/sitkImage4DTests.cxx | 5 +++-- Testing/Unit/sitkTransformixFilterTests.cxx | 10 +++++----- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/Testing/Unit/sitkElastixFilterTests.cxx b/Testing/Unit/sitkElastixFilterTests.cxx index 0ca0750a4..7b40b0f5b 100644 --- a/Testing/Unit/sitkElastixFilterTests.cxx +++ b/Testing/Unit/sitkElastixFilterTests.cxx @@ -298,7 +298,7 @@ TEST( ElastixFilterTest, InverseTransformTestEuler2D ) // Warp fixed image to moving image with the inverse transform TransformixFilterType::Pointer transformixFilter = TransformixFilterType::New(); - EXPECT_NO_THROW( transformixFilter->SetInput( inputImageReader->GetOutput() ) ); + EXPECT_NO_THROW( transformixFilter->SetMovingImage( inputImageReader->GetOutput() ) ); EXPECT_NO_THROW( transformixFilter->SetTransformParameterObject( inverseTransformParameterObject ) ); ImageFileWriterType::Pointer writer = ImageFileWriterType::New(); diff --git a/Testing/Unit/sitkImage4DTests.cxx b/Testing/Unit/sitkImage4DTests.cxx index 3bd6fbd95..443c554fa 100644 --- a/Testing/Unit/sitkImage4DTests.cxx +++ b/Testing/Unit/sitkImage4DTests.cxx @@ -49,11 +49,10 @@ const double adir[] = { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0 }; using itk::simple::InstantiatedPixelIDTypeList; -namespace sitk = itk::simple; class Image4D : public ::testing::Test { public: - typedef nsstd::auto_ptr sitkAutoImagePointer; + typedef itk::simple::nsstd::auto_ptr sitkAutoImagePointer; virtual void SetUp() { itk::ImageBase<4>::IndexType index; @@ -401,6 +400,8 @@ TEST_F( Image4D,Properties ) { ASSERT_ANY_THROW( shortImage->SetDirection( std::vector( adir, adir + 8 ) ) ); } +namespace sitk = itk::simple; + TEST_F( Image4D, CopyInformation ) { std::vector s4d(4,10); diff --git a/Testing/Unit/sitkTransformixFilterTests.cxx b/Testing/Unit/sitkTransformixFilterTests.cxx index ee839328c..eb3fd3c68 100644 --- a/Testing/Unit/sitkTransformixFilterTests.cxx +++ b/Testing/Unit/sitkTransformixFilterTests.cxx @@ -40,7 +40,7 @@ TEST( TransformixFilterTest, UpdateOnDownstreamUpdate ) TransformixFilterType::Pointer transformixFilter; EXPECT_NO_THROW( transformixFilter = TransformixFilterType::New() ); - EXPECT_NO_THROW( transformixFilter->SetInput( movingImageReader->GetOutput() ) ); + EXPECT_NO_THROW( transformixFilter->SetMovingImage( movingImageReader->GetOutput() ) ); EXPECT_NO_THROW( transformixFilter->SetOutputDirectory( dataFinder.GetOutputDirectory() ) ); EXPECT_NO_THROW( transformixFilter->SetTransformParameterObject( elastixFilter->GetTransformParameterObject() ) ); @@ -72,7 +72,7 @@ TEST( TransformixFilterTest, GetInputImageFromElastixFilter ) TransformixFilterType::Pointer transformixFilter; EXPECT_NO_THROW( transformixFilter = TransformixFilterType::New() ); - EXPECT_NO_THROW( transformixFilter->SetInput( elastixFilter->GetOutput() ) ); + EXPECT_NO_THROW( transformixFilter->SetMovingImage( elastixFilter->GetOutput() ) ); EXPECT_NO_THROW( transformixFilter->SetTransformParameterObject( elastixFilter->GetTransformParameterObject() ) ); EXPECT_NO_THROW( transformixFilter->SetOutputDirectory( dataFinder.GetOutputDirectory() ) ); @@ -229,9 +229,9 @@ TEST( TransformixFilterTest, SameTransformParameterMapForMultipleTransformations EXPECT_NO_THROW( transformixFilter = TransformixFilterType::New() ); EXPECT_NO_THROW( transformixFilter->SetOutputDirectory( dataFinder.GetOutputDirectory() ) ); EXPECT_NO_THROW( transformixFilter->SetTransformParameterObject( elastixFilter->GetTransformParameterObject() ) ); - EXPECT_NO_THROW( transformixFilter->SetInput( movingImageReader1->GetOutput() ) ); + EXPECT_NO_THROW( transformixFilter->SetMovingImage( movingImageReader1->GetOutput() ) ); EXPECT_NO_THROW( transformixFilter->Update() ); - EXPECT_NO_THROW( transformixFilter->SetInput( movingImageReader2->GetOutput() ) ); + EXPECT_NO_THROW( transformixFilter->SetMovingImage( movingImageReader2->GetOutput() ) ); EXPECT_NO_THROW( transformixFilter->Update() ); } @@ -260,7 +260,7 @@ TEST( TransformixFilterTest, BSpline4D ) TransformixFilterType::Pointer transformixFilter; EXPECT_NO_THROW( transformixFilter = TransformixFilterType::New() ); - EXPECT_NO_THROW( transformixFilter->SetInput( imageReader->GetOutput() ) ); + EXPECT_NO_THROW( transformixFilter->SetMovingImage( imageReader->GetOutput() ) ); EXPECT_NO_THROW( transformixFilter->SetTransformParameterObject( elastixFilter->GetTransformParameterObject() ) ); ImageFileWriterType::Pointer writer = ImageFileWriterType::New(); From 8a0b51f5503e9c446d9e3ac021f4b1803bb65b96 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 7 Sep 2016 15:21:32 +0200 Subject: [PATCH 388/412] BUG: Remove member function factory pixel type guard --- Code/Elastix/src/sitkSimpleElastix.cxx | 47 +++++++++++++++------- Code/Elastix/src/sitkSimpleTransformix.cxx | 7 ++-- 2 files changed, 36 insertions(+), 18 deletions(-) diff --git a/Code/Elastix/src/sitkSimpleElastix.cxx b/Code/Elastix/src/sitkSimpleElastix.cxx index 72ef00992..ddf90910f 100644 --- a/Code/Elastix/src/sitkSimpleElastix.cxx +++ b/Code/Elastix/src/sitkSimpleElastix.cxx @@ -855,25 +855,41 @@ ::Execute( void ) for( unsigned int i = 1; i < this->GetNumberOfFixedImages(); ++i ) { - if( this->GetFixedImage( i ).GetPixelID() != FixedImagePixelID ) + if( this->GetFixedImage( i ).GetDimension() != FixedImageDimension ) { - sitkExceptionMacro( "Fixed images must be of same pixel type (fixed image at index 0 is of type " - << GetPixelIDValueAsElastixParameter( this->GetFixedImage( 0 ).GetPixelID() ) << ", " - << "fixed image at index " << i << " is of type \"" - << GetPixelIDValueAsElastixParameter( this->GetFixedImage( i ).GetPixelID() ) - << "\")." ); + sitkExceptionMacro( "Fixed images must be of same dimension (fixed image at index 0 is of dimension " + << this->GetFixedImage( 0 ).GetDimension() << ", fixed image at index " << i + << " is of dimension \"" << this->GetFixedImage( i ).GetDimension() << "\")." ); } } for( unsigned int i = 1; i < this->GetNumberOfMovingImages(); ++i ) { - if( this->GetMovingImage( i ).GetPixelID() != MovingImagePixelID ) + if( this->GetMovingImage( i ).GetDimension() != FixedImageDimension ) { - sitkExceptionMacro( "Moving images must be of same pixel type (moving image at index 0 is of type " - << GetPixelIDValueAsElastixParameter( this->GetMovingImage( 0 ).GetPixelID() ) << ", " - << "moving image at index " << i << " is of type \"" - << GetPixelIDValueAsElastixParameter( this->GetMovingImage( i ).GetPixelID() ) - << "\")." ); + sitkExceptionMacro( "Moving images must be of same dimension as fixed images (fixed image at index 0 is of dimension " + << this->GetFixedImage( 0 ).GetDimension() << ", moving image at index " << i + << " is of dimension \"" << this->GetMovingImage( i ).GetDimension() << "\")." ); + } + } + + for( unsigned int i = 1; i < this->GetNumberOfFixedMasks(); ++i ) + { + if( this->GetFixedMask( i ).GetDimension() != FixedImageDimension ) + { + sitkExceptionMacro( "Fixed masks must be of same dimension as fixed images (fixed images are of dimension " + << this->GetFixedImage( 0 ).GetDimension() << ", fixed mask at index " << i + << " is of dimension \"" << this->GetFixedMask( i ).GetDimension() << "\")." ); + } + } + + for( unsigned int i = 1; i < this->GetNumberOfMovingMasks(); ++i ) + { + if( this->GetMovingMask( i ).GetDimension() != FixedImageDimension ) + { + sitkExceptionMacro( "Moving masks must be of same dimension as moving images (moving images are of dimension " + << this->GetMovingImage( 0 ).GetDimension() << ", moving mask at index " << i + << " is of dimension \"" << this->GetMovingMask( i ).GetDimension() << "\")." ); } } @@ -895,16 +911,17 @@ ::Execute( void ) } } - if( this->m_DualMemberFactory->HasMemberFunction( FixedImagePixelID, MovingImagePixelID, FixedImageDimension ) ) + if( this->m_DualMemberFactory->HasMemberFunction( sitkFloat32, sitkFloat32, FixedImageDimension ) ) { - return this->m_DualMemberFactory->GetMemberFunction( FixedImagePixelID, MovingImagePixelID, FixedImageDimension )(); + return this->m_DualMemberFactory->GetMemberFunction( sitkFloat32, sitkFloat32, FixedImageDimension )(); } sitkExceptionMacro( << "SimpleElastix does not support the combination of " << FixedImageDimension << "-dimensional " << GetPixelIDValueAsElastixParameter( FixedImagePixelID ) << " fixed image and a " << MovingImageDimension << "-dimensional " - << GetPixelIDValueAsElastixParameter( FixedImagePixelID ) << " moving image." ) + << GetPixelIDValueAsElastixParameter( MovingImagePixelID ) << " moving image. " + << "This a serious error. Contact developers at https://github.com/kaspermarstal/SimpleElastix/issues." ) } SimpleElastix::ParameterMapVectorType diff --git a/Code/Elastix/src/sitkSimpleTransformix.cxx b/Code/Elastix/src/sitkSimpleTransformix.cxx index 7ea625f3c..32a0970a5 100644 --- a/Code/Elastix/src/sitkSimpleTransformix.cxx +++ b/Code/Elastix/src/sitkSimpleTransformix.cxx @@ -535,14 +535,15 @@ ::Execute( void ) const PixelIDValueEnum MovingImagePixelEnum = this->m_MovingImage.GetPixelID(); const unsigned int MovingImageDimension = this->m_MovingImage.GetDimension(); - if( this->m_MemberFactory->HasMemberFunction( MovingImagePixelEnum, MovingImageDimension ) ) + if( this->m_MemberFactory->HasMemberFunction( sitkFloat32, MovingImageDimension ) ) { - return this->m_MemberFactory->GetMemberFunction( MovingImagePixelEnum, MovingImageDimension )(); + return this->m_MemberFactory->GetMemberFunction( sitkFloat32, MovingImageDimension )(); } sitkExceptionMacro( << "SimpleTransformix does not support the combination of image type " << GetPixelIDValueAsElastixParameter( MovingImagePixelEnum ) << " and dimension " - << MovingImageDimension << "." ); + << MovingImageDimension << ". This a serious error. " + << "Contact developers at https://github.com/kaspermarstal/SimpleElastix/issues." ); } Image From b2dd9264ab5e0eb03562b8fc0919e4e95bab0c06 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Fri, 9 Sep 2016 14:15:01 +0200 Subject: [PATCH 389/412] DOC: Update documentation --- Documentation/source/AffineRegistration.rst | 24 ++++++------ Documentation/source/GetDeformationField.rst | 2 + .../source/GroupwiseRegistration.rst | 10 ++--- Documentation/source/HelloWorld.rst | 39 +++++++++---------- Documentation/source/Introduction.rst | 2 +- Documentation/source/NonRigidRegistration.rst | 12 +++--- Documentation/source/ParameterMaps.rst | 37 ++++++++++++------ Documentation/source/RegisterDICOMs.rst | 1 + Documentation/source/RigidRegistration.rst | 12 +++--- 9 files changed, 77 insertions(+), 62 deletions(-) create mode 100644 Documentation/source/GetDeformationField.rst create mode 100644 Documentation/source/RegisterDICOMs.rst diff --git a/Documentation/source/AffineRegistration.rst b/Documentation/source/AffineRegistration.rst index 5926c79bb..377cfddb0 100644 --- a/Documentation/source/AffineRegistration.rst +++ b/Documentation/source/AffineRegistration.rst @@ -24,12 +24,12 @@ The image on the right has been sheared, scaled 1.2x, rotated 10 degrees and tra import SimpleITK as sitk - elastix = sitk.SimpleElastix() - elastix.SetFixedImage(sitk.ReadImage("fixedImage.nii") - elastix.SetMovingImage(sitk.ReadImage(movingImage.nii") - elastix.SetParameterMap(sitk.GetDefaultParameterMap("affine")) - elastix.Execute() - sitk.WriteImage(elastix.GetResultImage()) + SimpleElastix = sitk.SimpleElastix() + SimpleElastix.SetFixedImage(sitk.ReadImage("fixedImage.nii") + SimpleElastix.SetMovingImage(sitk.ReadImage(movingImage.nii") + SimpleElastix.SetParameterMap(sitk.GetDefaultParameterMap("affine")) + SimpleElastix.Execute() + sitk.WriteImage(SimpleElastix.GetResultImage()) It is clear from the result mean image on right in Fig. 11 that registration was successful. @@ -52,13 +52,13 @@ Notice that the only difference from the previous example is the requested param import SimpleITK as sitk - elastix = sitk.SimpleElastix() - elastix.SetFixedImage(sitk.ReadImage("fixedImage.nii") - elastix.SetMovingImage(sitk.ReadImage(movingImage.nii") + SimpleElastix = sitk.SimpleElastix() + SimpleElastix.SetFixedImage(sitk.ReadImage("fixedImage.nii") + SimpleElastix.SetMovingImage(sitk.ReadImage(movingImage.nii") parameterMap = sitk.GetDefaultParameterMap("rigid") parameterMap["Transform"] = ["AffineTransform"] - elastix.SetParameterMap() - elastix.Execute() - sitk.WriteImage(elastix.GetResultImage()) + SimpleElastix.SetParameterMap() + SimpleElastix.Execute() + sitk.WriteImage(SimpleElastix.GetResultImage()) This demonstrates how easy it is to try out different registration components with SimpleElastix. In the next example we will introduce non-rigid registration and initialize the moving image with an affine transform. \ No newline at end of file diff --git a/Documentation/source/GetDeformationField.rst b/Documentation/source/GetDeformationField.rst new file mode 100644 index 000000000..a481a4746 --- /dev/null +++ b/Documentation/source/GetDeformationField.rst @@ -0,0 +1,2 @@ +GetDeformationField +=================== \ No newline at end of file diff --git a/Documentation/source/GroupwiseRegistration.rst b/Documentation/source/GroupwiseRegistration.rst index 6456cdd59..fc046723e 100644 --- a/Documentation/source/GroupwiseRegistration.rst +++ b/Documentation/source/GroupwiseRegistration.rst @@ -34,11 +34,11 @@ Elastix takes a single N+1 dimensional image for groupwise registration. Therefo image = sitk.JoinSeries(vectorOfImages) # Register - elastix = sitk.SimpleElastix() - elastix.SetFixedImage(image) - elastix.SetMovingImage(image) - elastix.SetParameterMap(selx.GetDefaultParameterMap('groupwise')) - elastix.Execute() + SimpleElastix = sitk.SimpleElastix() + SimpleElastix.SetFixedImage(image) + SimpleElastix.SetMovingImage(image) + SimpleElastix.SetParameterMap(sitk.GetDefaultParameterMap('groupwise')) + SimpleElastix.Execute() While the groupwise transform works only on the moving image we need to pass a dummy fixed image is to prevent elastix from throwing errors. This does not consume extra memory as only pointers are passed internally. diff --git a/Documentation/source/HelloWorld.rst b/Documentation/source/HelloWorld.rst index 82b64132b..be0781ebc 100644 --- a/Documentation/source/HelloWorld.rst +++ b/Documentation/source/HelloWorld.rst @@ -1,7 +1,7 @@ Hello World =========== -This example illustrates the easiest way to use SimpleElastix. With a single function call we can specify the fixed image, the moving image and the type of registration you want to perform. SimpleElastix will then register our images using sensible default parameters that work well in most cases. In later examples we shall see how to tweak the default parameters, but for now we keep it simple for illustrative purposes. +This example illustrates how to use SimpleElastix. With a single function call we can specify the fixed image, the moving image and the type of registration you want to perform. SimpleElastix will then register our images using sensible default parameters that work well in most cases. In later examples we shall see how to tweak the default parameters, but for now we keep it simple. Registration With Translation Transform --------------------------------------- @@ -33,13 +33,13 @@ We identify that the objects are related by a simple spatial shift and that a tr "translation") -That's it! We have effectively registered two images using a robust multi-resolution approach with a single line of code. Compare this to the `ITK Hello World example `_. We refer to this short-hand notation as the procedural interface because it consists of functions that accomplish a specific task. The procedural interface is less flexible than the object-oriented interface (introduced below) but very simple to use. Let's break down what goes on. +That's it! We have effectively registered two images using a rsingle line of code. Compare this to the `ITK Hello World example `_. We refer to this short-hand notation as the procedural interface (some people also refer to it as the functional interface) because it consists of functions that accomplish a specific task. The procedural interface is less flexible than the object-oriented interface introduced below, but it is very simple to use. Let's break down what goes on under the hood of this single function call. -:code:`import SimpleITK as sitk` loads the SimpleITK module from which SimpleElastix is accessed (the main module has retained its SimpleITK name for compatibility reasons). This assumes that SimpleElastix has been compiled and installed on your machine. +First of all, :code:`import SimpleITK as sitk` loads the SimpleITK module from which SimpleElastix is accessed. This assumes that SimpleElastix has been compiled and installed on your machine. -:code:`sitk.ReadImage()` is the generic image file reader of SimpleITK which loads an image from disk and pass a SimpleITK image object to SimpleElastix. You can apply any SimpleITK filter to the fixed and moving image before passing them to SimpleElastix. +:code:`sitk.ReadImage()` is the generic image file reader of SimpleITK which loads an image from disk and pass a SimpleITK image object to SimpleElastix. You can also apply a SimpleITK filter to an image before passing them to SimpleElastix. For example, you could use the :code:`ResampleImageFilter()` to downsample images that would otherwise consume too much memory during registration. -The final parameter :code:`"translation"` specifies the desired type of registration. In the Parameter Maps section we will take a close look at parameter maps and examine what what happens under the hood when you specify this parameter. It is obvious from the figure below that a translation transform is sufficient to align these images. +The final parameter :code:`"translation"` specifies the desired type of registration. In the Parameter Maps section we will take a close look at parameter maps and examine what happens when you specify this parameter. It is obvious from the figure below that a translation transform is sufficient to align these images. .. _fig2: @@ -57,7 +57,7 @@ The final parameter :code:`"translation"` specifies the desired type of registra Object-Oriented Interface ------------------------- -The example above used procedural-style function call. While the procedural interface may be useful in rapid prototyping, it trades off flexibility for code simplicity. For example, the final deformation field cannot be retrived and applied to another image. This is a problem if we want to subsequently warp other images, e.g. a label image, using the same transformation. Further, image quality is reduced from resampling the resulting image twice. To this end, SimpleElastix comes with a powerful object-oriented interface suitable for more advanced use cases and scripting purposes. In the next example, we perform the same Hello World example, but this time using the object oriented interface: +The example above used procedural interface. While the procedural interface may be useful for rapid prototyping, it trades off flexibility for code simplicity. For example, the final deformation field cannot be retrived and applied to another image. This is a problem if we want to subsequently warp other images, e.g. a label image, using the same transformation. Further, image quality is reduced from resampling the resulting image twice. To this end, SimpleElastix comes with a more flexible object-oriented interface suitable for more advanced use cases and scripting purposes. In the next example, we perform the same registration as above, but this time using the object oriented interface: :: @@ -67,29 +67,28 @@ The example above used procedural-style function call. While the procedural inte movingImage = sitk.ReadImage('movingImage.nii') parameterMap = sitk.GetDefaultParameterMap('translation') - elastix = sitk.SimpleElastix() - elastix.SetFixedImage(fixedImage) - elastix.SetMovingImage(movingImage) - elastix.SetParameterMap(parameterMap) + SimpleElastix = sitk.SimpleElastix() + SimpleElastix.SetFixedImage(fixedImage) + SimpleElastix.SetMovingImage(movingImage) + SimpleElastix.SetParameterMap(parameterMap) + SimpleElastix.Execute() - elastix.Execute() + resultImage = SimpleElastix.GetResultImage() + transformParameterMap = SimpleElastix.GetTransformParameterMap() - resultImage = elastix.GetResultImage() - transformParameterMap = elastix.GetTransformParameterMap() - -This is more verbose but also a lot more powerful. We can now warp an entire population of images (e.g. binary images of segmented brain regions) using the same parameter map and a single instance of transformix: +This is more verbose but also a lot more powerful. We can now warp an entire population of images (e.g. binary label images for segmentation of different brain regions) using the same parameter map and a single instance of transformix: :: - transformix = sitk.SimpleTransformix() - transformix.SetParameterMap(transformParameterMap) + SimpleTransformix = sitk.SimpleTransformix() + SimpleTransformix.SetTransformParameterMap(transformParameterMap) population = ['image1.hdr', 'image2.hdr', ... , 'imageN.hdr'] for filename in population: - transformix.SetInputImage(sitk.ReadImage(filename)) - transformix.Execute() - sitk.WriteImage(transformix.GetResultImage(), "result_"+filename) + SimpleTransformix.SetMovingImage(sitk.ReadImage(filename)) + SimpleTransformix.Execute() + sitk.WriteImage(SimpleTransformix.GetResultImage(), "result_"+filename) The object-oriented interface facilitates reuse of components and dramatically simplifies book-keeping and boilerplate code. We will use the object-oriented interface from this point forward. diff --git a/Documentation/source/Introduction.rst b/Documentation/source/Introduction.rst index 0c86c32ec..56b558375 100644 --- a/Documentation/source/Introduction.rst +++ b/Documentation/source/Introduction.rst @@ -17,7 +17,7 @@ A significant amount of research has focused on developing the registration algo SimpleElastix ------------- -Elastix \cite{Klein2010} is an open source, command-line program for intensity-based registration of medical images that allows the user to quickly configure, test, and compare different registration methods. SimpleElastix is an extension of SimpleITK \cite{Lowekamp2013} that allows you to configure and run Elastix entirely in Python, Java, R, Octave, Ruby, Lua, Tcl and C\# on Linux, Mac and Windows. The goal is to bring robust registration algorithms to a wider audience and make it easier to use elastix for e.g. Java-based enterprise applications or rapid Python prototyping. +Elastix \cite{Klein2010} is an open source, command-line program for intensity-based registration of medical images that allows the user to quickly configure, test, and compare different registration methods. SimpleElastix is an extension of SimpleITK \cite{Lowekamp2013} that allows you to configure and run Elastix entirely in Python, Java, R, Octave, Ruby, Lua, Tcl and C\# on Linux, Mac and Windows. The goal is to bring robust registration algorithms to a wider audience and make it easier to use elastix, e.g. for Java-based enterprise applications or rapid Python prototyping. A lot of research has focused on making SimpleElastix computationally efficient and easy to use. Stochastic sampling (Klein et al. 2007), multi-threading and code optimizations (Shamonin et al 2014) makes registration run fast without sacrificing robustness. A simple parameter interface and modular architecture allows you to configure registration components at runtime and easily try out different registration methods. diff --git a/Documentation/source/NonRigidRegistration.rst b/Documentation/source/NonRigidRegistration.rst index 329a9fd31..bc7384e09 100644 --- a/Documentation/source/NonRigidRegistration.rst +++ b/Documentation/source/NonRigidRegistration.rst @@ -20,17 +20,17 @@ The following code runs multi-resolution affine initialization and starts a non- import SimpleITK as sitk - elastix = sitk.SimpleElastix() - elastix.SetFixedImage(sitk.ReadImage("fixedImage.nii")) - elastix.SetMovingImage(sitk.ReadImage("movingImage.nii")) + SimpleElastix = sitk.SimpleElastix() + SimpleElastix.SetFixedImage(sitk.ReadImage("fixedImage.nii")) + SimpleElastix.SetMovingImage(sitk.ReadImage("movingImage.nii")) parameterMapVector = sitk.VectorOfParameterMap() parameterMapVector.append(sitk.GetDefaultParameterMap("affine")) parameterMapVector.append(sitk.GetDefaultParameterMap("bspline")) - elastix.SetParameterMap(parameterMapVector) + SimpleElastix.SetParameterMap(parameterMapVector) - elastix.Execute() - sitk.WriteImage(elastix.GetResultImage()) + SimpleElastix.Execute() + sitk.WriteImage(SimpleElastix.GetResultImage()) The result image is seen below. diff --git a/Documentation/source/ParameterMaps.rst b/Documentation/source/ParameterMaps.rst index d02e92b1b..f708cfa1d 100644 --- a/Documentation/source/ParameterMaps.rst +++ b/Documentation/source/ParameterMaps.rst @@ -30,11 +30,11 @@ SimpleElastix can read these types of files as well but further introduces nativ import SimpleITK as sitk p = sitk.ParameterMap() - p["Registration"] = ["MultiResolutionRegistration"] - p["Transform"] = ["TranslationTransform"] + p['Registration'] = ['MultiResolutionRegistration'] + p['Transform'] = ['TranslationTransform'] ... -We can also load one of the default parameter maps and tweak its settings to get started more quickly, however, as shown in the following section. +and so on. Elastix has default settings for most parameters, but still, there are quite a lot of parameters to be set. While we can specify a parameter map scratch as above, we can also load one of the default parameter maps and tweak its settings to get started more quickly, as shown in the following section. The Default Parameter Maps -------------------------- @@ -42,26 +42,39 @@ In the Hello World example we obtained a registered image by running :: - resultImage = sitk.Elastix(sitk.ReadImage("fixedImage.nii"), \ - sitk.ReadImage("movingImage.nii"), \ - "translation") + resultImage = sitk.Elastix(sitk.ReadImage('fixedImage.nii'), \ + sitk.ReadImage('movingImage.nii'), \ + 'translation') -Internally, SimpleElastix passes images along with a parameter map to elastix and invokes registration. The parameter map is returned by a call to :code:`sitk.GetDefaultParameterFile('translation')`. This function provides parameter maps for rigid, affine, non-rigid and groupwise registration methods (in order of increasing complexity). The returned parameter object can be reconfigured and passed back to SimpleElastix allowing you to quickly optimize the registration method to your particular problem: +Internally, SimpleElastix passes images along with a parameter map to elastix and invokes registration. The parameter map is returned by an internal call to :code:`sitk.GetDefaultParameterFile('translation')`. This function provides parameter maps for rigid, affine, non-rigid and groupwise registration methods (in order of increasing complexity). + +.. tip:: + + You can also leave out the parameter map parameter entirely, and SimpleElastix with register your images with a :code:`translation -> affine -> b-spline` multi-resolution approach. Similarly, for the object-oriented interface, simply leave out the call to :code:`SetParameterMap` to achieve this functionality. You can view these default parameter maps like this: + + :: + + import SimpleITK as sitk + SimpleElastix = sitk.SimpleElastix() + parameterMaps = SimpleElastaix.GetParameterMaps() + sitk.PrintParameterMaps(parameterMaps) + +You can also retrieve this parameter map yourself and reconfigure it before passing it back to SimpleElastix, allowing you to quickly optimize a registration method to your particular problem: :: parameterMap = sitk.GetDefaultParameterMap('translation') # Use a non-rigid transform instead of a translation transform - parameterMap["Transform"] = ["BSplineTransform"] + parameterMap['Transform'] = ['BSplineTransform'] - # Because of the increased complexity of the b-sbpline transform, + # Because of the increased complexity of the b-spline transform, # it is a good idea to run the registration a little longer to # ensure convergence - parameterMap["MaximumNumberOfIterations"] = ["512"] + parameterMap['MaximumNumberOfIterations'] = ['512'] - resultImage = sitk.Elastix(sitk.ReadImage("fixedImage.nii"), \ - sitk.ReadImage("movingImage.nii"), \ + resultImage = sitk.Elastix(sitk.ReadImage('fixedImage.nii'), \ + sitk.ReadImage('movingImage.nii'), \ parameterMap) We will study other parameter maps more closely in later examples. For now, we simply print the translation parameter map to console. diff --git a/Documentation/source/RegisterDICOMs.rst b/Documentation/source/RegisterDICOMs.rst new file mode 100644 index 000000000..78bbe4205 --- /dev/null +++ b/Documentation/source/RegisterDICOMs.rst @@ -0,0 +1 @@ +Registering DICOM images \ No newline at end of file diff --git a/Documentation/source/RigidRegistration.rst b/Documentation/source/RigidRegistration.rst index b88bb3bca..b4df6f321 100644 --- a/Documentation/source/RigidRegistration.rst +++ b/Documentation/source/RigidRegistration.rst @@ -24,12 +24,12 @@ The image on right has been rotated 10 degrees and translated 13 pixels in the x import SimpleITK as sitk - elastix = sitk.SimpleElastix() - elastix.SetFixedImage(sitk.SetFixedImage("fixedImage.nii")) - elastix.SetMovingImage(sitk.SetFixedImage("movingImage.nii")) - elastix.SetParameterMap(sitk.GetDefaultParameterMap("rigid")) - elastix.Execute() - sitk.WriteImage(elastix.GetResultImage()) + SimpleElastix = sitk.SimpleElastix() + SimpleElastix.SetFixedImage(sitk.SetFixedImage("fixedImage.nii")) + SimpleElastix.SetMovingImage(sitk.SetFixedImage("movingImage.nii")) + SimpleElastix.SetParameterMap(sitk.GetDefaultParameterMap("rigid")) + SimpleElastix.Execute() + sitk.WriteImage(SimpleElastix.GetResultImage()) It is clear from the result mean image on right in Fig. 9 that registration was successful. From 7a224fffe0c1d22cc7343d73b45940721de624ac Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 14 Sep 2016 20:08:58 +0200 Subject: [PATCH 390/412] COMP: Disable less used components to speed up build time and reduce binary size --- SuperBuild/External_Elastix.cmake | 49 ++++++++++++++++--------------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/SuperBuild/External_Elastix.cmake b/SuperBuild/External_Elastix.cmake index 1e26f5213..bc47184f2 100644 --- a/SuperBuild/External_Elastix.cmake +++ b/SuperBuild/External_Elastix.cmake @@ -55,33 +55,34 @@ ExternalProject_Add( ${proj} -DUSE_BSplineResampleInterpolator:BOOL=ON -DUSE_BSplineResampleInterpolatorFloat:BOOL=ON -DUSE_BSplineStackTransform:BOOL=ON - -DUSE_BSplineTransformWithDiffusion:BOOL=ON - -DUSE_CMAEvolutionStrategy:BOOL=ON + -DUSE_BSplineTransformWithDiffusion:BOOL=OFF + -DUSE_CMAEvolutionStrategy:BOOL=OFF -DUSE_CUDAResampler:BOOL=OFF - -DUSE_ConjugateGradient:BOOL=ON - -DUSE_ConjugateGradientFRPR:BOOL=ON + -DUSE_ConjugateGradient:BOOL=OFF + -DUSE_ConjugateGradientFRPR:BOOL=OFF -DUSE_CorrespondingPointsEuclideanDistanceMetric:BOOL=ON -DUSE_DeformationFieldTransform:BOOL=ON -DUSE_DisplacementMagnitudePenalty:BOOL=ON - -DUSE_DistancePreservingRigidityPenalty:BOOL=ON + -DUSE_DistancePreservingRigidityPenalty:BOOL=OFF -DUSE_EulerTransformElastix:BOOL=ON - -DUSE_FiniteDifferenceGradientDescent:BOOL=ON - -DUSE_FixedGenericPyramid:BOOL=ON - -DUSE_FixedRecursivePyramid:BOOL=ON + -DUSE_FiniteDifferenceGradientDescent:BOOL=OFF + -DUSE_FixedGenericPyramid:BOOL=OFF + -DUSE_FixedRecursivePyramid:BOOL=OFF -DUSE_FixedShrinkingPyramid:BOOL=ON -DUSE_FixedSmoothingPyramid:BOOL=ON - -DUSE_FullSampler:BOOL=ON - -DUSE_FullSearch:BOOL=ON - -DUSE_GradientDifferenceMetric:BOOL=ON + -DUSE_FullSampler:BOOL=OFF + -DUSE_FullSearch:BOOL=OFF + -DUSE_GradientDifferenceMetric:BOOL=OFF -DUSE_GridSampler:BOOL=ON -DUSE_KNNGraphAlphaMutualInformationMetric:BOOL=OFF -DUSE_LinearInterpolator:BOOL=ON -DUSE_LinearResampleInterpolator:BOOL=ON - -DUSE_MissingStructurePenalty:BOOL=ON - -DUSE_MovingRecursivePyramid:BOOL=ON + -DUSE_MissingStructurePenalty:BOOL=OFF + -DUSE_MovingGenericPyramid:BOOL=OFF + -DUSE_MovingRecursivePyramid:BOOL=OFF -DUSE_MovingShrinkingPyramid:BOOL=ON -DUSE_MovingSmoothingPyramid:BOOL=ON - -DUSE_MultiBSplineTransformWithNormal:BOOL=ON + -DUSE_MultiBSplineTransformWithNormal:BOOL=OFF -DUSE_MultiInputRandomCoordinateSampler:BOOL=ON -DUSE_MultiMetricMultiResolutionRegistration:BOOL=ON -DUSE_MultiResolutionRegistration:BOOL=ON @@ -94,30 +95,30 @@ ExternalProject_Add( ${proj} -DUSE_NormalizedMutualInformationMetric:BOOL=ON -DUSE_PCAMetric:BOOL=ON -DUSE_PCAMetric2:BOOL=ON - -DUSE_PatternIntensityMetric:BOOL=ON - -DUSE_PolydataDummyPenalty:BOOL=ON - -DUSE_Powell:BOOL=ON + -DUSE_PatternIntensityMetric:BOOL=OFF + -DUSE_PolydataDummyPenalty:BOOL=OFF + -DUSE_Powell:BOOL=OFF -DUSE_QuasiNewtonLBFGS:BOOL=ON -DUSE_RSGDEachParameterApart:BOOL=ON -DUSE_RandomCoordinateSampler:BOOL=ON -DUSE_RandomSampler:BOOL=ON -DUSE_RandomSamplerSparseMask:BOOL=ON - -DUSE_RayCastInterpolator:BOOL=ON - -DUSE_RayCastResampleInterpolator:BOOL=ON + -DUSE_RayCastInterpolator:BOOL=OFF + -DUSE_RayCastResampleInterpolator:BOOL=OFF -DUSE_ReducedDimensionBSplineInterpolator:BOOL=ON -DUSE_ReducedDimensionBSplineResampleInterpolator:BOOL=ON - -DUSE_RegularStepGradientDescent:BOOL=ON + -DUSE_RegularStepGradientDescent:BOOL=OFF -DUSE_SimilarityTransformElastix:BOOL=ON - -DUSE_Simplex:BOOL=ON - -DUSE_SimultaneousPerturbation:BOOL=ON + -DUSE_Simplex:BOOL=OFF + -DUSE_SimultaneousPerturbation:BOOL=OFF -DUSE_SplineKernelTransform:BOOL=ON -DUSE_StandardGradientDescent:BOOL=ON - -DUSE_StatisticalShapePenalty:BOOL=ON + -DUSE_StatisticalShapePenalty:BOOL=OFF -DUSE_TransformBendingEnergyPenanalty:BOOL=ON -DUSE_TransformRigidityPenalty:BOOL=ON -DUSE_TranslationTransformElastix:BOOL=ON -DUSE_VarianceOverLastDimensionMetric:BOOL=ON - -DUSE_ViolaWellsMutualInformationMetric:BOOL=ON + -DUSE_ViolaWellsMutualInformationMetric:BOOL=OFF -DUSE_WeightedCombinationTransformElastix:BOOL=ON DEPENDS ${${CMAKE_PROJECT_NAME}_DEPENDENCIES} ) From 0f5c0385c5a4f7ab6c41e745e486ef2acdf9bc10 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Sat, 17 Sep 2016 01:00:30 +0200 Subject: [PATCH 391/412] BUG: Always cast images to float for which elastix is compiled --- Code/Elastix/include/sitkSimpleElastix.hxx | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Code/Elastix/include/sitkSimpleElastix.hxx b/Code/Elastix/include/sitkSimpleElastix.hxx index ec9975b4e..4f1887ff5 100644 --- a/Code/Elastix/include/sitkSimpleElastix.hxx +++ b/Code/Elastix/include/sitkSimpleElastix.hxx @@ -1,7 +1,6 @@ #ifndef __sitksimpleelastix_hxx_ #define __sitksimpleelastix_hxx_ -#include "sitkPixelIDValues.h" #include "sitkCastImageFilter.h" namespace itk { @@ -22,12 +21,12 @@ SimpleElastix::DualExecuteInternal( void ) for( unsigned int i = 0; i < this->GetNumberOfFixedImages(); ++i ) { - elastixFilter->AddFixedImage( itkDynamicCastInDebugMode< TFixedImage* >( Cast( this->GetFixedImage( i ), static_cast< PixelIDValueEnum >( GetPixelIDValueFromElastixString( "float" ) ) ).GetITKBase() ) ); + elastixFilter->AddFixedImage( itkDynamicCastInDebugMode< TFixedImage* >( Cast( this->GetFixedImage( i ), sitkFloat32 ).GetITKBase() ) ); } for( unsigned int i = 0; i < this->GetNumberOfMovingImages(); ++i ) { - elastixFilter->AddMovingImage( itkDynamicCastInDebugMode< TMovingImage* >( Cast( this->GetMovingImage( i ), static_cast< PixelIDValueEnum >( GetPixelIDValueFromElastixString( "float" ) ) ).GetITKBase() ) ); + elastixFilter->AddMovingImage( itkDynamicCastInDebugMode< TMovingImage* >( Cast( this->GetMovingImage( i ), sitkFloat32 ).GetITKBase() ) ); } for( unsigned int i = 0; i < this->GetNumberOfFixedMasks(); ++i ) From 7232e4595e54e752f01dc1e3e3881b50cdb8fca3 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Sat, 17 Sep 2016 01:07:48 +0200 Subject: [PATCH 392/412] ENH: Add method to get single transform parameter map by index --- Code/Elastix/include/sitkSimpleElastix.h | 1 + Code/Elastix/src/sitkSimpleElastix.cxx | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/Code/Elastix/include/sitkSimpleElastix.h b/Code/Elastix/include/sitkSimpleElastix.h index 7c0031559..e65774925 100644 --- a/Code/Elastix/include/sitkSimpleElastix.h +++ b/Code/Elastix/include/sitkSimpleElastix.h @@ -132,6 +132,7 @@ class SITKCommon_EXPORT SimpleElastix Image Execute( void ); std::vector< std::map< std::string, std::vector< std::string > > > GetTransformParameterMap( void ); + std::map< std::string, std::vector< std::string > > GetTransformParameterMap( const unsigned int index ); Image GetResultImage( void ); std::vector< std::map< std::string, std::vector< std::string > > > ExecuteInverse( void ); diff --git a/Code/Elastix/src/sitkSimpleElastix.cxx b/Code/Elastix/src/sitkSimpleElastix.cxx index ddf90910f..0add929d4 100644 --- a/Code/Elastix/src/sitkSimpleElastix.cxx +++ b/Code/Elastix/src/sitkSimpleElastix.cxx @@ -936,6 +936,24 @@ ::GetTransformParameterMap( void ) return this->m_TransformParameterMapVector; } +SimpleElastix::ParameterMapType +SimpleElastix +::GetTransformParameterMap( const unsigned int index ) +{ + if( this->GetNumberOfParameterMaps() == 0 ) + { + sitkExceptionMacro( "Number of transform parameter maps: 0. Run registration with Execute()." ); + } + + if( this->GetNumberOfParameterMaps() <= index ) + { + sitkExceptionMacro( "Index exceeds number of transform parameter maps (index: " << index + << ", number of parameter maps: " << this->GetNumberOfParameterMaps() << ")." ); + } + + return this->m_TransformParameterMapVector[ index ]; +} + Image SimpleElastix ::GetResultImage( void ) From 414c55e0abb27dae61d02dd1e9bed6575d702b37 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 21 Sep 2016 15:56:27 +0200 Subject: [PATCH 393/412] COMP: Add pypi upload script --- Utilities/pypi.sh.in | 1 + 1 file changed, 1 insertion(+) create mode 100644 Utilities/pypi.sh.in diff --git a/Utilities/pypi.sh.in b/Utilities/pypi.sh.in new file mode 100644 index 000000000..16831f455 --- /dev/null +++ b/Utilities/pypi.sh.in @@ -0,0 +1 @@ +sudo python @CMAKE_BINARY_DIR@/Wrapping/Python/Packaging/setup.py bdist upload -r pypi \ No newline at end of file From 416faf3eaa7e55fdf5990ed839d1db512180fe23 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Thu, 22 Sep 2016 11:01:36 +0200 Subject: [PATCH 394/412] DOC: Add command prompt compilation guide for Windows --- Documentation/source/GettingStarted.rst | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/Documentation/source/GettingStarted.rst b/Documentation/source/GettingStarted.rst index d84e7a1f1..3762a0fbe 100644 --- a/Documentation/source/GettingStarted.rst +++ b/Documentation/source/GettingStarted.rst @@ -95,7 +95,13 @@ SimpleElastix can be compiled with the SuperBuild. The SuperBuild is a script th - Press generate. -3. Open Visual Studio, select File -> Open Project/Solution -> Open and choose :code:`SuperBuildSimpleITK` solution. +3. If you are comfortable with the commandline, this is by far the easiest and least error-prone way of compiling the project. Otherwise skip to steps 4 and 5 that uses Visual Studio . + - Open x64 native tools command prompt. On Windows 10, open the stat menu and click on "All Apps". Find the Visual Studio folder (e.g. "Microsoft Visual Studio 2012"), open it, and click on "Open VS2012 x64 Native Tools Command Prompt." + - Navigate to the build folder specified in CMake. + - Run :code:`msbuild ALL_BUILD.vcxproj /p:Configuration=Release`. + - Done. Ignore steps 4 and 5. + +4. Open Visual Studio, select File -> Open Project/Solution -> Open and choose :code:`SuperBuildSimpleITK` solution. .. figure:: _static/WindowsInstallationOpenSolution.png :align: center @@ -104,7 +110,7 @@ SimpleElastix can be compiled with the SuperBuild. The SuperBuild is a script th Figure 5: Open the solution in Visual Studio. -4. Make sure "Release" build type is selected and build the :code:`ALL_BUILD` project. If the "Debug" build type is used instead of "Release" mode, we will experience a significant performance penalty and may not be able to build language packages that are distributed without development binaries, e.g. Python. +5. Make sure "Release" build type is selected and build the :code:`ALL_BUILD` project. If the "Debug" build type is used instead of "Release" mode, we will experience a significant performance penalty and may not be able to build language packages that are distributed without development binaries. .. figure:: _static/WindowsInstallationBuildSolution.png :align: center @@ -115,7 +121,7 @@ SimpleElastix can be compiled with the SuperBuild. The SuperBuild is a script th Manually Building On Linux -------------------------- -The following approach allows us to a locally installed version of ITK and/or elastix. +The following approach allows us to use a locally installed version of ITK and/or elastix. 1. Setup the prerequisites - `sudo apt-get install cmake swig monodevelop r-base r-base-dev ruby python python-dev tcl tcl-dev tk tk-dev`. @@ -149,7 +155,9 @@ The language package may be configured incorrectly or the necessary folders may - Solution 2: Set the paths manually in CMake (quick and dirty fix). For example, specify :code:`PYTHON_EXECUTABLE`, :code:`PYTHON_INCLUDE_DIR` and :code:`PYTHON_LIBRARY` if you wish to build the python package. - Linux and Mac OS X: Run :code:`$ ccmake .` in the build directory and press :code:`t` on your keyboard to see these options. - Windows: Tick "Advanced" in the CMake GUI to see these options. - - You will have to repeat this procedure every time you setup a new build of SimpleElastix so it is worth considering configuring your :code:`PATH` variable instead (we recommend you configure your :code:`$PATH` environment variable correctly in any case). If you still experience problems at this point, re-install the language package or consult Google or Stackoverflow. + - You will have to repeat this procedure every time you setup a new build of SimpleElastix, so we recommend that you configure your :code:`$PATH` environment variable as described in solution 1 above. + +If you are still experiencing problems at this point, re-install the language package or consult Google or Stack Overflow. Visual Studio throws :code:`LNK1102 out of memory` error even though I selected the 64-bit compiler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From 3ae515fd2b06aae58102afde551898a1d0eac3bc Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Mon, 26 Sep 2016 13:31:26 +0200 Subject: [PATCH 395/412] ENH: Remove redundant cast --- Code/Elastix/include/sitkSimpleElastix.hxx | 3 +-- Code/Elastix/include/sitkSimpleTransformix.hxx | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Code/Elastix/include/sitkSimpleElastix.hxx b/Code/Elastix/include/sitkSimpleElastix.hxx index 4f1887ff5..1c9fbf964 100644 --- a/Code/Elastix/include/sitkSimpleElastix.hxx +++ b/Code/Elastix/include/sitkSimpleElastix.hxx @@ -65,8 +65,7 @@ SimpleElastix::DualExecuteInternal( void ) elastixFilter->Update(); - // Cast DataObject -> itk::Image< ResultImagePixelType, ImageDimension > -> sitk::Image - this->m_ResultImage = Cast( Image( itkDynamicCastInDebugMode< TFixedImage * >( elastixFilter->GetOutput() ) ), this->GetFixedImage( 0 ).GetPixelID() ); + this->m_ResultImage = Image( itkDynamicCastInDebugMode< TFixedImage * >( elastixFilter->GetOutput() ) ); this->m_ResultImage.MakeUnique(); this->m_TransformParameterMapVector = elastixFilter->GetTransformParameterObject()->GetParameterMap(); } diff --git a/Code/Elastix/include/sitkSimpleTransformix.hxx b/Code/Elastix/include/sitkSimpleTransformix.hxx index 270563f35..28db5f372 100644 --- a/Code/Elastix/include/sitkSimpleTransformix.hxx +++ b/Code/Elastix/include/sitkSimpleTransformix.hxx @@ -46,8 +46,7 @@ SimpleTransformix::ExecuteInternal( void ) if( !this->IsEmpty( this->GetMovingImage() ) ) { - // Cast DataObject -> itk::Image< ResultImagePixelType, ImageDimension -> sitk::Image - this->m_ResultImage = Cast( Image( itkDynamicCastInDebugMode< TMovingImage* >( transformixFilter->GetOutput() ) ), this->GetMovingImage().GetPixelID() ); + this->m_ResultImage = Image( itkDynamicCastInDebugMode< TMovingImage * >( transformixFilter->GetOutput() ) ); this->m_ResultImage.MakeUnique(); } } From 0c85738d70f25af7007b0bab89c02cbeb698ec19 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Mon, 26 Sep 2016 13:31:54 +0200 Subject: [PATCH 396/412] ENH: Do not compile RSGDEachParameterApart component by default --- SuperBuild/External_Elastix.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_Elastix.cmake b/SuperBuild/External_Elastix.cmake index bc47184f2..5199a596b 100644 --- a/SuperBuild/External_Elastix.cmake +++ b/SuperBuild/External_Elastix.cmake @@ -99,7 +99,7 @@ ExternalProject_Add( ${proj} -DUSE_PolydataDummyPenalty:BOOL=OFF -DUSE_Powell:BOOL=OFF -DUSE_QuasiNewtonLBFGS:BOOL=ON - -DUSE_RSGDEachParameterApart:BOOL=ON + -DUSE_RSGDEachParameterApart:BOOL=OFF -DUSE_RandomCoordinateSampler:BOOL=ON -DUSE_RandomSampler:BOOL=ON -DUSE_RandomSamplerSparseMask:BOOL=ON From a57b92446fae76f67d16637c57d2597fcdfa4183 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Mon, 26 Sep 2016 13:33:01 +0200 Subject: [PATCH 397/412] ENH: Update elastix --- SuperBuild/External_Elastix.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_Elastix.cmake b/SuperBuild/External_Elastix.cmake index 5199a596b..48182d8cf 100644 --- a/SuperBuild/External_Elastix.cmake +++ b/SuperBuild/External_Elastix.cmake @@ -11,7 +11,7 @@ endif() file( WRITE "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" "${ep_common_cache}" ) set( ELASTIX_GIT_REPOSITORY ${git_protocol}://github.com/kaspermarstal/elastix ) -set( ELASTIX_GIT_TAG 54e5a7c4513bb36374c18d05951de7354f5837ca ) +set( ELASTIX_GIT_TAG 416faf3eaa7e55fdf5990ed839d1db512180fe23 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ELASTIX_BUILD_SHARED_LIBS ON ) From bd9d74fdf9c896675b1dae4d75a0654dfb6c8384 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Tue, 27 Sep 2016 10:11:55 +0200 Subject: [PATCH 398/412] ENH: Update elastix --- SuperBuild/External_Elastix.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_Elastix.cmake b/SuperBuild/External_Elastix.cmake index 48182d8cf..659d8e567 100644 --- a/SuperBuild/External_Elastix.cmake +++ b/SuperBuild/External_Elastix.cmake @@ -11,7 +11,7 @@ endif() file( WRITE "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" "${ep_common_cache}" ) set( ELASTIX_GIT_REPOSITORY ${git_protocol}://github.com/kaspermarstal/elastix ) -set( ELASTIX_GIT_TAG 416faf3eaa7e55fdf5990ed839d1db512180fe23 ) +set( ELASTIX_GIT_TAG fa451dd33ac72dbded40dbf408db2c4e958469ac ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ELASTIX_BUILD_SHARED_LIBS ON ) From 56fbcba555895ab101d158cdb5cc3a6c5fbc8ec8 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Mon, 24 Oct 2016 10:55:42 +0200 Subject: [PATCH 399/412] BUG: Compare moving image and moving mask dimensions against first moving image, not first fixed image --- Code/Elastix/src/sitkSimpleElastix.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Elastix/src/sitkSimpleElastix.cxx b/Code/Elastix/src/sitkSimpleElastix.cxx index 0add929d4..bb2c24491 100644 --- a/Code/Elastix/src/sitkSimpleElastix.cxx +++ b/Code/Elastix/src/sitkSimpleElastix.cxx @@ -865,7 +865,7 @@ ::Execute( void ) for( unsigned int i = 1; i < this->GetNumberOfMovingImages(); ++i ) { - if( this->GetMovingImage( i ).GetDimension() != FixedImageDimension ) + if( this->GetMovingImage( i ).GetDimension() != MovingImageDimension ) { sitkExceptionMacro( "Moving images must be of same dimension as fixed images (fixed image at index 0 is of dimension " << this->GetFixedImage( 0 ).GetDimension() << ", moving image at index " << i @@ -885,7 +885,7 @@ ::Execute( void ) for( unsigned int i = 1; i < this->GetNumberOfMovingMasks(); ++i ) { - if( this->GetMovingMask( i ).GetDimension() != FixedImageDimension ) + if( this->GetMovingMask( i ).GetDimension() != MovingImageDimension ) { sitkExceptionMacro( "Moving masks must be of same dimension as moving images (moving images are of dimension " << this->GetMovingImage( 0 ).GetDimension() << ", moving mask at index " << i From 25272c6a1a51bb8994b02204469c3d312c62dab8 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Mon, 24 Oct 2016 10:56:36 +0200 Subject: [PATCH 400/412] DOC: Fix ITK Review CMake command --- Documentation/source/GettingStarted.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/source/GettingStarted.rst b/Documentation/source/GettingStarted.rst index 3762a0fbe..0be1264de 100644 --- a/Documentation/source/GettingStarted.rst +++ b/Documentation/source/GettingStarted.rst @@ -128,7 +128,7 @@ The following approach allows us to use a locally installed version of ITK and/o 2. Install SWIG >= 3.0.5 3. Install ITK. Configure CMake using the same approach as above. - Clone ITK from `github.com/InsightSoftwareConsortium/ITK `_. - - Configure CMake. Set the following CMake variables: BUILD_SHARED_LIBS=OFF, ITK_USE_REVIEW=ON, ITK_WRAP_*=OFF. + - Configure CMake. Set the following CMake variables: BUILD_SHARED_LIBS=OFF, Module_ITKReview=ON, ITK_WRAP_*=OFF. - Compile ITK. Make sure to note the build settings, e.g. Release x64. 4. Build elastix. - Clone elastix from `github.com/kaspermarstal/elastix `_. From d20bd04532c9683bda4e7e38df4d10964d0d74cf Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Mon, 24 Oct 2016 10:57:30 +0200 Subject: [PATCH 401/412] DOC: Fix number of DOFs for affine registration, Euler transform does not include scaling --- Documentation/source/Introduction.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentation/source/Introduction.rst b/Documentation/source/Introduction.rst index 56b558375..657eb072a 100644 --- a/Documentation/source/Introduction.rst +++ b/Documentation/source/Introduction.rst @@ -88,11 +88,11 @@ Transforms The choice of transform is essential for successful registration and, perhaps more importantly, what we perceive as "successful". The transform reflects the desired type of transformation and constrain the solution space to that type of deformation. For example, in intra-subject applications it may be sufficent to consider only rigid transformations if you are registering bones, while a cross-sectional study demands more flexible transformation models to allow for normal anatomical variability between patients. -The number of parameters of the transform corresponds to the degrees of freedom (DOF) of the transformation. This number varies greatly from 3 DOFs for 3D translation and 9 DOFs for 3D affine warping to anywhere between hundreds and millions of DOFs for b-spline deformation fields and non-parametric methods. +The number of parameters of the transform corresponds to the degrees of freedom (DOF) of the transformation. This number varies greatly from 3 DOFs for 3D translation and 12 DOFs for 3D affine warping to anywhere between hundreds and millions of DOFs for b-spline deformation fields and non-parametric methods. The number of DOFs is equal to the dimensionality of the search space and directly proportional to the computational complexity of the optimization problem. The computational complexity affects running time and likelihood of convergence to an optimal solution. Notice that there is a distinction between convergence to an optimal solution and a good registration result. If we use a 2D translation transform embedded in a multi-resolution approach, chances are we will find the global optimal solution. That does not garuantee a good level of anatomical correspondence, however, which will most likely require a more complex deformation model. On the other hand, registering complex anatomical structures using a b-spline deformation without proper initialization is most likely going to fail. Therefore it is often a good idea to start with simple transforms and propagate solutions through transforms of gradually increasing complexity. -Some common transforms are (in order of increasing complexity) translation, rigid (rotation, translation), Euler (rotation, translation, scaling), affine (rotation, translation, scaling, shearing), b-spline (non-rigid), Spline-Kernel Transform (non-rigid) and weighted combinations of any of these. +Some common transforms are (in order of increasing complexity) translation, rigid (rotation, translation), Euler (rotation, translation), affine (rotation, translation, scaling, shearing), b-spline (non-rigid), Spline-Kernel Transform (non-rigid) and weighted combinations of any of these. In elastix, the transform is defined from the fixed image to the moving image. It may seem counter-intuitive that the transform is defined in this direction, since it is the moving image we want to transform. Would it not be more logical to map each pixel in the moving image to its new position in fixed image? Perhaps, but then two pixels from the moving image might be mapped to the same pixel on the fixed grid and some pixels in the fixed image might not be mapped to at all. The chosen convention allows us to iterate over the fixed image and pick a pixel from the moving image for every pixel in the fixed image. From a16a07fad343b9031a76a85fd5f9f499674d1b00 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Mon, 24 Oct 2016 10:59:21 +0200 Subject: [PATCH 402/412] COMP: Add pypi script --- Utilities/CMakeLists.txt | 10 +++++++++- Utilities/SimpleElastix/CMakeLists.txt | 4 ---- Utilities/pypi.sh.in | 2 +- 3 files changed, 10 insertions(+), 6 deletions(-) delete mode 100644 Utilities/SimpleElastix/CMakeLists.txt diff --git a/Utilities/CMakeLists.txt b/Utilities/CMakeLists.txt index 2453ed0ed..a763c9d9d 100644 --- a/Utilities/CMakeLists.txt +++ b/Utilities/CMakeLists.txt @@ -1 +1,9 @@ -add_subdirectory( SimpleElastix ) +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/pypi.sh.in + ${CMAKE_CURRENT_BINARY_DIR}/pypi.sh +) + +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/valgrind.sh.in + ${CMAKE_CURRENT_BINARY_DIR}/valgrind.sh +) diff --git a/Utilities/SimpleElastix/CMakeLists.txt b/Utilities/SimpleElastix/CMakeLists.txt deleted file mode 100644 index 8c610e55f..000000000 --- a/Utilities/SimpleElastix/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -configure_file( - ${CMAKE_CURRENT_SOURCE_DIR}/valgrind.sh.in - ${CMAKE_CURRENT_BINARY_DIR}/valgrind.sh -) diff --git a/Utilities/pypi.sh.in b/Utilities/pypi.sh.in index 16831f455..c888c6865 100644 --- a/Utilities/pypi.sh.in +++ b/Utilities/pypi.sh.in @@ -1 +1 @@ -sudo python @CMAKE_BINARY_DIR@/Wrapping/Python/Packaging/setup.py bdist upload -r pypi \ No newline at end of file +sudo python @CMAKE_BINARY_DIR@/Wrapping/Python/Packaging/setup.py bdist upload -r pypi From 015513705634a879b8222b8c041dbf4427b65af1 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Mon, 24 Oct 2016 11:00:00 +0200 Subject: [PATCH 403/412] COMP: Change pypi package info to SimpleElastix --- Wrapping/Python/Packaging/setup.py.in | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/Wrapping/Python/Packaging/setup.py.in b/Wrapping/Python/Packaging/setup.py.in index f432bc2a1..e28eda3d2 100644 --- a/Wrapping/Python/Packaging/setup.py.in +++ b/Wrapping/Python/Packaging/setup.py.in @@ -58,19 +58,17 @@ Distribution.has_ext_modules = always_has_ext_modules setup( - name = 'SimpleITK', + name = 'SimpleElastix', version = get_pep386version(), - author = 'Insight Software Consortium', - author_email = 'insight-users@itk.org', + author = 'Kasper Marstal', + author_email = 'kaspermarstal@gmail.com', packages= ['SimpleITK'], package_dir = {'SimpleITK':r'@SIMPLEITK_PYTHON_PACKAGE_DIR@'}, package_data = {'SimpleITK':[r'@SIMPLEITK_RELATIVE_BINARY_MODULE@']}, - download_url = r'https://www.itk.org/SimpleITKDoxygen/html/PyDownloadPage.html', + download_url = r'https://simpleelastix.github.io', platforms = [], - description = r'Simplified interface to the Insight Toolkit for image registration and segmentation', - long_description = 'Provide an abstraction layer to ITK that enables developers\ - and users to access the powerful features of the InsightToolkit in a more \ - simplified manner.', + description = r'User-friendly multi-lingual library for medical image registration', + long_description = 'Native elastix interface for Python, Java, R, Lua, Tcl, Ruby and C#.', classifiers=[ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", @@ -79,6 +77,6 @@ setup( "Topic :: Scientific/Engineering" ], license='Apache', - keywords = 'ITK InsightToolkit segmentation registration image', - url = r'http://simpleitk.org/' + keywords = 'elastix medical image registration', + url = r'https://simpleelastix.github.io' ) From 0357d760ee7c96640a60cfbfc064a1d8981c5054 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 16 Nov 2016 12:44:27 +0100 Subject: [PATCH 404/412] COMP: ITK required by SimpleElastix examples --- Examples/CMakeLists.txt | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index 2f96999c7..772e654f5 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -14,11 +14,6 @@ if(NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK") find_package(SimpleITK REQUIRED) include(${SimpleITK_USE_FILE}) - # SimpleElastix further requires ITK - find_package(ITK) - set(ITK_NO_IO_FACTORY_REGISTER_MANAGER 1) - include(${ITK_USE_FILE}) - # Add compiler flags needed to use SimpleITK. set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SimpleITK_REQUIRED_C_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SimpleITK_REQUIRED_CXX_FLAGS}") @@ -27,6 +22,13 @@ if(NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") endif() +if(CMAKE_PROJECT_NAME STREQUAL "SimpleITK") + # SimpleElastix further requires ITK + find_package(ITK REQUIRED) + set(ITK_NO_IO_FACTORY_REGISTER_MANAGER 1) + include(${ITK_USE_FILE}) +endif() + # Add individual cxx executables add_executable ( SimpleElastix1 SimpleElastix1.cxx ) target_link_libraries ( SimpleElastix1 ${SimpleITK_LIBRARIES} ) From bb2c9275f8b8fa4916648f7c0ad93208dfe2dc67 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Wed, 16 Nov 2016 15:31:46 +0100 Subject: [PATCH 405/412] ENH: Add valgrind shell script --- Utilities/{SimpleElastix => }/valgrind.sh.in | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Utilities/{SimpleElastix => }/valgrind.sh.in (100%) diff --git a/Utilities/SimpleElastix/valgrind.sh.in b/Utilities/valgrind.sh.in similarity index 100% rename from Utilities/SimpleElastix/valgrind.sh.in rename to Utilities/valgrind.sh.in From b5948dfee67701caf9cf9401df0a24cd50edd252 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Fri, 18 Nov 2016 15:14:57 +0100 Subject: [PATCH 406/412] WIP: Fix building examples as external project --- Examples/CMakeLists.txt | 10 ++++------ Examples/ITKIntegration/CMakeLists.txt | 4 ++-- SuperBuild/External_SimpleITKExamples.cmake | 3 ++- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index 772e654f5..7a3cb11cd 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -22,12 +22,10 @@ if(NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") endif() -if(CMAKE_PROJECT_NAME STREQUAL "SimpleITK") - # SimpleElastix further requires ITK - find_package(ITK REQUIRED) - set(ITK_NO_IO_FACTORY_REGISTER_MANAGER 1) - include(${ITK_USE_FILE}) -endif() +# ITK and Elastix is required to build SimpleElastix examples +set(ITK_NO_IO_FACTORY_REGISTER_MANAGER 1) +include(${ITK_USE_FILE}) +include(${ELASTIX_USE_FILE}) # Add individual cxx executables add_executable ( SimpleElastix1 SimpleElastix1.cxx ) diff --git a/Examples/ITKIntegration/CMakeLists.txt b/Examples/ITKIntegration/CMakeLists.txt index 73aa7ed6b..8634a5405 100644 --- a/Examples/ITKIntegration/CMakeLists.txt +++ b/Examples/ITKIntegration/CMakeLists.txt @@ -2,7 +2,7 @@ add_executable ( ITKIntegration ITKIntegration.cxx ) target_link_libraries ( ITKIntegration ${SimpleITK_LIBRARIES} ) add_executable( ElastixFilter ElastixFilter.cxx ) -target_link_libraries( ElastixFilter ${SimpleITK_LIBRARIES} ) +target_link_libraries( ElastixFilter ${SimpleITK_LIBRARIES} elastix ${ITK_LIBRARIES} ) add_executable( TransformixFilter TransformixFilter.cxx ) -target_link_libraries( TransformixFilter ${SimpleITK_LIBRARIES} ) +target_link_libraries( TransformixFilter ${SimpleITK_LIBRARIES} transformix ${ITK_LIBRARIES} ) diff --git a/SuperBuild/External_SimpleITKExamples.cmake b/SuperBuild/External_SimpleITKExamples.cmake index b340085b7..262dba839 100644 --- a/SuperBuild/External_SimpleITKExamples.cmake +++ b/SuperBuild/External_SimpleITKExamples.cmake @@ -17,8 +17,9 @@ if (${BUILD_EXAMPLES} ) --no-warn-unused-cli -C "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" ${ep_common_args} - -DELASTIX_USE_FILE:PATH=${ELASTIX_USE_FILE} -DSimpleITK_DIR:PATH=${CMAKE_CURRENT_BINARY_DIR}/lib/cmake/SimpleITK-0.10/ + -DITK_USE_FILE:PATH=${ITK_USE_FILE} + -DELASTIX_USE_FILE:PATH=${ELASTIX_USE_FILE} -DCMAKE_SKIP_RPATH:BOOL=ON -DCMAKE_INSTALL_PREFIX:PATH= BUILD_COMMAND ${BUILD_COMMAND_STRING} From 1a420e2b785d3ff97d26ef3b608f583c993b01b6 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Mon, 21 Nov 2016 23:10:22 +0100 Subject: [PATCH 407/412] ENH: Pimple refactoring MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit adds new facade classes for elastix and transformix using the pimple pattern. This compiles all elastix and transformix headers into the compilation units and thus avoids the need to install these headers unto a user’s system. --- CMakeLists.txt | 32 +- Code/Common/include/sitkPixelIDTypeLists.h | 6 +- Code/Elastix/include/sitkSimpleElastix.h | 62 +- Code/Elastix/include/sitkSimpleElastix.hxx | 83 -- Code/Elastix/include/sitkSimpleTransformix.h | 58 +- .../Elastix/include/sitkSimpleTransformix.hxx | 64 - Code/Elastix/src/CMakeLists.txt | 12 +- Code/Elastix/src/sitkSimpleElastix.cxx | 621 ++------- Code/Elastix/src/sitkSimpleElastixImpl.cxx | 1127 +++++++++++++++++ Code/Elastix/src/sitkSimpleElastixImpl.h | 177 +++ Code/Elastix/src/sitkSimpleTransformix.cxx | 249 +--- .../Elastix/src/sitkSimpleTransformixImpl.cxx | 585 +++++++++ Code/Elastix/src/sitkSimpleTransformixImpl.h | 134 ++ Examples/CMakeLists.txt | 11 +- Examples/ITKIntegration/CMakeLists.txt | 14 +- SuperBuild/External_Elastix.cmake | 2 +- SuperBuild/External_SimpleITKExamples.cmake | 3 +- Testing/Unit/sitkSimpleElastixTests.cxx | 6 +- UseSimpleITK.cmake.in | 5 - 19 files changed, 2248 insertions(+), 1003 deletions(-) delete mode 100644 Code/Elastix/include/sitkSimpleElastix.hxx delete mode 100644 Code/Elastix/include/sitkSimpleTransformix.hxx create mode 100644 Code/Elastix/src/sitkSimpleElastixImpl.cxx create mode 100644 Code/Elastix/src/sitkSimpleElastixImpl.h create mode 100644 Code/Elastix/src/sitkSimpleTransformixImpl.cxx create mode 100644 Code/Elastix/src/sitkSimpleTransformixImpl.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 35053235c..0b94cea80 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -80,8 +80,15 @@ if(ITK_FOUND) endif() #---------------------------------------------------------- -# Configure elastix +# Set flags and directories +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SimpleITK_REQUIRED_C_FLAGS}") +set(CMAKE_CXX_FLAGS "${CXX_ADDITIONAL_WARNING_FLAGS} ${CMAKE_CXX_FLAGS} ${SimpleITK_REQUIRED_CXX_FLAGS}") +set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") +set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") +set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") +#----------------------------------------------------------- +# Configure Elastix find_package( OpenMP ) if( OPENMP_FOUND ) set( SimpleITK_REQUIRED_C_FLAGS "${SimpleITK_REQUIRED_C_FLAGS} ${OpenMP_C_FLAGS} " ) @@ -106,14 +113,6 @@ if( ELASTIX_BUILD_EXECUTABLE ) message(FATAL_ERROR "SimpleElastix requires elastix libraries, please set ELASTIX_BUILD_EXECUTABLE=OFF and rebuild elastix") endif() -#---------------------------------------------------------- -# Set flags and directories -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SimpleITK_REQUIRED_C_FLAGS}") -set(CMAKE_CXX_FLAGS "${CXX_ADDITIONAL_WARNING_FLAGS} ${CMAKE_CXX_FLAGS} ${SimpleITK_REQUIRED_CXX_FLAGS}") -set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") -set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") - #---------------------------------------------------------- # Place all options to go into sitkConfigure.h here option(BUILD_SHARED_LIBS "Build SimpleITK ITK with shared libraries. This does not effect wrapped languages." OFF) @@ -370,7 +369,6 @@ endif() # we enter the sub-directories include(CTest) - #------------------------------------------------------------------------------ # Go to subdirectories add_subdirectory ( Utilities ) @@ -504,16 +502,10 @@ install( install(FILES ${SimpleITK_DOC_FILES} DESTINATION "${SimpleITK_INSTALL_DOC_DIR}" COMPONENT Runtime) -# Additional files needed by SimpleElastix -install( - DIRECTORY - ${ITK_INCLUDE_DIRS} - ${ELASTIX_INCLUDE_DIRECTORIES} - DESTINATION - ${SimpleITK_INSTALL_INCLUDE_DIR}/ - COMPONENT Development - FILES_MATCHING PATTERN "*.h" -) +install( DIRECTORY "${ELASTIX_LINK_DIRECTORIES}" + DESTINATION ${SimpleITK_INSTALL_INCLUDE_DIR} + COMPONENT Development + FILES_MATCHING PATTERN "*ix*" ) #------------------------------------------------------------------------------ # CPack diff --git a/Code/Common/include/sitkPixelIDTypeLists.h b/Code/Common/include/sitkPixelIDTypeLists.h index b971ee8b5..442071f78 100644 --- a/Code/Common/include/sitkPixelIDTypeLists.h +++ b/Code/Common/include/sitkPixelIDTypeLists.h @@ -217,9 +217,9 @@ typedef AllPixelIDTypeList InstantiatedPixelIDTypeList; #endif -/** SimpleElastix and SimpleTransformix is compiled with float pixel type only for - * saving compile time and reducing binary size. Images are automacially casted to - * and from float before and after registration. +/** SimpleElastix and SimpleTransformix is compiled with float pixel type only. This + * saves compile time and reduces binary size. Images are automacially casted to and + * from float before and after registration. */ typedef typelist::MakeTypeList< BasicPixelID< float > >::Type FloatPixelIDTypeList; diff --git a/Code/Elastix/include/sitkSimpleElastix.h b/Code/Elastix/include/sitkSimpleElastix.h index e65774925..42c569665 100644 --- a/Code/Elastix/include/sitkSimpleElastix.h +++ b/Code/Elastix/include/sitkSimpleElastix.h @@ -1,16 +1,10 @@ #ifndef __sitksimpleelastix_h_ #define __sitksimpleelastix_h_ -// SimpleITK +#include "nsstd/auto_ptr.h" #include "sitkCommon.h" -#include "sitkMemberFunctionFactory.h" -#include "sitkDualMemberFunctionFactory.h" #include "sitkImage.h" -// Elastix -#include "elxElastixFilter.h" -#include "elxParameterObject.h" - namespace itk { namespace simple { @@ -23,20 +17,16 @@ class SITKCommon_EXPORT SimpleElastix typedef SimpleElastix Self; - typedef std::vector< Image > VectorOfImage; - - typedef elastix::ParameterObject ParameterObjectType; - typedef ParameterObjectType::Pointer ParameterObjectPointer; - typedef ParameterObjectType::ParameterMapType ParameterMapType; - typedef ParameterObjectType::ParameterMapVectorType ParameterMapVectorType; - typedef ParameterMapType::iterator ParameterMapIterator; - typedef ParameterMapType::const_iterator ParameterMapConstIterator; - typedef itk::ParameterFileParser ParameterFileParserType; - typedef ParameterFileParserType::Pointer ParameterFileParserPointer; - typedef ParameterObjectType::ParameterKeyType ParameterKeyType; - typedef ParameterObjectType::ParameterValueType ParameterValueType; - typedef ParameterObjectType::ParameterValueVectorType ParameterValueVectorType; - typedef ParameterObjectType::ParameterValueVectorIterator ParameterValueVectorIterator; + typedef std::vector< Image > VectorOfImage; + + typedef std::string ParameterKeyType; + typedef std::string ParameterValueType; + typedef std::vector< ParameterValueType > ParameterValueVectorType; + typedef ParameterValueVectorType::iterator ParameterValueVectorIterator; + typedef std::map< ParameterKeyType, ParameterValueVectorType > ParameterMapType; + typedef std::vector< ParameterMapType > ParameterMapVectorType; + typedef ParameterMapType::iterator ParameterMapIterator; + typedef ParameterMapType::const_iterator ParameterMapConstIterator; const std::string GetName( void ); @@ -146,34 +136,8 @@ class SITKCommon_EXPORT SimpleElastix private: - bool IsEmpty( const Image& image ); - - // Definitions for SimpleITK member factory - typedef Image ( Self::*MemberFunctionType )( void ); - template< class TFixedImage, class TMovingImage > Image DualExecuteInternal( void ); - friend struct detail::DualExecuteInternalAddressor< MemberFunctionType >; - nsstd::auto_ptr< detail::DualMemberFunctionFactory< MemberFunctionType > > m_DualMemberFactory; - - VectorOfImage m_FixedImages; - VectorOfImage m_MovingImages; - VectorOfImage m_FixedMasks; - VectorOfImage m_MovingMasks; - Image m_ResultImage; - - std::string m_InitialTransformParameterMapFileName; - std::string m_FixedPointSetFileName; - std::string m_MovingPointSetFileName; - - ParameterMapVectorType m_ParameterMapVector; - ParameterMapVectorType m_TransformParameterMapVector; - ParameterMapVectorType m_InverseTransformParameterMapVector; - - std::string m_OutputDirectory; - std::string m_LogFileName; - - bool m_LogToFile; - bool m_LogToConsole; - + struct SimpleElastixImpl; + nsstd::auto_ptr< SimpleElastixImpl > m_Pimple; }; diff --git a/Code/Elastix/include/sitkSimpleElastix.hxx b/Code/Elastix/include/sitkSimpleElastix.hxx deleted file mode 100644 index 1c9fbf964..000000000 --- a/Code/Elastix/include/sitkSimpleElastix.hxx +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef __sitksimpleelastix_hxx_ -#define __sitksimpleelastix_hxx_ - -#include "sitkCastImageFilter.h" - -namespace itk { - namespace simple { - -template< typename TFixedImage, typename TMovingImage > -Image -SimpleElastix::DualExecuteInternal( void ) -{ - typedef elastix::ElastixFilter< TFixedImage, TMovingImage > ElastixFilterType; - typedef typename ElastixFilterType::Pointer ElastixFilterPointer; - typedef typename ElastixFilterType::FixedMaskType FixedMaskType; - typedef typename ElastixFilterType::MovingMaskType MovingMaskType; - - try - { - ElastixFilterPointer elastixFilter = ElastixFilterType::New(); - - for( unsigned int i = 0; i < this->GetNumberOfFixedImages(); ++i ) - { - elastixFilter->AddFixedImage( itkDynamicCastInDebugMode< TFixedImage* >( Cast( this->GetFixedImage( i ), sitkFloat32 ).GetITKBase() ) ); - } - - for( unsigned int i = 0; i < this->GetNumberOfMovingImages(); ++i ) - { - elastixFilter->AddMovingImage( itkDynamicCastInDebugMode< TMovingImage* >( Cast( this->GetMovingImage( i ), sitkFloat32 ).GetITKBase() ) ); - } - - for( unsigned int i = 0; i < this->GetNumberOfFixedMasks(); ++i ) - { - elastixFilter->AddFixedMask( itkDynamicCastInDebugMode< FixedMaskType* >( this->GetFixedMask( i ).GetITKBase() ) ); - } - - for( unsigned int i = 0; i < this->GetNumberOfMovingMasks(); ++i ) - { - elastixFilter->AddMovingMask( itkDynamicCastInDebugMode< MovingMaskType* >( this->GetMovingMask( i ).GetITKBase() ) ); - } - - elastixFilter->SetInitialTransformParameterFileName( this->GetInitialTransformParameterFileName() ); - elastixFilter->SetFixedPointSetFileName( this->GetFixedPointSetFileName() ); - elastixFilter->SetMovingPointSetFileName( this->GetMovingPointSetFileName() ); - - elastixFilter->SetOutputDirectory( this->GetOutputDirectory() ); - elastixFilter->SetLogFileName( this->GetLogFileName() ); - elastixFilter->SetLogToFile( this->GetLogToFile() ); - elastixFilter->SetLogToConsole( this->GetLogToConsole() ); - - ParameterMapVectorType parameterMapVector = this->m_ParameterMapVector; - for( unsigned int i = 0; i < parameterMapVector.size(); i++ ) - { - parameterMapVector[ i ][ "FixedInternalImagePixelType" ] - = ParameterValueVectorType( 1, "float" ); - parameterMapVector[ i ][ "MovingInternalImagePixelType" ] - = ParameterValueVectorType( 1, "float" ); - parameterMapVector[ i ][ "ResultImagePixelType" ] - = ParameterValueVectorType( 1, "float" ); - } - - ParameterObjectPointer parameterObject = ParameterObjectType::New(); - parameterObject->SetParameterMap( parameterMapVector ); - elastixFilter->SetParameterObject( parameterObject ); - - elastixFilter->Update(); - - this->m_ResultImage = Image( itkDynamicCastInDebugMode< TFixedImage * >( elastixFilter->GetOutput() ) ); - this->m_ResultImage.MakeUnique(); - this->m_TransformParameterMapVector = elastixFilter->GetTransformParameterObject()->GetParameterMap(); - } - catch( itk::ExceptionObject &e ) - { - sitkExceptionMacro( << e ); - } - - return this->m_ResultImage; -} - -} // end namespace simple -} // end namespace itk - -#endif // __sitksimpleelastix_hxx_ diff --git a/Code/Elastix/include/sitkSimpleTransformix.h b/Code/Elastix/include/sitkSimpleTransformix.h index 558634015..5377233cf 100644 --- a/Code/Elastix/include/sitkSimpleTransformix.h +++ b/Code/Elastix/include/sitkSimpleTransformix.h @@ -1,15 +1,10 @@ #ifndef __sitksimpletransformix_h_ #define __sitksimpletransformix_h_ -// SimpleITK +#include "nsstd/auto_ptr.h" #include "sitkCommon.h" -#include "sitkMemberFunctionFactory.h" #include "sitkImage.h" -// Transformix -#include "elxTransformixFilter.h" -#include "elxParameterObject.h" - namespace itk { namespace simple { @@ -22,17 +17,14 @@ class SITKCommon_EXPORT SimpleTransformix typedef SimpleTransformix Self; - typedef elastix::ParameterObject ParameterObjectType; - typedef ParameterObjectType::Pointer ParameterObjectPointer; - typedef ParameterObjectType::ParameterMapType ParameterMapType; - typedef ParameterObjectType::ParameterMapVectorType ParameterMapVectorType; - typedef ParameterMapType::iterator ParameterMapIterator; - typedef ParameterMapType::const_iterator ParameterMapConstIterator; - typedef itk::ParameterFileParser ParameterFileParserType; - typedef ParameterFileParserType::Pointer ParameterFileParserPointer; - typedef ParameterObjectType::ParameterKeyType ParameterKeyType; - typedef ParameterObjectType::ParameterValueType ParameterValueType; - typedef ParameterObjectType::ParameterValueVectorType ParameterValueVectorType; + typedef std::string ParameterKeyType; + typedef std::string ParameterValueType; + typedef std::vector< ParameterValueType > ParameterValueVectorType; + typedef ParameterValueVectorType::iterator ParameterValueVectorIterator; + typedef std::map< ParameterKeyType, ParameterValueVectorType > ParameterMapType; + typedef std::vector< ParameterMapType > ParameterMapVectorType; + typedef ParameterMapType::iterator ParameterMapIterator; + typedef ParameterMapType::const_iterator ParameterMapConstIterator; const std::string GetName( void ); @@ -94,7 +86,7 @@ class SITKCommon_EXPORT SimpleTransformix Self& RemoveTransformParameter( const std::string key ); Self& RemoveTransformParameter( const unsigned int index, const std::string key ); - std::map< std::string, std::vector< std::string > > ReadParameterFile( const std::string filename ); + std::map< std::string, std::vector< std::string > > ReadParameterFile( const std::string parameterFileName ); Self& WriteParameterFile( const std::map< std::string, std::vector< std::string > > parameterMap, const std::string parameterFileName ); Self& PrintParameterMap( void ); @@ -104,36 +96,10 @@ class SITKCommon_EXPORT SimpleTransformix Image Execute( void ); Image GetResultImage( void ); - - - private: - - bool IsEmpty( const Image& image ); - - // Definitions for SimpleITK member factory - typedef Image ( Self::*MemberFunctionType )( void ); - template< class TMovingImage > Image ExecuteInternal( void ); - friend struct detail::MemberFunctionAddressor< MemberFunctionType >; - nsstd::auto_ptr< detail::MemberFunctionFactory< MemberFunctionType > > m_MemberFactory; - - Image m_MovingImage; - Image m_ResultImage; - - ParameterMapVectorType m_TransformParameterMapVector; - - bool m_ComputeSpatialJacobian; - bool m_ComputeDeterminantOfSpatialJacobian; - bool m_ComputeDeformationField; - std::string m_MovingPointSetFileName; - - std::string m_OutputDirectory; - std::string m_LogFileName; - - bool m_LogToConsole; - bool m_LogToFile; + struct SimpleTransformixImpl; + nsstd::auto_ptr< SimpleTransformixImpl > m_Pimple; - }; // Procedural Interface diff --git a/Code/Elastix/include/sitkSimpleTransformix.hxx b/Code/Elastix/include/sitkSimpleTransformix.hxx deleted file mode 100644 index 28db5f372..000000000 --- a/Code/Elastix/include/sitkSimpleTransformix.hxx +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef __sitksimpletransformix_hxx_ -#define __sitksimpletransformix_hxx_ - -#include "sitkCastImageFilter.h" - -namespace itk { - namespace simple { - -template< typename TMovingImage > -Image -SimpleTransformix::ExecuteInternal( void ) -{ - typedef elastix::TransformixFilter< TMovingImage > TransformixFilterType; - typedef typename TransformixFilterType::Pointer TransforimxFilterPointer; - - try - { - TransforimxFilterPointer transformixFilter = TransformixFilterType::New(); - - if( !this->IsEmpty( this->m_MovingImage ) ) { - transformixFilter->SetMovingImage( itkDynamicCastInDebugMode< TMovingImage* >( Cast( this->GetMovingImage(), static_cast< PixelIDValueEnum >( GetPixelIDValueFromElastixString( "float" ) ) ).GetITKBase() ) ); - } - - transformixFilter->SetFixedPointSetFileName( this->GetFixedPointSetFileName() ); - transformixFilter->SetComputeSpatialJacobian( this->GetComputeSpatialJacobian() ); - transformixFilter->SetComputeDeterminantOfSpatialJacobian( this->GetComputeDeterminantOfSpatialJacobian() ); - transformixFilter->SetComputeDeformationField( this->GetComputeDeformationField() ); - - transformixFilter->SetOutputDirectory( this->GetOutputDirectory() ); - transformixFilter->SetLogFileName( this->GetLogFileName() ); - transformixFilter->SetLogToFile( this->GetLogToFile() ); - transformixFilter->SetLogToConsole( this->GetLogToConsole() ); - - ParameterMapVectorType transformParameterMapVector = this->m_TransformParameterMapVector; - for( unsigned int i = 0; i < transformParameterMapVector.size(); i++ ) - { - transformParameterMapVector[ i ][ "FixedInternalImagePixelType" ] = ParameterValueVectorType( 1, "float" ); - transformParameterMapVector[ i ][ "MovingInternalImagePixelType" ] = ParameterValueVectorType( 1, "float" ); - transformParameterMapVector[ i ][ "ResultImagePixelType" ] = ParameterValueVectorType( 1, "float" ); - } - - ParameterObjectPointer parameterObject = ParameterObjectType::New(); - parameterObject->SetParameterMap( transformParameterMapVector ); - transformixFilter->SetTransformParameterObject( parameterObject ); - transformixFilter->Update(); - - if( !this->IsEmpty( this->GetMovingImage() ) ) - { - this->m_ResultImage = Image( itkDynamicCastInDebugMode< TMovingImage * >( transformixFilter->GetOutput() ) ); - this->m_ResultImage.MakeUnique(); - } - } - catch( itk::ExceptionObject &e ) - { - sitkExceptionMacro( << e ); - } - - return this->m_ResultImage; -} - -} // end namespace simple -} // end namespace itk - -#endif // __sitksimpletransformix_hxx_ diff --git a/Code/Elastix/src/CMakeLists.txt b/Code/Elastix/src/CMakeLists.txt index 93a9b75e3..7a8d88aff 100644 --- a/Code/Elastix/src/CMakeLists.txt +++ b/Code/Elastix/src/CMakeLists.txt @@ -1,12 +1,14 @@ set( ITK_NO_IO_FACTORY_REGISTER_MANAGER 1 ) include( ${ITK_USE_FILE} ) -add_library( SimpleElastix sitkSimpleElastix.cxx ) +add_library( SimpleElastix sitkSimpleElastix.cxx sitkSimpleElastixImpl.h sitkSimpleElastixImpl.cxx ) set_target_properties( SimpleElastix PROPERTIES SKIP_BUILD_RPATH TRUE ) -target_link_libraries( SimpleElastix elastix SimpleITKCommon ) +target_link_libraries( SimpleElastix INTERFACE elastix ) sitk_install_exported_target( SimpleElastix ) -add_library( SimpleTransformix sitkSimpleTransformix.cxx ) +add_library( SimpleTransformix sitkSimpleTransformix.cxx sitkSimpleTransformixImpl.h sitkSimpleTransformixImpl.cxx ) set_target_properties( SimpleTransformix PROPERTIES SKIP_BUILD_RPATH TRUE ) -target_link_libraries( SimpleTransformix transformix SimpleITKCommon ) -sitk_install_exported_target( SimpleTransformix ) +target_link_libraries( SimpleTransformix INTERFACE transformix ) +sitk_install_exported_target( SimpleTransformix ) + + diff --git a/Code/Elastix/src/sitkSimpleElastix.cxx b/Code/Elastix/src/sitkSimpleElastix.cxx index bb2c24491..8c18259a8 100644 --- a/Code/Elastix/src/sitkSimpleElastix.cxx +++ b/Code/Elastix/src/sitkSimpleElastix.cxx @@ -2,46 +2,14 @@ #define __sitksimpleelastix_cxx_ #include "sitkSimpleElastix.h" -#include "sitkSimpleElastix.hxx" +#include "sitkSimpleElastixImpl.h" namespace itk { namespace simple { SimpleElastix -::SimpleElastix( void ) +::SimpleElastix( void ) : m_Pimple( new SimpleElastixImpl ) { - // Register this class with SimpleITK - this->m_DualMemberFactory.reset( new detail::DualMemberFunctionFactory< MemberFunctionType >( this ) ); - this->m_DualMemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, FloatPixelIDTypeList, 2 >(); - this->m_DualMemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, FloatPixelIDTypeList, 3 >(); - -#ifdef SITK_4D_IMAGES - this->m_DualMemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, FloatPixelIDTypeList, 4 >(); -#endif - - m_FixedImages = VectorOfImage(); - m_MovingImages = VectorOfImage(); - m_FixedMasks = VectorOfImage(); - m_MovingMasks = VectorOfImage(); - m_ResultImage = Image(); - - m_ParameterMapVector = ParameterMapVectorType(); - m_TransformParameterMapVector = ParameterMapVectorType(); - - m_FixedPointSetFileName = ""; - m_MovingPointSetFileName = ""; - - m_OutputDirectory = "."; - m_LogFileName = ""; - - this->m_LogToFile = false; - this->m_LogToConsole = false; - - ParameterMapVectorType defaultParameterMap; - defaultParameterMap.push_back( ParameterObjectType::GetDefaultParameterMap( "translation" ) ); - defaultParameterMap.push_back( ParameterObjectType::GetDefaultParameterMap( "affine" ) ); - defaultParameterMap.push_back( ParameterObjectType::GetDefaultParameterMap( "bspline" ) ); - this->SetParameterMap( defaultParameterMap ); } SimpleElastix @@ -53,21 +21,14 @@ const std::string SimpleElastix ::GetName( void ) { - const std::string name = "SimpleElastix"; - return name; + return this->m_Pimple->GetName(); } SimpleElastix::Self& SimpleElastix ::SetFixedImage( const Image& fixedImage ) { - if( this->IsEmpty( fixedImage ) ) - { - sitkExceptionMacro( "Image is empty." ) - } - - this->RemoveFixedImage(); - this->m_FixedImages.push_back( fixedImage ); + this->m_Pimple->SetFixedImage( fixedImage ); return *this; } @@ -75,14 +36,7 @@ SimpleElastix::Self& SimpleElastix ::SetFixedImage( const VectorOfImage& fixedImages ) { - if( fixedImages.size() == 0u ) - { - sitkExceptionMacro( "Cannot set fixed images from empty vector" ); - } - - this->RemoveFixedImage(); - this->m_FixedImages = fixedImages; - + this->m_Pimple->SetFixedImage( fixedImages ); return *this; } @@ -90,12 +44,7 @@ SimpleElastix::Self& SimpleElastix ::AddFixedImage( const Image& fixedImage ) { - if( this->IsEmpty( fixedImage ) ) - { - sitkExceptionMacro( "Image is empty." ) - } - - this->m_FixedImages.push_back( fixedImage ); + this->m_Pimple->AddFixedImage( fixedImage ); return *this; } @@ -103,39 +52,29 @@ Image& SimpleElastix ::GetFixedImage( const unsigned long index ) { - if( index < this->m_FixedImages.size() ) - { - return this->m_FixedImages[ index ]; - } - - sitkExceptionMacro( "Index out of range (index: " << index << ", number of fixed images: " << this->m_FixedImages.size() << ")" ); + return this->m_Pimple->GetFixedImage( index ); } SimpleElastix::VectorOfImage& SimpleElastix ::GetFixedImage( void ) { - return this->m_FixedImages; + return this->m_Pimple->GetFixedImage(); } SimpleElastix::Self& SimpleElastix ::RemoveFixedImage( const unsigned long index ) { - if( index < this->m_FixedImages.size() ) - { - this->m_FixedImages.erase( this->m_FixedImages.begin() + index ); - return *this; - } - - sitkExceptionMacro( "Index out of range (index: " << index << ", number of fixed images: " << this->m_FixedImages.size() << ")" ); + this->m_Pimple->RemoveFixedImage( index ); + return *this; } SimpleElastix::Self& SimpleElastix ::RemoveFixedImage( void ) { - this->m_FixedImages.clear(); + this->m_Pimple->RemoveFixedImage(); return *this; } @@ -143,20 +82,14 @@ unsigned int SimpleElastix ::GetNumberOfFixedImages( void ) { - return this->m_FixedImages.size(); + return this->m_Pimple->GetNumberOfFixedImages(); } SimpleElastix::Self& SimpleElastix ::SetMovingImage( const Image& movingImage ) { - if( this->IsEmpty( movingImage ) ) - { - sitkExceptionMacro( "Image is empty." ) - } - - this->RemoveMovingImage(); - this->m_MovingImages.push_back( movingImage ); + this->m_Pimple->SetMovingImage( movingImage ); return *this; } @@ -164,14 +97,7 @@ SimpleElastix::Self& SimpleElastix ::SetMovingImage( const VectorOfImage& movingImages ) { - if( movingImages.size() == 0u ) - { - sitkExceptionMacro( "Cannot set moving images from empty vector" ); - } - - this->RemoveMovingImage(); - this->m_MovingImages = movingImages; - + this->m_Pimple->SetMovingImage( movingImages ); return *this; } @@ -179,12 +105,7 @@ SimpleElastix::Self& SimpleElastix ::AddMovingImage( const Image& movingImage ) { - if( this->IsEmpty( movingImage ) ) - { - sitkExceptionMacro( "Image is empty." ) - } - - this->m_MovingImages.push_back( movingImage ); + this->m_Pimple->AddMovingImage( movingImage ); return *this; } @@ -192,39 +113,29 @@ Image& SimpleElastix ::GetMovingImage( const unsigned long index ) { - if( index < this->m_MovingImages.size() ) - { - return this->m_MovingImages[ index ]; - } - - sitkExceptionMacro( "Index out of range (index: " << index << ", number of moving images: " << this->m_MovingImages.size() << ")" ); + return this->m_Pimple->GetMovingImage( index ); } SimpleElastix::VectorOfImage& SimpleElastix ::GetMovingImage( void ) { - return this->m_MovingImages; + return this->m_Pimple->GetMovingImage(); } SimpleElastix::Self& SimpleElastix ::RemoveMovingImage( const unsigned long index ) { - if( index < this->m_MovingImages.size() ) - { - this->m_MovingImages.erase( this->m_MovingImages.begin() + index ); - return *this; - } - - sitkExceptionMacro( "Index out of range (index: " << index << ", number of moving images: " << this->m_MovingImages.size() << ")" ); + this->m_Pimple->RemoveMovingImage( index ); + return *this; } SimpleElastix::Self& SimpleElastix ::RemoveMovingImage( void ) { - this->m_MovingImages.clear(); + this->m_Pimple->RemoveMovingImage(); return *this; } @@ -232,20 +143,14 @@ unsigned int SimpleElastix ::GetNumberOfMovingImages( void ) { - return this->m_MovingImages.size(); + return this->m_Pimple->GetNumberOfMovingImages(); } SimpleElastix::Self& SimpleElastix ::SetFixedMask( const Image& fixedMask ) { - if( this->IsEmpty( fixedMask ) ) - { - sitkExceptionMacro( "Image is empty." ) - } - - this->RemoveFixedMask(); - this->m_FixedMasks.push_back( fixedMask ); + this->m_Pimple->SetFixedMask( fixedMask ); return *this; } @@ -253,14 +158,7 @@ SimpleElastix::Self& SimpleElastix ::SetFixedMask( const VectorOfImage& fixedMasks ) { - if( fixedMasks.size() == 0u ) - { - sitkExceptionMacro( "Cannot set fixed images from empty vector" ); - } - - this->RemoveFixedMask(); - this->m_FixedMasks = fixedMasks; - + this->m_Pimple->SetFixedMask( fixedMasks ); return *this; } @@ -268,12 +166,7 @@ SimpleElastix::Self& SimpleElastix ::AddFixedMask( const Image& fixedMask ) { - if( this->IsEmpty( fixedMask ) ) - { - sitkExceptionMacro( "Image is empty." ) - } - - this->m_FixedMasks.push_back( fixedMask ); + this->m_Pimple->AddFixedMask( fixedMask ); return *this; } @@ -281,39 +174,29 @@ Image& SimpleElastix ::GetFixedMask( const unsigned long index ) { - if( index < this->m_FixedMasks.size() ) - { - return this->m_FixedMasks[ index ]; - } - - sitkExceptionMacro( "Index out of range (index: " << index << ", number of fixed masks: " << this->m_FixedMasks.size() << ")" ); + return this->m_Pimple->GetFixedMask( index ); } SimpleElastix::VectorOfImage& SimpleElastix ::GetFixedMask( void ) { - return this->m_FixedMasks; + return this->m_Pimple->GetFixedMask(); } SimpleElastix::Self& SimpleElastix ::RemoveFixedMask( const unsigned long index ) { - if( index < this->m_FixedMasks.size() ) - { - this->m_FixedMasks.erase( this->m_FixedMasks.begin() + index ); - return *this; - } - - sitkExceptionMacro( "Index out of range (index: " << index << ", number of fixed masks: " << this->m_FixedMasks.size() << ")" ); + this->m_Pimple->RemoveFixedMask( index ); + return *this; } SimpleElastix::Self& SimpleElastix ::RemoveFixedMask( void ) { - this->m_FixedMasks.clear(); + this->m_Pimple->RemoveFixedMask(); return *this; } @@ -321,20 +204,14 @@ unsigned int SimpleElastix ::GetNumberOfFixedMasks( void ) { - return this->m_FixedMasks.size(); + return this->m_Pimple->GetNumberOfFixedMasks(); } SimpleElastix::Self& SimpleElastix ::SetMovingMask( const Image& movingMask ) { - if( this->IsEmpty( movingMask ) ) - { - sitkExceptionMacro( "Image is empty." ) - } - - this->RemoveMovingMask(); - this->m_MovingMasks.push_back( movingMask ); + this->m_Pimple->SetMovingMask( movingMask ); return *this; } @@ -342,14 +219,7 @@ SimpleElastix::Self& SimpleElastix ::SetMovingMask( const VectorOfImage& movingMasks ) { - if( movingMasks.size() == 0u ) - { - sitkExceptionMacro( "Cannot set moving masks from empty vector" ); - } - - this->RemoveMovingMask(); - this->m_MovingMasks = movingMasks; - + this->m_Pimple->SetMovingMask( movingMasks ); return *this; } @@ -357,12 +227,7 @@ SimpleElastix::Self& SimpleElastix ::AddMovingMask( const Image& movingMask ) { - if( this->IsEmpty( movingMask ) ) - { - sitkExceptionMacro( "Image is empty." ) - } - - this->m_MovingMasks.push_back( movingMask ); + this->m_Pimple->AddMovingMask( movingMask ); return *this; } @@ -370,39 +235,29 @@ Image& SimpleElastix ::GetMovingMask( const unsigned long index ) { - if( index < this->m_MovingMasks.size() ) - { - return this->m_MovingMasks[ index ]; - } - - sitkExceptionMacro( "Index out of range (index: " << index << ", number of moving masks: " << this->m_MovingMasks.size() << ")" ); + return this->m_Pimple->GetMovingMask( index ); } SimpleElastix::VectorOfImage& SimpleElastix ::GetMovingMask( void ) { - return this->m_MovingMasks; + return this->m_Pimple->GetMovingMask(); } SimpleElastix::Self& SimpleElastix ::RemoveMovingMask( const unsigned long index ) { - if( index < this->m_MovingMasks.size() ) - { - this->m_MovingMasks.erase( this->m_MovingMasks.begin() + index ); - return *this; - } - - sitkExceptionMacro( "Index out of range (index: " << index << ", number of moving masks: " << this->m_MovingMasks.size() << ")" ); + this->m_Pimple->RemoveMovingMask( index ); + return *this; } SimpleElastix::Self& SimpleElastix ::RemoveMovingMask( void ) { - this->m_MovingMasks.clear(); + this->m_Pimple->RemoveMovingMask(); return *this; } @@ -410,14 +265,14 @@ unsigned int SimpleElastix ::GetNumberOfMovingMasks( void ) { - return this->m_MovingMasks.size(); + return this->m_Pimple->GetNumberOfMovingMasks(); } SimpleElastix::Self& SimpleElastix ::SetFixedPointSetFileName( const std::string fixedPointSetFileName ) { - this->m_FixedPointSetFileName = fixedPointSetFileName; + this->m_Pimple->SetFixedPointSetFileName( fixedPointSetFileName ); return *this; } @@ -425,14 +280,14 @@ std::string SimpleElastix ::GetFixedPointSetFileName( void ) { - return this->m_FixedPointSetFileName; + return this->m_Pimple->GetFixedPointSetFileName(); } SimpleElastix::Self& SimpleElastix ::RemoveFixedPointSetFileName( void ) { - this->m_FixedPointSetFileName = ""; + this->m_Pimple->RemoveFixedPointSetFileName(); return *this; } @@ -440,7 +295,7 @@ SimpleElastix::Self& SimpleElastix ::SetMovingPointSetFileName( const std::string movingPointSetFileName ) { - this->m_MovingPointSetFileName = movingPointSetFileName; + this->m_Pimple->SetMovingPointSetFileName( movingPointSetFileName ); return *this; } @@ -448,14 +303,14 @@ std::string SimpleElastix ::GetMovingPointSetFileName( void ) { - return this->m_MovingPointSetFileName; + return this->m_Pimple->GetMovingPointSetFileName(); } SimpleElastix::Self& SimpleElastix ::RemoveMovingPointSetFileName( void ) { - this->m_MovingPointSetFileName = ""; + this->m_Pimple->RemoveMovingImage(); return *this; } @@ -463,7 +318,7 @@ SimpleElastix::Self& SimpleElastix ::SetOutputDirectory( const std::string outputDirectory ) { - this->m_OutputDirectory = outputDirectory; + this->m_Pimple->SetOutputDirectory( outputDirectory ); return *this; } @@ -471,14 +326,14 @@ std::string SimpleElastix ::GetOutputDirectory( void ) { - return this->m_OutputDirectory; + return this->m_Pimple->GetOutputDirectory(); } SimpleElastix::Self& SimpleElastix ::RemoveOutputDirectory( void ) { - this->m_OutputDirectory = ""; + this->m_Pimple->RemoveOutputDirectory(); return *this; } @@ -486,7 +341,7 @@ SimpleElastix::Self& SimpleElastix ::SetLogFileName( std::string logFileName ) { - this->m_LogFileName = logFileName; + this->m_Pimple->SetLogFileName( logFileName ); return *this; } @@ -494,14 +349,14 @@ std::string SimpleElastix ::GetLogFileName( void ) { - return this->m_LogFileName; + return this->m_Pimple->GetLogFileName(); } SimpleElastix::Self& SimpleElastix ::RemoveLogFileName( void ) { - this->m_LogFileName = ""; + this->m_Pimple->RemoveLogFileName(); return *this; } @@ -509,7 +364,7 @@ SimpleElastix::Self& SimpleElastix ::SetLogToFile( bool logToFile ) { - this->m_LogToFile = logToFile; + this->m_Pimple->SetLogToFile( logToFile ); return *this; } @@ -517,14 +372,14 @@ bool SimpleElastix ::GetLogToFile( void ) { - return this->m_LogToFile; + return this->m_Pimple->GetLogToFile(); } SimpleElastix::Self& SimpleElastix ::LogToFileOn() { - this->SetLogToFile( true ); + this->m_Pimple->LogToFileOn(); return *this; } @@ -532,7 +387,7 @@ SimpleElastix::Self& SimpleElastix ::LogToFileOff() { - this->SetLogToFile( false ); + this->m_Pimple->LogToFileOff(); return *this; } @@ -540,7 +395,7 @@ SimpleElastix::Self& SimpleElastix ::SetLogToConsole( bool logToConsole ) { - this->m_LogToConsole = logToConsole; + this->m_Pimple->SetLogToConsole( logToConsole ); return *this; } @@ -548,14 +403,14 @@ bool SimpleElastix ::GetLogToConsole( void ) { - return this->m_LogToConsole; + return this->m_Pimple->GetLogToConsole(); } SimpleElastix::Self& SimpleElastix ::LogToConsoleOn() { - this->SetLogToConsole( true ); + this->m_Pimple->LogToConsoleOn(); return *this; } @@ -563,7 +418,7 @@ SimpleElastix::Self& SimpleElastix ::LogToConsoleOff() { - this->SetLogToConsole( false ); + this->m_Pimple->LogToConsoleOff(); return *this; } @@ -571,8 +426,7 @@ SimpleElastix::Self& SimpleElastix ::SetParameterMap( const std::string transformName, const unsigned int numberOfResolutions, const double finalGridSpacingInPhysicalUnits ) { - ParameterMapType parameterMap = ParameterObjectType::GetDefaultParameterMap( transformName, numberOfResolutions, finalGridSpacingInPhysicalUnits ); - this->SetParameterMap( parameterMap ); + this->m_Pimple->SetParameterMap( transformName, numberOfResolutions, finalGridSpacingInPhysicalUnits ); return *this; } @@ -580,8 +434,7 @@ SimpleElastix::Self& SimpleElastix ::SetParameterMap( const ParameterMapType parameterMap ) { - ParameterMapVectorType parameterMapVector = ParameterMapVectorType( 1, parameterMap ); - this->SetParameterMap( parameterMapVector ); + this->m_Pimple->SetParameterMap( parameterMap ); return *this; } @@ -589,7 +442,7 @@ SimpleElastix::Self& SimpleElastix ::SetParameterMap( const ParameterMapVectorType parameterMapVector ) { - this->m_ParameterMapVector = parameterMapVector; + this->m_Pimple->SetParameterMap( parameterMapVector ); return *this; } @@ -597,7 +450,7 @@ SimpleElastix::Self& SimpleElastix ::AddParameterMap( const ParameterMapType parameterMap ) { - this->m_ParameterMapVector.push_back( parameterMap ); + this->m_Pimple->AddParameterMap( parameterMap ); return *this; } @@ -605,21 +458,21 @@ SimpleElastix::ParameterMapVectorType SimpleElastix ::GetParameterMap( void ) { - return this->m_ParameterMapVector; + return this->m_Pimple->GetParameterMap(); } unsigned int SimpleElastix ::GetNumberOfParameterMaps( void ) { - return this->m_ParameterMapVector.size(); + return this->m_Pimple->GetNumberOfParameterMaps(); } SimpleElastix::Self& SimpleElastix ::SetInitialTransformParameterFileName( const std::string initialTransformParameterFileName ) { - this->m_InitialTransformParameterMapFileName = initialTransformParameterFileName; + this->m_Pimple->SetInitialTransformParameterFileName( initialTransformParameterFileName ); return *this; } @@ -627,14 +480,14 @@ std::string SimpleElastix ::GetInitialTransformParameterFileName( void ) { - return m_InitialTransformParameterMapFileName ; + return this->m_Pimple->GetInitialTransformParameterFileName(); } SimpleElastix::Self& SimpleElastix ::RemoveInitialTransformParameterFileName( void ) { - this->m_InitialTransformParameterMapFileName = ""; + this->m_Pimple->RemoveInitialTransformParameterFileName(); return *this; } @@ -642,11 +495,7 @@ SimpleElastix::Self& SimpleElastix ::SetParameter( const ParameterKeyType key, const ParameterValueType value ) { - for( unsigned int i = 0; i < this->m_ParameterMapVector.size(); i++ ) - { - this->SetParameter( i, key, value ); - } - + this->m_Pimple->SetParameter( key, value ); return *this; } @@ -654,11 +503,7 @@ SimpleElastix::Self& SimpleElastix ::SetParameter( const ParameterKeyType key, const ParameterValueVectorType value ) { - for( unsigned int i = 0; i < this->m_ParameterMapVector.size(); i++ ) - { - this->SetParameter( i, key, value ); - } - + this->m_Pimple->SetParameter( key, value ); return *this; } @@ -666,13 +511,7 @@ SimpleElastix::Self& SimpleElastix ::SetParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueType value ) { - if( index >= this->m_ParameterMapVector.size() ) - { - sitkExceptionMacro( "Parameter map index is out of range (index: " << index << "; number of parameters maps: " << this->m_ParameterMapVector.size() << "). Note that indexes are zero-based." ); - } - - this->m_ParameterMapVector[ index ][ key ] = ParameterValueVectorType( 1, value ); - + this->m_Pimple->SetParameter( index, key, value ); return *this; } @@ -680,13 +519,7 @@ SimpleElastix::Self& SimpleElastix ::SetParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueVectorType value ) { - if( index >= this->m_ParameterMapVector.size() ) - { - sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of parameters maps: " << this->m_ParameterMapVector.size() << "). Note that indexes are zero-based." ); - } - - this->m_ParameterMapVector[ index ][ key ] = value; - + this->m_Pimple->SetParameter( index, key, value ); return *this; } @@ -694,11 +527,7 @@ SimpleElastix::Self& SimpleElastix ::AddParameter( const ParameterKeyType key, const ParameterValueType value ) { - for( unsigned int i = 0; i < this->m_ParameterMapVector.size(); i++ ) - { - this->AddParameter( i, key, value ); - } - + this->m_Pimple->AddParameter( key, value ); return *this; } @@ -706,11 +535,7 @@ SimpleElastix::Self& SimpleElastix ::AddParameter( const ParameterKeyType key, const ParameterValueVectorType value ) { - for( unsigned int i = 0; i < this->m_ParameterMapVector.size(); i++ ) - { - this->AddParameter( i, key, value ); - } - + this->m_Pimple->AddParameter( key, value ); return *this; } @@ -718,20 +543,7 @@ SimpleElastix::Self& SimpleElastix ::AddParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueType value ) { - if( index >= this->m_ParameterMapVector.size() ) - { - sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of parameters maps: " << this->m_ParameterMapVector.size() << "). Note that indexes are zero-based." ); - } - - if( this->m_ParameterMapVector[ index ].find( key ) == this->m_ParameterMapVector[ index ].end() ) - { - this->SetParameter( index, key, value ); - } - else - { - this->m_ParameterMapVector[ index ][ key ].push_back( value ); - } - + this->m_Pimple->AddParameter( index, key, value ); return *this; } @@ -739,23 +551,7 @@ SimpleElastix::Self& SimpleElastix ::AddParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueVectorType value ) { - if( index >= this->m_ParameterMapVector.size() ) - { - sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of parameters maps: " << this->m_ParameterMapVector.size() << "). Note that indexes are zero-based." ); - } - - if( this->m_ParameterMapVector[ index ].find( key ) == this->m_ParameterMapVector[ index ].end() ) - { - this->SetParameter( index, key, value ); - } - else - { - for( unsigned int i = 0; i < value.size(); i++ ) - { - this->m_ParameterMapVector[ index ][ key ].push_back( value[ i ] ); - } - } - + this->m_Pimple->AddParameter( index, key, value ); return *this; } @@ -763,35 +559,21 @@ SimpleElastix::ParameterValueVectorType SimpleElastix ::GetParameter( const ParameterKeyType key ) { - if( this->m_ParameterMapVector.size() > 0 ) - { - sitkExceptionMacro( "An index is needed when more than one parameter map is present. Please specify the parameter map number as the first argument." ); - } - - return this->GetParameter( 0, key ); + return this->m_Pimple->GetParameter( key ); } SimpleElastix::ParameterValueVectorType SimpleElastix ::GetParameter( const unsigned int index, const ParameterKeyType key ) { - if( index >= this->m_ParameterMapVector.size() ) - { - sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of parameters maps: " << this->m_ParameterMapVector.size() << "). Note that indexes are zero-based." ); - } - - return this->m_ParameterMapVector[ index ][ key ]; + return this->m_Pimple->GetParameter( index, key ); } SimpleElastix::Self& SimpleElastix ::RemoveParameter( const ParameterKeyType key ) { - for( unsigned int i = 0; i < this->m_ParameterMapVector.size(); i++ ) - { - this->RemoveParameter( i, key ); - } - + this->m_Pimple->RemoveParameter( key ); return *this; } @@ -799,13 +581,7 @@ SimpleElastix::Self& SimpleElastix ::RemoveParameter( const unsigned int index, const ParameterKeyType key ) { - if( index >= this->m_ParameterMapVector.size() ) - { - sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of parameters maps: " << this->m_ParameterMapVector.size() << "). Note that indexes are zero-based." ); - } - - this->m_ParameterMapVector[ index ].erase( key ); - + this->m_Pimple->RemoveParameter( index, key ); return *this; } @@ -813,17 +589,14 @@ SimpleElastix::ParameterMapType SimpleElastix ::ReadParameterFile( const std::string fileName ) { - ParameterObjectPointer parameterObject = ParameterObjectType::New(); - parameterObject->ReadParameterFile( fileName ); - return parameterObject->GetParameterMap( 0 ); + return this->m_Pimple->ReadParameterFile( fileName ); } SimpleElastix::Self& SimpleElastix ::WriteParameterFile( ParameterMapType const parameterMap, const std::string parameterFileName ) { - ParameterObjectPointer parameterObject = ParameterObjectType::New(); - parameterObject->WriteParameterFile( parameterMap, parameterFileName ); + this->m_Pimple->WriteParameterFile( parameterMap, parameterFileName); return *this; } @@ -831,261 +604,70 @@ SimpleElastix::ParameterMapType SimpleElastix ::GetDefaultParameterMap( const std::string transformName, const unsigned int numberOfResolutions, const double finalGridSpacingInPhysicalUnits ) { - return ParameterObjectType::GetDefaultParameterMap( transformName, numberOfResolutions, finalGridSpacingInPhysicalUnits ); + return this->m_Pimple->GetDefaultParameterMap( transformName, numberOfResolutions, finalGridSpacingInPhysicalUnits ); } Image SimpleElastix ::Execute( void ) { - if( this->GetNumberOfFixedImages() == 0 ) - { - sitkExceptionMacro( "Fixed image not set." ); - } - - if( this->GetNumberOfMovingImages() == 0 ) - { - sitkExceptionMacro( "Moving image not set." ); - } - - const PixelIDValueEnum FixedImagePixelID = this->GetFixedImage( 0 ).GetPixelID(); - const unsigned int FixedImageDimension = this->GetFixedImage( 0 ).GetDimension(); - const PixelIDValueEnum MovingImagePixelID = this->GetMovingImage( 0 ).GetPixelID(); - const unsigned int MovingImageDimension = this->GetMovingImage( 0 ).GetDimension(); - - for( unsigned int i = 1; i < this->GetNumberOfFixedImages(); ++i ) - { - if( this->GetFixedImage( i ).GetDimension() != FixedImageDimension ) - { - sitkExceptionMacro( "Fixed images must be of same dimension (fixed image at index 0 is of dimension " - << this->GetFixedImage( 0 ).GetDimension() << ", fixed image at index " << i - << " is of dimension \"" << this->GetFixedImage( i ).GetDimension() << "\")." ); - } - } - - for( unsigned int i = 1; i < this->GetNumberOfMovingImages(); ++i ) - { - if( this->GetMovingImage( i ).GetDimension() != MovingImageDimension ) - { - sitkExceptionMacro( "Moving images must be of same dimension as fixed images (fixed image at index 0 is of dimension " - << this->GetFixedImage( 0 ).GetDimension() << ", moving image at index " << i - << " is of dimension \"" << this->GetMovingImage( i ).GetDimension() << "\")." ); - } - } - - for( unsigned int i = 1; i < this->GetNumberOfFixedMasks(); ++i ) - { - if( this->GetFixedMask( i ).GetDimension() != FixedImageDimension ) - { - sitkExceptionMacro( "Fixed masks must be of same dimension as fixed images (fixed images are of dimension " - << this->GetFixedImage( 0 ).GetDimension() << ", fixed mask at index " << i - << " is of dimension \"" << this->GetFixedMask( i ).GetDimension() << "\")." ); - } - } - - for( unsigned int i = 1; i < this->GetNumberOfMovingMasks(); ++i ) - { - if( this->GetMovingMask( i ).GetDimension() != MovingImageDimension ) - { - sitkExceptionMacro( "Moving masks must be of same dimension as moving images (moving images are of dimension " - << this->GetMovingImage( 0 ).GetDimension() << ", moving mask at index " << i - << " is of dimension \"" << this->GetMovingMask( i ).GetDimension() << "\")." ); - } - } - - for( unsigned int i = 0; i < this->GetNumberOfFixedMasks(); ++i ) - { - if( this->GetFixedMask( i ).GetPixelID() != sitkUInt8 ) - { - sitkExceptionMacro( "Fixed mask must be of pixel type unsigned char (fixed mask at index " - << i << " is of type \"" << GetPixelIDValueAsElastixParameter( this->GetFixedMask( i ).GetPixelID() ) << "\")." ); - } - } - - for( unsigned int i = 0; i < this->GetNumberOfMovingMasks(); ++i ) - { - if( this->GetMovingMask( i ).GetPixelID() != sitkUInt8 ) - { - sitkExceptionMacro( "Moving mask must be of pixel type unsigned char (moving mask at index " - << i << " is of type \"" << GetPixelIDValueAsElastixParameter( this->GetMovingMask( i ).GetPixelID() ) << "\")." ); - } - } - - if( this->m_DualMemberFactory->HasMemberFunction( sitkFloat32, sitkFloat32, FixedImageDimension ) ) - { - return this->m_DualMemberFactory->GetMemberFunction( sitkFloat32, sitkFloat32, FixedImageDimension )(); - } - - sitkExceptionMacro( << "SimpleElastix does not support the combination of " - << FixedImageDimension << "-dimensional " - << GetPixelIDValueAsElastixParameter( FixedImagePixelID ) << " fixed image and a " - << MovingImageDimension << "-dimensional " - << GetPixelIDValueAsElastixParameter( MovingImagePixelID ) << " moving image. " - << "This a serious error. Contact developers at https://github.com/kaspermarstal/SimpleElastix/issues." ) + return this->m_Pimple->Execute(); } SimpleElastix::ParameterMapVectorType SimpleElastix ::GetTransformParameterMap( void ) { - if( this->m_TransformParameterMapVector.size() == 0 ) - { - sitkExceptionMacro( "Number of transform parameter maps: 0. Run registration with Execute()." ); - } - - return this->m_TransformParameterMapVector; + return this->m_Pimple->GetTransformParameterMap(); } SimpleElastix::ParameterMapType SimpleElastix ::GetTransformParameterMap( const unsigned int index ) { - if( this->GetNumberOfParameterMaps() == 0 ) - { - sitkExceptionMacro( "Number of transform parameter maps: 0. Run registration with Execute()." ); - } - - if( this->GetNumberOfParameterMaps() <= index ) - { - sitkExceptionMacro( "Index exceeds number of transform parameter maps (index: " << index - << ", number of parameter maps: " << this->GetNumberOfParameterMaps() << ")." ); - } - - return this->m_TransformParameterMapVector[ index ]; + return this->m_Pimple->GetTransformParameterMap( index ); } Image SimpleElastix ::GetResultImage( void ) { - if( this->IsEmpty( this->m_ResultImage ) ) - { - sitkExceptionMacro( "No result image found. Run registration with Execute()." ) - } - - return this->m_ResultImage; + return this->m_Pimple->GetResultImage(); } SimpleElastix::ParameterMapVectorType SimpleElastix ::ExecuteInverse( void ) { - return this->ExecuteInverse( this->GetParameterMap() ); + return this->m_Pimple->ExecuteInverse(); } SimpleElastix::ParameterMapVectorType SimpleElastix ::ExecuteInverse( std::map< std::string, std::vector< std::string > > inverseParameterMap ) { - return this->ExecuteInverse( ParameterMapVectorType( 1, inverseParameterMap ) ); + return this->m_Pimple->ExecuteInverse( ParameterMapVectorType( 1, inverseParameterMap ) ); } SimpleElastix::ParameterMapVectorType SimpleElastix ::ExecuteInverse( std::vector< std::map< std::string, std::vector< std::string > > > inverseParameterMapVector ) { - if( this->m_FixedImages.size() == 0 ) - { - sitkExceptionMacro( "No fixed images found. Elastix needs the fixed image of the forward transformation to compute the inverse transform.") - } - - if( this->m_MovingImages.size() == 0 ) - { - sitkExceptionMacro( "No moving images found. Elastix needs the moving image of the forward transformation to compute the inverse transform.") - } - - if( this->m_TransformParameterMapVector.size() == 0 ) - { - sitkExceptionMacro( "No forward transform parameter map found. Run forward registration before computing the inverse.") - } - - // Write forward transform parameter file to disk - // Head of chain - std::vector< std::string > forwardTransformParameterFileNames; - forwardTransformParameterFileNames.push_back( this->GetOutputDirectory() + "/forwardTransformParameterFile.0.txt" ); - ParameterMapVectorType forwardTransformParameterMaps = this->m_TransformParameterMapVector; - forwardTransformParameterMaps[ 0 ][ "InitialTransformParametersFileName" ] = ParameterValueVectorType( 1, "NoInitialTransform" ); - for( unsigned int i = 1; i < forwardTransformParameterMaps.size(); i++ ) - { - // Chain transform parameter file - forwardTransformParameterFileNames.push_back( this->GetOutputDirectory() + "/forwardTransformParameterFile." + ParameterObjectType::ToString( i ) + ".txt" ); - forwardTransformParameterMaps[ i ][ "InitialTransformParametersFileName" ] = ParameterValueVectorType( 1, forwardTransformParameterFileNames[ forwardTransformParameterFileNames.size()-1 ] ); - } - ParameterObjectPointer forwardTransformParameterMapObject = ParameterObjectType::New(); - forwardTransformParameterMapObject->SetParameterMap( forwardTransformParameterMaps ); - forwardTransformParameterMapObject->WriteParameterFile( forwardTransformParameterFileNames ); - - // Setup inverse transform parameter map - for( unsigned int i = 0; i < inverseParameterMapVector.size(); i++ ) - { - inverseParameterMapVector[ i ][ "Registration" ] = ParameterValueVectorType( 1, "MultiResolutionRegistration" ); - inverseParameterMapVector[ i ][ "Metric" ] = ParameterValueVectorType( 1, "DisplacementMagnitudePenalty" ); - - // RandomSparseMask will throw an error if no mask is supplied - if( inverseParameterMapVector[ i ][ "ImageSampler" ].size() > 0 && inverseParameterMapVector[ i ][ "ImageSampler" ][ 0 ] == "RandomSparseMask" ) - { - inverseParameterMapVector[ i ][ "ImageSampler" ] = ParameterValueVectorType( 1, "RandomCoordinate" ); - } - } - - // Setup inverse registration - SimpleElastix selx; - selx.SetInitialTransformParameterFileName( forwardTransformParameterFileNames[ 0 ] ); - selx.SetParameterMap( inverseParameterMapVector ); - - // Pass options from this SimpleElastix - selx.SetFixedImage( this->GetFixedImage( 0 ) ); - selx.SetMovingImage( this->GetFixedImage( 0 ) ); // <-- The fixed image is also used as the moving image. This is not a bug. - selx.SetOutputDirectory( this->GetOutputDirectory() ); - selx.SetLogFileName( this->GetLogFileName() ); - selx.SetLogToFile( this->GetLogToFile() ); - selx.SetLogToConsole( this->GetLogToConsole() ); - - selx.Execute(); - - for( unsigned int i = 0; i < forwardTransformParameterFileNames.size(); i++ ) - { - try - { - std::remove( forwardTransformParameterFileNames[ i ].c_str() ); - } - catch( ... ) - { - std::cout << "Error removing file " << forwardTransformParameterFileNames[ i ] << ". Continuing ... " << std::endl; - } - } - - // TODO: Change direction/origin/spacing to match moving image - - // Unlink the first transform parameter map - ParameterMapVectorType inverseTransformParameterMap = selx.GetTransformParameterMap(); - inverseTransformParameterMap[ 0 ][ "InitialTransformParametersFileName" ] = ParameterValueVectorType( 1, "NoInitialTransform" ); - this->m_InverseTransformParameterMapVector = inverseTransformParameterMap; - return this->m_InverseTransformParameterMapVector; + return this->m_Pimple->ExecuteInverse( inverseParameterMapVector ); } SimpleElastix::ParameterMapVectorType SimpleElastix ::GetInverseTransformParameterMap( void ) { - if( this->m_InverseTransformParameterMapVector.size() == 0 ) - { - sitkExceptionMacro( "Number of inverse transform parameter maps: 0. Run inverse registration with ExecuteInverse()." ); - } - - return this->m_InverseTransformParameterMapVector; + return this->m_Pimple->GetInverseTransformParameterMap(); } SimpleElastix::Self& SimpleElastix ::PrintParameterMap( void ) { - if( this->GetNumberOfParameterMaps() == 0 ) - { - sitkExceptionMacro( "Cannot print parameter maps: Number of parameter maps is 0." ) - } - - this->PrintParameterMap( this->GetParameterMap() ); + this->m_Pimple->PrintParameterMap(); return *this; } @@ -1093,7 +675,7 @@ SimpleElastix::Self& SimpleElastix ::PrintParameterMap( const ParameterMapType parameterMap ) { - this->PrintParameterMap( ParameterMapVectorType( 1, parameterMap ) ); + this->m_Pimple->PrintParameterMap( parameterMap ); return *this; } @@ -1101,20 +683,10 @@ SimpleElastix::Self& SimpleElastix ::PrintParameterMap( const ParameterMapVectorType parameterMapVector ) { - ParameterObjectPointer parameterObject = ParameterObjectType::New(); - parameterObject->SetParameterMap( parameterMapVector ); - parameterObject->Print( std::cout ); + this->m_Pimple->PrintParameterMap( parameterMapVector ); return *this; } -bool -SimpleElastix -::IsEmpty( const Image& image ) -{ - const bool isEmpty = image.GetWidth() == 0 && image.GetHeight() == 0; - return isEmpty; -} - /** * Procedural interface */ @@ -1152,9 +724,8 @@ PrintParameterMap( const SimpleElastix::ParameterMapType parameterMap ) void PrintParameterMap( const SimpleElastix::ParameterMapVectorType parameterMapVector ) { - SimpleElastix::ParameterObjectPointer parameterObject = SimpleElastix::ParameterObjectType::New(); - parameterObject->SetParameterMap( parameterMapVector ); - parameterObject->Print( std::cout ); + SimpleElastix selx; + selx.SetParameterMap( parameterMapVector ); } Image diff --git a/Code/Elastix/src/sitkSimpleElastixImpl.cxx b/Code/Elastix/src/sitkSimpleElastixImpl.cxx new file mode 100644 index 000000000..6c93f2321 --- /dev/null +++ b/Code/Elastix/src/sitkSimpleElastixImpl.cxx @@ -0,0 +1,1127 @@ +#ifndef __sitksimpleelastiximpl_cxx_ +#define __sitksimpleelastiximpl_cxx_ + +#include "sitkSimpleElastix.h" +#include "sitkSimpleElastixImpl.h" +#include "sitkCastImageFilter.h" + +namespace itk { + namespace simple { + +SimpleElastix::SimpleElastixImpl +::SimpleElastixImpl( void ) +{ + // Register this class with SimpleITK + this->m_DualMemberFactory.reset( new detail::DualMemberFunctionFactory< MemberFunctionType >( this ) ); + this->m_DualMemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, FloatPixelIDTypeList, 2 >(); + this->m_DualMemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, FloatPixelIDTypeList, 3 >(); + +#ifdef SITK_4D_IMAGES + this->m_DualMemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, FloatPixelIDTypeList, 4 >(); +#endif + + m_FixedImages = VectorOfImage(); + m_MovingImages = VectorOfImage(); + m_FixedMasks = VectorOfImage(); + m_MovingMasks = VectorOfImage(); + m_ResultImage = Image(); + + m_ParameterMapVector = ParameterMapVectorType(); + m_TransformParameterMapVector = ParameterMapVectorType(); + + m_FixedPointSetFileName = ""; + m_MovingPointSetFileName = ""; + + m_OutputDirectory = "."; + m_LogFileName = ""; + + this->m_LogToFile = false; + this->m_LogToConsole = false; + + ParameterMapVectorType defaultParameterMap; + defaultParameterMap.push_back( ParameterObjectType::GetDefaultParameterMap( "translation" ) ); + defaultParameterMap.push_back( ParameterObjectType::GetDefaultParameterMap( "affine" ) ); + defaultParameterMap.push_back( ParameterObjectType::GetDefaultParameterMap( "bspline" ) ); + this->SetParameterMap( defaultParameterMap ); +} + +SimpleElastix::SimpleElastixImpl +::~SimpleElastixImpl( void ) +{ +} + + +Image +SimpleElastix::SimpleElastixImpl +::Execute( void ) +{ + if( this->GetNumberOfFixedImages() == 0 ) + { + sitkExceptionMacro( "Fixed image not set." ); + } + + if( this->GetNumberOfMovingImages() == 0 ) + { + sitkExceptionMacro( "Moving image not set." ); + } + + const PixelIDValueEnum FixedImagePixelID = this->GetFixedImage( 0 ).GetPixelID(); + const unsigned int FixedImageDimension = this->GetFixedImage( 0 ).GetDimension(); + const PixelIDValueEnum MovingImagePixelID = this->GetMovingImage( 0 ).GetPixelID(); + const unsigned int MovingImageDimension = this->GetMovingImage( 0 ).GetDimension(); + + for( unsigned int i = 1; i < this->GetNumberOfFixedImages(); ++i ) + { + if( this->GetFixedImage( i ).GetDimension() != FixedImageDimension ) + { + sitkExceptionMacro( "Fixed images must be of same dimension (fixed image at index 0 is of dimension " + << this->GetFixedImage( 0 ).GetDimension() << ", fixed image at index " << i + << " is of dimension \"" << this->GetFixedImage( i ).GetDimension() << "\")." ); + } + } + + for( unsigned int i = 1; i < this->GetNumberOfMovingImages(); ++i ) + { + if( this->GetMovingImage( i ).GetDimension() != MovingImageDimension ) + { + sitkExceptionMacro( "Moving images must be of same dimension as fixed images (fixed image at index 0 is of dimension " + << this->GetFixedImage( 0 ).GetDimension() << ", moving image at index " << i + << " is of dimension \"" << this->GetMovingImage( i ).GetDimension() << "\")." ); + } + } + + for( unsigned int i = 1; i < this->GetNumberOfFixedMasks(); ++i ) + { + if( this->GetFixedMask( i ).GetDimension() != FixedImageDimension ) + { + sitkExceptionMacro( "Fixed masks must be of same dimension as fixed images (fixed images are of dimension " + << this->GetFixedImage( 0 ).GetDimension() << ", fixed mask at index " << i + << " is of dimension \"" << this->GetFixedMask( i ).GetDimension() << "\")." ); + } + } + + for( unsigned int i = 1; i < this->GetNumberOfMovingMasks(); ++i ) + { + if( this->GetMovingMask( i ).GetDimension() != MovingImageDimension ) + { + sitkExceptionMacro( "Moving masks must be of same dimension as moving images (moving images are of dimension " + << this->GetMovingImage( 0 ).GetDimension() << ", moving mask at index " << i + << " is of dimension \"" << this->GetMovingMask( i ).GetDimension() << "\")." ); + } + } + + for( unsigned int i = 0; i < this->GetNumberOfFixedMasks(); ++i ) + { + if( this->GetFixedMask( i ).GetPixelID() != sitkUInt8 ) + { + sitkExceptionMacro( "Fixed mask must be of pixel type unsigned char (fixed mask at index " + << i << " is of type \"" << GetPixelIDValueAsElastixParameter( this->GetFixedMask( i ).GetPixelID() ) << "\")." ); + } + } + + for( unsigned int i = 0; i < this->GetNumberOfMovingMasks(); ++i ) + { + if( this->GetMovingMask( i ).GetPixelID() != sitkUInt8 ) + { + sitkExceptionMacro( "Moving mask must be of pixel type unsigned char (moving mask at index " + << i << " is of type \"" << GetPixelIDValueAsElastixParameter( this->GetMovingMask( i ).GetPixelID() ) << "\")." ); + } + } + + if( this->m_DualMemberFactory->HasMemberFunction( sitkFloat32, sitkFloat32, FixedImageDimension ) ) + { + return this->m_DualMemberFactory->GetMemberFunction( sitkFloat32, sitkFloat32, FixedImageDimension )(); + } + + sitkExceptionMacro( << "SimpleElastix does not support the combination of " + << FixedImageDimension << "-dimensional " + << GetPixelIDValueAsElastixParameter( FixedImagePixelID ) << " fixed image and a " + << MovingImageDimension << "-dimensional " + << GetPixelIDValueAsElastixParameter( MovingImagePixelID ) << " moving image. " + << "This a serious error. Contact developers at https://github.com/kaspermarstal/SimpleElastix/issues." ) +} + +template< typename TFixedImage, typename TMovingImage > +Image +SimpleElastix::SimpleElastixImpl +::DualExecuteInternal( void ) +{ + typedef elastix::ElastixFilter< TFixedImage, TMovingImage > ElastixFilterType; + typedef typename ElastixFilterType::Pointer ElastixFilterPointer; + typedef typename ElastixFilterType::FixedMaskType FixedMaskType; + typedef typename ElastixFilterType::MovingMaskType MovingMaskType; + + try + { + ElastixFilterPointer elastixFilter = ElastixFilterType::New(); + + for( unsigned int i = 0; i < this->GetNumberOfFixedImages(); ++i ) + { + elastixFilter->AddFixedImage( itkDynamicCastInDebugMode< TFixedImage* >( Cast( this->GetFixedImage( i ), sitkFloat32 ).GetITKBase() ) ); + } + + for( unsigned int i = 0; i < this->GetNumberOfMovingImages(); ++i ) + { + elastixFilter->AddMovingImage( itkDynamicCastInDebugMode< TMovingImage* >( Cast( this->GetMovingImage( i ), sitkFloat32 ).GetITKBase() ) ); + } + + for( unsigned int i = 0; i < this->GetNumberOfFixedMasks(); ++i ) + { + elastixFilter->AddFixedMask( itkDynamicCastInDebugMode< FixedMaskType* >( this->GetFixedMask( i ).GetITKBase() ) ); + } + + for( unsigned int i = 0; i < this->GetNumberOfMovingMasks(); ++i ) + { + elastixFilter->AddMovingMask( itkDynamicCastInDebugMode< MovingMaskType* >( this->GetMovingMask( i ).GetITKBase() ) ); + } + + elastixFilter->SetInitialTransformParameterFileName( this->GetInitialTransformParameterFileName() ); + elastixFilter->SetFixedPointSetFileName( this->GetFixedPointSetFileName() ); + elastixFilter->SetMovingPointSetFileName( this->GetMovingPointSetFileName() ); + + elastixFilter->SetOutputDirectory( this->GetOutputDirectory() ); + elastixFilter->SetLogFileName( this->GetLogFileName() ); + elastixFilter->SetLogToFile( this->GetLogToFile() ); + elastixFilter->SetLogToConsole( this->GetLogToConsole() ); + + ParameterMapVectorType parameterMapVector = this->m_ParameterMapVector; + for( unsigned int i = 0; i < parameterMapVector.size(); i++ ) + { + parameterMapVector[ i ][ "FixedInternalImagePixelType" ] + = ParameterValueVectorType( 1, "float" ); + parameterMapVector[ i ][ "MovingInternalImagePixelType" ] + = ParameterValueVectorType( 1, "float" ); + parameterMapVector[ i ][ "ResultImagePixelType" ] + = ParameterValueVectorType( 1, "float" ); + } + + ParameterObjectPointer parameterObject = ParameterObjectType::New(); + parameterObject->SetParameterMap( parameterMapVector ); + elastixFilter->SetParameterObject( parameterObject ); + + elastixFilter->Update(); + + this->m_ResultImage = Image( itkDynamicCastInDebugMode< TFixedImage * >( elastixFilter->GetOutput() ) ); + this->m_ResultImage.MakeUnique(); + this->m_TransformParameterMapVector = elastixFilter->GetTransformParameterObject()->GetParameterMap(); + } + catch( itk::ExceptionObject &e ) + { + sitkExceptionMacro( << e ); + } + + return this->m_ResultImage; +} + +const std::string +SimpleElastix::SimpleElastixImpl +::GetName( void ) +{ + const std::string name = "SimpleElastix"; + return name; +} + +void +SimpleElastix::SimpleElastixImpl +::SetFixedImage( const Image& fixedImage ) +{ + if( this->IsEmpty( fixedImage ) ) + { + sitkExceptionMacro( "Image is empty." ) + } + + this->RemoveFixedImage(); + this->m_FixedImages.push_back( fixedImage ); +} + +void +SimpleElastix::SimpleElastixImpl +::SetFixedImage( const VectorOfImage& fixedImages ) +{ + if( fixedImages.size() == 0u ) + { + sitkExceptionMacro( "Cannot set fixed images from empty vector" ); + } + + this->RemoveFixedImage(); + this->m_FixedImages = fixedImages; +} + +void +SimpleElastix::SimpleElastixImpl +::AddFixedImage( const Image& fixedImage ) +{ + if( this->IsEmpty( fixedImage ) ) + { + sitkExceptionMacro( "Image is empty." ) + } + + this->m_FixedImages.push_back( fixedImage ); +} + +Image& +SimpleElastix::SimpleElastixImpl +::GetFixedImage( const unsigned long index ) +{ + if( index < this->m_FixedImages.size() ) + { + return this->m_FixedImages[ index ]; + } + + sitkExceptionMacro( "Index out of range (index: " << index << ", number of fixed images: " << this->m_FixedImages.size() << ")" ); +} + +SimpleElastix::SimpleElastixImpl::VectorOfImage& +SimpleElastix::SimpleElastixImpl +::GetFixedImage( void ) +{ + return this->m_FixedImages; +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveFixedImage( const unsigned long index ) +{ + if( index < this->m_FixedImages.size() ) + { + this->m_FixedImages.erase( this->m_FixedImages.begin() + index ); + } + + sitkExceptionMacro( "Index out of range (index: " << index << ", number of fixed images: " << this->m_FixedImages.size() << ")" ); +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveFixedImage( void ) +{ + this->m_FixedImages.clear(); +} + +unsigned int +SimpleElastix::SimpleElastixImpl +::GetNumberOfFixedImages( void ) +{ + return this->m_FixedImages.size(); +} + +void +SimpleElastix::SimpleElastixImpl +::SetMovingImage( const Image& movingImage ) +{ + if( this->IsEmpty( movingImage ) ) + { + sitkExceptionMacro( "Image is empty." ) + } + + this->RemoveMovingImage(); + this->m_MovingImages.push_back( movingImage ); +} + +void +SimpleElastix::SimpleElastixImpl +::SetMovingImage( const VectorOfImage& movingImages ) +{ + if( movingImages.size() == 0u ) + { + sitkExceptionMacro( "Cannot set moving images from empty vector" ); + } + + this->RemoveMovingImage(); + this->m_MovingImages = movingImages; +} + +void +SimpleElastix::SimpleElastixImpl +::AddMovingImage( const Image& movingImage ) +{ + if( this->IsEmpty( movingImage ) ) + { + sitkExceptionMacro( "Image is empty." ) + } + + this->m_MovingImages.push_back( movingImage ); +} + +Image& +SimpleElastix::SimpleElastixImpl +::GetMovingImage( const unsigned long index ) +{ + if( index < this->m_MovingImages.size() ) + { + return this->m_MovingImages[ index ]; + } + + sitkExceptionMacro( "Index out of range (index: " << index << ", number of moving images: " << this->m_MovingImages.size() << ")" ); +} + +SimpleElastix::SimpleElastixImpl::VectorOfImage& +SimpleElastix::SimpleElastixImpl +::GetMovingImage( void ) +{ + return this->m_MovingImages; +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveMovingImage( const unsigned long index ) +{ + if( index < this->m_MovingImages.size() ) + { + this->m_MovingImages.erase( this->m_MovingImages.begin() + index ); + } + + sitkExceptionMacro( "Index out of range (index: " << index << ", number of moving images: " << this->m_MovingImages.size() << ")" ); +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveMovingImage( void ) +{ + this->m_MovingImages.clear(); +} + +unsigned int +SimpleElastix::SimpleElastixImpl +::GetNumberOfMovingImages( void ) +{ + return this->m_MovingImages.size(); +} + +void +SimpleElastix::SimpleElastixImpl +::SetFixedMask( const Image& fixedMask ) +{ + if( this->IsEmpty( fixedMask ) ) + { + sitkExceptionMacro( "Image is empty." ) + } + + this->RemoveFixedMask(); + this->m_FixedMasks.push_back( fixedMask ); +} + +void +SimpleElastix::SimpleElastixImpl +::SetFixedMask( const VectorOfImage& fixedMasks ) +{ + if( fixedMasks.size() == 0u ) + { + sitkExceptionMacro( "Cannot set fixed images from empty vector" ); + } + + this->RemoveFixedMask(); + this->m_FixedMasks = fixedMasks; +} + +void +SimpleElastix::SimpleElastixImpl +::AddFixedMask( const Image& fixedMask ) +{ + if( this->IsEmpty( fixedMask ) ) + { + sitkExceptionMacro( "Image is empty." ) + } + + this->m_FixedMasks.push_back( fixedMask ); +} + +Image& +SimpleElastix::SimpleElastixImpl +::GetFixedMask( const unsigned long index ) +{ + if( index < this->m_FixedMasks.size() ) + { + return this->m_FixedMasks[ index ]; + } + + sitkExceptionMacro( "Index out of range (index: " << index << ", number of fixed masks: " << this->m_FixedMasks.size() << ")" ); +} + +SimpleElastix::VectorOfImage& +SimpleElastix::SimpleElastixImpl +::GetFixedMask( void ) +{ + return this->m_FixedMasks; +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveFixedMask( const unsigned long index ) +{ + if( index < this->m_FixedMasks.size() ) + { + this->m_FixedMasks.erase( this->m_FixedMasks.begin() + index ); + } + + sitkExceptionMacro( "Index out of range (index: " << index << ", number of fixed masks: " << this->m_FixedMasks.size() << ")" ); +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveFixedMask( void ) +{ + this->m_FixedMasks.clear(); +} + +unsigned int +SimpleElastix::SimpleElastixImpl +::GetNumberOfFixedMasks( void ) +{ + return this->m_FixedMasks.size(); +} + +void +SimpleElastix::SimpleElastixImpl +::SetMovingMask( const Image& movingMask ) +{ + if( this->IsEmpty( movingMask ) ) + { + sitkExceptionMacro( "Image is empty." ) + } + + this->RemoveMovingMask(); + this->m_MovingMasks.push_back( movingMask ); +} + +void +SimpleElastix::SimpleElastixImpl +::SetMovingMask( const VectorOfImage& movingMasks ) +{ + if( movingMasks.size() == 0u ) + { + sitkExceptionMacro( "Cannot set moving masks from empty vector" ); + } + + this->RemoveMovingMask(); + this->m_MovingMasks = movingMasks; +} + +void +SimpleElastix::SimpleElastixImpl +::AddMovingMask( const Image& movingMask ) +{ + if( this->IsEmpty( movingMask ) ) + { + sitkExceptionMacro( "Image is empty." ) + } + + this->m_MovingMasks.push_back( movingMask ); +} + +Image& +SimpleElastix::SimpleElastixImpl +::GetMovingMask( const unsigned long index ) +{ + if( index < this->m_MovingMasks.size() ) + { + return this->m_MovingMasks[ index ]; + } + + sitkExceptionMacro( "Index out of range (index: " << index << ", number of moving masks: " << this->m_MovingMasks.size() << ")" ); +} + +SimpleElastix::SimpleElastixImpl::VectorOfImage& +SimpleElastix::SimpleElastixImpl +::GetMovingMask( void ) +{ + return this->m_MovingMasks; +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveMovingMask( const unsigned long index ) +{ + if( index < this->m_MovingMasks.size() ) + { + this->m_MovingMasks.erase( this->m_MovingMasks.begin() + index ); + } + + sitkExceptionMacro( "Index out of range (index: " << index << ", number of moving masks: " << this->m_MovingMasks.size() << ")" ); +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveMovingMask( void ) +{ + this->m_MovingMasks.clear(); +} + +unsigned int +SimpleElastix::SimpleElastixImpl +::GetNumberOfMovingMasks( void ) +{ + return this->m_MovingMasks.size(); +} + +void +SimpleElastix::SimpleElastixImpl +::SetFixedPointSetFileName( const std::string fixedPointSetFileName ) +{ + this->m_FixedPointSetFileName = fixedPointSetFileName; +} + +std::string +SimpleElastix::SimpleElastixImpl +::GetFixedPointSetFileName( void ) +{ + return this->m_FixedPointSetFileName; +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveFixedPointSetFileName( void ) +{ + this->m_FixedPointSetFileName = ""; +} + +void +SimpleElastix::SimpleElastixImpl +::SetMovingPointSetFileName( const std::string movingPointSetFileName ) +{ + this->m_MovingPointSetFileName = movingPointSetFileName; +} + +std::string +SimpleElastix::SimpleElastixImpl +::GetMovingPointSetFileName( void ) +{ + return this->m_MovingPointSetFileName; +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveMovingPointSetFileName( void ) +{ + this->m_MovingPointSetFileName = ""; +} + +void +SimpleElastix::SimpleElastixImpl +::SetOutputDirectory( const std::string outputDirectory ) +{ + this->m_OutputDirectory = outputDirectory; +} + +std::string +SimpleElastix::SimpleElastixImpl +::GetOutputDirectory( void ) +{ + return this->m_OutputDirectory; +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveOutputDirectory( void ) +{ + this->m_OutputDirectory = ""; +} + +void +SimpleElastix::SimpleElastixImpl +::SetLogFileName( std::string logFileName ) +{ + this->m_LogFileName = logFileName; +} + +std::string +SimpleElastix::SimpleElastixImpl +::GetLogFileName( void ) +{ + return this->m_LogFileName; +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveLogFileName( void ) +{ + this->m_LogFileName = ""; +} + +void +SimpleElastix::SimpleElastixImpl +::SetLogToFile( bool logToFile ) +{ + this->m_LogToFile = logToFile; +} + +bool +SimpleElastix::SimpleElastixImpl +::GetLogToFile( void ) +{ + return this->m_LogToFile; +} + +void +SimpleElastix::SimpleElastixImpl +::LogToFileOn() +{ + this->SetLogToFile( true ); +} + +void +SimpleElastix::SimpleElastixImpl +::LogToFileOff() +{ + this->SetLogToFile( false ); +} + +void +SimpleElastix::SimpleElastixImpl +::SetLogToConsole( bool logToConsole ) +{ + this->m_LogToConsole = logToConsole; +} + +bool +SimpleElastix::SimpleElastixImpl +::GetLogToConsole( void ) +{ + return this->m_LogToConsole; +} + +void +SimpleElastix::SimpleElastixImpl +::LogToConsoleOn() +{ + this->SetLogToConsole( true ); +} + +void +SimpleElastix::SimpleElastixImpl +::LogToConsoleOff() +{ + this->SetLogToConsole( false ); +} + +void +SimpleElastix::SimpleElastixImpl +::SetParameterMap( const std::string transformName, const unsigned int numberOfResolutions, const double finalGridSpacingInPhysicalUnits ) +{ + ParameterMapType parameterMap = ParameterObjectType::GetDefaultParameterMap( transformName, numberOfResolutions, finalGridSpacingInPhysicalUnits ); + this->SetParameterMap( parameterMap ); +} + +void +SimpleElastix::SimpleElastixImpl +::SetParameterMap( const ParameterMapType parameterMap ) +{ + ParameterMapVectorType parameterMapVector = ParameterMapVectorType( 1, parameterMap ); + this->SetParameterMap( parameterMapVector ); +} + +void +SimpleElastix::SimpleElastixImpl +::SetParameterMap( const ParameterMapVectorType parameterMapVector ) +{ + this->m_ParameterMapVector = parameterMapVector; +} + +void +SimpleElastix::SimpleElastixImpl +::AddParameterMap( const ParameterMapType parameterMap ) +{ + this->m_ParameterMapVector.push_back( parameterMap ); +} + +SimpleElastix::SimpleElastixImpl::ParameterMapVectorType +SimpleElastix::SimpleElastixImpl +::GetParameterMap( void ) +{ + return this->m_ParameterMapVector; +} + +unsigned int +SimpleElastix::SimpleElastixImpl +::GetNumberOfParameterMaps( void ) +{ + return this->m_ParameterMapVector.size(); +} + +void +SimpleElastix::SimpleElastixImpl +::SetInitialTransformParameterFileName( const std::string initialTransformParameterFileName ) +{ + this->m_InitialTransformParameterMapFileName = initialTransformParameterFileName; +} + +std::string +SimpleElastix::SimpleElastixImpl +::GetInitialTransformParameterFileName( void ) +{ + return m_InitialTransformParameterMapFileName ; +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveInitialTransformParameterFileName( void ) +{ + this->m_InitialTransformParameterMapFileName = ""; +} + +void +SimpleElastix::SimpleElastixImpl +::SetParameter( const ParameterKeyType key, const ParameterValueType value ) +{ + for( unsigned int i = 0; i < this->m_ParameterMapVector.size(); i++ ) + { + this->SetParameter( i, key, value ); + } +} + +void +SimpleElastix::SimpleElastixImpl +::SetParameter( const ParameterKeyType key, const ParameterValueVectorType value ) +{ + for( unsigned int i = 0; i < this->m_ParameterMapVector.size(); i++ ) + { + this->SetParameter( i, key, value ); + } +} + +void +SimpleElastix::SimpleElastixImpl +::SetParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueType value ) +{ + if( index >= this->m_ParameterMapVector.size() ) + { + sitkExceptionMacro( "Parameter map index is out of range (index: " << index << "; number of parameters maps: " << this->m_ParameterMapVector.size() << "). Note that indexes are zero-based." ); + } + + this->m_ParameterMapVector[ index ][ key ] = ParameterValueVectorType( 1, value ); +} + +void +SimpleElastix::SimpleElastixImpl +::SetParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueVectorType value ) +{ + if( index >= this->m_ParameterMapVector.size() ) + { + sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of parameters maps: " << this->m_ParameterMapVector.size() << "). Note that indexes are zero-based." ); + } + + this->m_ParameterMapVector[ index ][ key ] = value; +} + +void +SimpleElastix::SimpleElastixImpl +::AddParameter( const ParameterKeyType key, const ParameterValueType value ) +{ + for( unsigned int i = 0; i < this->m_ParameterMapVector.size(); i++ ) + { + this->AddParameter( i, key, value ); + } +} + +void +SimpleElastix::SimpleElastixImpl +::AddParameter( const ParameterKeyType key, const ParameterValueVectorType value ) +{ + for( unsigned int i = 0; i < this->m_ParameterMapVector.size(); i++ ) + { + this->AddParameter( i, key, value ); + } +} + +void +SimpleElastix::SimpleElastixImpl +::AddParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueType value ) +{ + if( index >= this->m_ParameterMapVector.size() ) + { + sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of parameters maps: " << this->m_ParameterMapVector.size() << "). Note that indexes are zero-based." ); + } + + if( this->m_ParameterMapVector[ index ].find( key ) == this->m_ParameterMapVector[ index ].end() ) + { + this->SetParameter( index, key, value ); + } + else + { + this->m_ParameterMapVector[ index ][ key ].push_back( value ); + } +} + +void +SimpleElastix::SimpleElastixImpl +::AddParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueVectorType value ) +{ + if( index >= this->m_ParameterMapVector.size() ) + { + sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of parameters maps: " << this->m_ParameterMapVector.size() << "). Note that indexes are zero-based." ); + } + + if( this->m_ParameterMapVector[ index ].find( key ) == this->m_ParameterMapVector[ index ].end() ) + { + this->SetParameter( index, key, value ); + } + else + { + for( unsigned int i = 0; i < value.size(); i++ ) + { + this->m_ParameterMapVector[ index ][ key ].push_back( value[ i ] ); + } + } +} + +SimpleElastix::SimpleElastixImpl::ParameterValueVectorType +SimpleElastix::SimpleElastixImpl +::GetParameter( const ParameterKeyType key ) +{ + if( this->m_ParameterMapVector.size() > 0 ) + { + sitkExceptionMacro( "An index is needed when more than one parameter map is present. Please specify the parameter map number as the first argument." ); + } + + return this->GetParameter( 0, key ); +} + +SimpleElastix::SimpleElastixImpl::ParameterValueVectorType +SimpleElastix::SimpleElastixImpl +::GetParameter( const unsigned int index, const ParameterKeyType key ) +{ + if( index >= this->m_ParameterMapVector.size() ) + { + sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of parameters maps: " << this->m_ParameterMapVector.size() << "). Note that indexes are zero-based." ); + } + + return this->m_ParameterMapVector[ index ][ key ]; +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveParameter( const ParameterKeyType key ) +{ + for( unsigned int i = 0; i < this->m_ParameterMapVector.size(); i++ ) + { + this->RemoveParameter( i, key ); + } +} + +void +SimpleElastix::SimpleElastixImpl +::RemoveParameter( const unsigned int index, const ParameterKeyType key ) +{ + if( index >= this->m_ParameterMapVector.size() ) + { + sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of parameters maps: " << this->m_ParameterMapVector.size() << "). Note that indexes are zero-based." ); + } + + this->m_ParameterMapVector[ index ].erase( key ); +} + +SimpleElastix::SimpleElastixImpl::ParameterMapType +SimpleElastix::SimpleElastixImpl +::ReadParameterFile( const std::string fileName ) +{ + ParameterObjectPointer parameterObject = ParameterObjectType::New(); + parameterObject->ReadParameterFile( fileName ); + return parameterObject->GetParameterMap( 0 ); +} + +void +SimpleElastix::SimpleElastixImpl +::WriteParameterFile( ParameterMapType const parameterMap, const std::string parameterFileName ) +{ + ParameterObjectPointer parameterObject = ParameterObjectType::New(); + parameterObject->WriteParameterFile( parameterMap, parameterFileName ); +} + +SimpleElastix::SimpleElastixImpl::ParameterMapType +SimpleElastix::SimpleElastixImpl +::GetDefaultParameterMap( const std::string transformName, const unsigned int numberOfResolutions, const double finalGridSpacingInPhysicalUnits ) +{ + return ParameterObjectType::GetDefaultParameterMap( transformName, numberOfResolutions, finalGridSpacingInPhysicalUnits ); +} + +SimpleElastix::SimpleElastixImpl::ParameterMapVectorType +SimpleElastix::SimpleElastixImpl +::GetTransformParameterMap( void ) +{ + if( this->m_TransformParameterMapVector.size() == 0 ) + { + sitkExceptionMacro( "Number of transform parameter maps: 0. Run registration with Execute()." ); + } + + return this->m_TransformParameterMapVector; +} + +SimpleElastix::SimpleElastixImpl::ParameterMapType +SimpleElastix::SimpleElastixImpl +::GetTransformParameterMap( const unsigned int index ) +{ + if( this->GetNumberOfParameterMaps() == 0 ) + { + sitkExceptionMacro( "Number of transform parameter maps: 0. Run registration with Execute()." ); + } + + if( this->GetNumberOfParameterMaps() <= index ) + { + sitkExceptionMacro( "Index exceeds number of transform parameter maps (index: " << index + << ", number of parameter maps: " << this->GetNumberOfParameterMaps() << ")." ); + } + + return this->m_TransformParameterMapVector[ index ]; +} + +Image +SimpleElastix::SimpleElastixImpl +::GetResultImage( void ) +{ + if( this->IsEmpty( this->m_ResultImage ) ) + { + sitkExceptionMacro( "No result image found. Run registration with Execute()." ) + } + + return this->m_ResultImage; +} + +SimpleElastix::SimpleElastixImpl::ParameterMapVectorType +SimpleElastix::SimpleElastixImpl +::ExecuteInverse( void ) +{ + return this->ExecuteInverse( this->GetParameterMap() ); +} + +SimpleElastix::SimpleElastixImpl::ParameterMapVectorType +SimpleElastix::SimpleElastixImpl +::ExecuteInverse( std::map< std::string, std::vector< std::string > > inverseParameterMap ) +{ + return this->ExecuteInverse( ParameterMapVectorType( 1, inverseParameterMap ) ); +} + +SimpleElastix::SimpleElastixImpl::ParameterMapVectorType +SimpleElastix::SimpleElastixImpl +::ExecuteInverse( std::vector< std::map< std::string, std::vector< std::string > > > inverseParameterMapVector ) +{ + if( this->m_FixedImages.size() == 0 ) + { + sitkExceptionMacro( "No fixed images found. Elastix needs the fixed image of the forward transformation to compute the inverse transform.") + } + + if( this->m_MovingImages.size() == 0 ) + { + sitkExceptionMacro( "No moving images found. Elastix needs the moving image of the forward transformation to compute the inverse transform.") + } + + if( this->m_TransformParameterMapVector.size() == 0 ) + { + sitkExceptionMacro( "No forward transform parameter map found. Run forward registration before computing the inverse.") + } + + // Write forward transform parameter file to disk + // Head of chain + std::vector< std::string > forwardTransformParameterFileNames; + forwardTransformParameterFileNames.push_back( this->GetOutputDirectory() + "/forwardTransformParameterFile.0.txt" ); + ParameterMapVectorType forwardTransformParameterMaps = this->m_TransformParameterMapVector; + forwardTransformParameterMaps[ 0 ][ "InitialTransformParametersFileName" ] = ParameterValueVectorType( 1, "NoInitialTransform" ); + for( unsigned int i = 1; i < forwardTransformParameterMaps.size(); i++ ) + { + // Chain transform parameter file + forwardTransformParameterFileNames.push_back( this->GetOutputDirectory() + "/forwardTransformParameterFile." + ParameterObjectType::ToString( i ) + ".txt" ); + forwardTransformParameterMaps[ i ][ "InitialTransformParametersFileName" ] = ParameterValueVectorType( 1, forwardTransformParameterFileNames[ forwardTransformParameterFileNames.size()-1 ] ); + } + ParameterObjectPointer forwardTransformParameterMapObject = ParameterObjectType::New(); + forwardTransformParameterMapObject->SetParameterMap( forwardTransformParameterMaps ); + forwardTransformParameterMapObject->WriteParameterFile( forwardTransformParameterFileNames ); + + // Setup inverse transform parameter map + for( unsigned int i = 0; i < inverseParameterMapVector.size(); i++ ) + { + inverseParameterMapVector[ i ][ "Registration" ] = ParameterValueVectorType( 1, "MultiResolutionRegistration" ); + inverseParameterMapVector[ i ][ "Metric" ] = ParameterValueVectorType( 1, "DisplacementMagnitudePenalty" ); + + // RandomSparseMask will throw an error if no mask is supplied + if( inverseParameterMapVector[ i ][ "ImageSampler" ].size() > 0 && inverseParameterMapVector[ i ][ "ImageSampler" ][ 0 ] == "RandomSparseMask" ) + { + inverseParameterMapVector[ i ][ "ImageSampler" ] = ParameterValueVectorType( 1, "RandomCoordinate" ); + } + } + + // Setup inverse registration + SimpleElastix selx; + selx.SetInitialTransformParameterFileName( forwardTransformParameterFileNames[ 0 ] ); + selx.SetParameterMap( inverseParameterMapVector ); + + // Pass options from this SimpleElastix + selx.SetFixedImage( this->GetFixedImage( 0 ) ); + selx.SetMovingImage( this->GetFixedImage( 0 ) ); // <-- The fixed image is also used as the moving image. This is not a bug. + selx.SetOutputDirectory( this->GetOutputDirectory() ); + selx.SetLogFileName( this->GetLogFileName() ); + selx.SetLogToFile( this->GetLogToFile() ); + selx.SetLogToConsole( this->GetLogToConsole() ); + + selx.Execute(); + + for( unsigned int i = 0; i < forwardTransformParameterFileNames.size(); i++ ) + { + try + { + std::remove( forwardTransformParameterFileNames[ i ].c_str() ); + } + catch( ... ) + { + std::cout << "Error removing file " << forwardTransformParameterFileNames[ i ] << ". Continuing ... " << std::endl; + } + } + + // TODO: Change direction/origin/spacing to match moving image + + // Unlink the first transform parameter map + ParameterMapVectorType inverseTransformParameterMap = selx.GetTransformParameterMap(); + inverseTransformParameterMap[ 0 ][ "InitialTransformParametersFileName" ] = ParameterValueVectorType( 1, "NoInitialTransform" ); + this->m_InverseTransformParameterMapVector = inverseTransformParameterMap; + return this->m_InverseTransformParameterMapVector; +} + +SimpleElastix::SimpleElastixImpl::ParameterMapVectorType +SimpleElastix::SimpleElastixImpl +::GetInverseTransformParameterMap( void ) +{ + if( this->m_InverseTransformParameterMapVector.size() == 0 ) + { + sitkExceptionMacro( "Number of inverse transform parameter maps: 0. Run inverse registration with ExecuteInverse()." ); + } + + return this->m_InverseTransformParameterMapVector; +} + +void +SimpleElastix::SimpleElastixImpl +::PrintParameterMap( void ) +{ + if( this->GetNumberOfParameterMaps() == 0 ) + { + sitkExceptionMacro( "Cannot print parameter maps: Number of parameter maps is 0." ) + } + + this->PrintParameterMap( this->GetParameterMap() ); +} + +void +SimpleElastix::SimpleElastixImpl +::PrintParameterMap( const ParameterMapType parameterMap ) +{ + this->PrintParameterMap( ParameterMapVectorType( 1, parameterMap ) ); +} + +void +SimpleElastix::SimpleElastixImpl +::PrintParameterMap( const ParameterMapVectorType parameterMapVector ) +{ + ParameterObjectPointer parameterObject = ParameterObjectType::New(); + parameterObject->SetParameterMap( parameterMapVector ); + parameterObject->Print( std::cout ); +} + +bool +SimpleElastix::SimpleElastixImpl +::IsEmpty( const Image& image ) +{ + const bool isEmpty = image.GetWidth() == 0 && image.GetHeight() == 0; + return isEmpty; +} + +} // end namespace simple +} // end namespace itk + +#endif // __sitksimpleelastiximpl_cxx_ \ No newline at end of file diff --git a/Code/Elastix/src/sitkSimpleElastixImpl.h b/Code/Elastix/src/sitkSimpleElastixImpl.h new file mode 100644 index 000000000..644df06de --- /dev/null +++ b/Code/Elastix/src/sitkSimpleElastixImpl.h @@ -0,0 +1,177 @@ +#ifndef __sitksimpleelastiximpl_h_ +#define __sitksimpleelastiximpl_h_ + +// SimpleITK +#include "sitkSimpleElastix.h" +#include "sitkMemberFunctionFactory.h" +#include "sitkDualMemberFunctionFactory.h" + +// Elastix +#include "elxElastixFilter.h" +#include "elxParameterObject.h" + +namespace itk { + namespace simple { + +struct SimpleElastix::SimpleElastixImpl +{ + + SimpleElastixImpl( void ); + ~SimpleElastixImpl( void ); + + typedef SimpleElastixImpl Self; + + typedef SimpleElastix::VectorOfImage VectorOfImage; + + typedef SimpleElastix::ParameterKeyType ParameterKeyType; + typedef SimpleElastix::ParameterValueType ParameterValueType; + typedef SimpleElastix::ParameterValueVectorType ParameterValueVectorType; + typedef SimpleElastix::ParameterValueVectorIterator ParameterValueVectorIterator; + typedef SimpleElastix::ParameterMapType ParameterMapType; + typedef SimpleElastix::ParameterMapVectorType ParameterMapVectorType; + typedef SimpleElastix::ParameterMapIterator ParameterMapIterator; + typedef SimpleElastix::ParameterMapConstIterator ParameterMapConstIterator; + + typedef elastix::ParameterObject ParameterObjectType; + typedef elastix::ParameterObject::Pointer ParameterObjectPointer; + + const std::string GetName( void ); + + void SetFixedImage( const Image& fixedImage ); + void SetFixedImage( const VectorOfImage& fixedImages ); + void AddFixedImage( const Image& fixedImage ); + Image& GetFixedImage( const unsigned long index ); + VectorOfImage& GetFixedImage( void ); + void RemoveFixedImage( const unsigned long index ); + void RemoveFixedImage( void ); + unsigned int GetNumberOfFixedImages(); + + void SetMovingImage( const Image& movingImages ); + void SetMovingImage( const VectorOfImage& movingImage ); + void AddMovingImage( const Image& movingImage ); + Image& GetMovingImage( const unsigned long index ); + VectorOfImage& GetMovingImage( void ); + void RemoveMovingImage( const unsigned long index ); + void RemoveMovingImage( void ); + unsigned int GetNumberOfMovingImages(); + + void SetFixedMask( const Image& fixedMask ); + void SetFixedMask( const VectorOfImage& fixedMasks ); + void AddFixedMask( const Image& fixedMask ); + Image& GetFixedMask( const unsigned long index ); + VectorOfImage& GetFixedMask( void ); + void RemoveFixedMask( const unsigned long index ); + void RemoveFixedMask( void ); + unsigned int GetNumberOfFixedMasks(); + + void SetMovingMask( const Image& movingMask ); + void SetMovingMask( const VectorOfImage& movingMasks ); + void AddMovingMask( const Image& movingMask ); + Image& GetMovingMask( const unsigned long index ); + VectorOfImage& GetMovingMask( void ); + void RemoveMovingMask( const unsigned long index ); + void RemoveMovingMask( void ); + unsigned int GetNumberOfMovingMasks(); + + void SetFixedPointSetFileName( const std::string movingPointSetFileName ); + std::string GetFixedPointSetFileName( void ); + void RemoveFixedPointSetFileName( void ); + + void SetMovingPointSetFileName( const std::string movingPointSetFileName ); + std::string GetMovingPointSetFileName( void ); + void RemoveMovingPointSetFileName( void ); + + void SetOutputDirectory( const std::string outputDirectory ); + std::string GetOutputDirectory( void ); + void RemoveOutputDirectory( void ); + + void SetLogFileName( const std::string logFileName ); + std::string GetLogFileName( void ); + void RemoveLogFileName( void ); + + void SetLogToFile( const bool logToFile ); + bool GetLogToFile( void ); + void LogToFileOn( void ); + void LogToFileOff( void ); + + void SetLogToConsole( bool ); + bool GetLogToConsole( void ); + void LogToConsoleOn(); + void LogToConsoleOff(); + + void SetParameterMap( const std::string transformName, const unsigned int numberOfResolutions = 4u, const double finalGridSpacingInPhysicalUnits = 10.0 ); + void SetParameterMap( const std::vector< std::map< std::string, std::vector< std::string > > > parameterMapVector ); + void SetParameterMap( const std::map< std::string, std::vector< std::string > > parameterMap ); + void AddParameterMap( const std::map< std::string, std::vector< std::string > > parameterMap ); + std::vector< std::map< std::string, std::vector< std::string > > > GetParameterMap( void ); + std::map< std::string, std::vector< std::string > > GetDefaultParameterMap( const std::string transformName, const unsigned int numberOfResolutions = 4, const double finalGridSpacingInPhysicalUnits = 10.0 ); + unsigned int GetNumberOfParameterMaps( void ); + + void SetParameter( const std::string key, const std::string value ); + void SetParameter( const std::string key, const std::vector< std::string > value ); + void SetParameter( const unsigned int index, const std::string key, const std::string value ); + void SetParameter( const unsigned int index, const std::string key, const std::vector< std::string > value ); + void AddParameter( const std::string key, const std::string value ); + void AddParameter( const unsigned int index, const std::string key, const std::string value ); + void AddParameter( const std::string key, const std::vector< std::string > value ); + void AddParameter( const unsigned int index, const std::string key, const std::vector< std::string > value ); + std::vector< std::string > GetParameter( const std::string key ); + std::vector< std::string > GetParameter( const unsigned int index, const std::string key ); + void RemoveParameter( const std::string key ); + void RemoveParameter( const unsigned int index, const std::string key ); + + void SetInitialTransformParameterFileName( const std::string initialTransformParmaterFileName ); + std::string GetInitialTransformParameterFileName( void ); + void RemoveInitialTransformParameterFileName( void ); + + std::map< std::string, std::vector< std::string > > ReadParameterFile( const std::string filename ); + void WriteParameterFile( const std::map< std::string, std::vector< std::string > > parameterMap, const std::string filename ); + + Image Execute( void ); + std::vector< std::map< std::string, std::vector< std::string > > > GetTransformParameterMap( void ); + std::map< std::string, std::vector< std::string > > GetTransformParameterMap( const unsigned int index ); + Image GetResultImage( void ); + + std::vector< std::map< std::string, std::vector< std::string > > > ExecuteInverse( void ); + std::vector< std::map< std::string, std::vector< std::string > > > ExecuteInverse( std::map< std::string, std::vector< std::string > > inverseParameterMap ); + std::vector< std::map< std::string, std::vector< std::string > > > ExecuteInverse( std::vector< std::map< std::string, std::vector< std::string > > > inverseParameterMapVector ); + std::vector< std::map< std::string, std::vector< std::string > > > GetInverseTransformParameterMap( void ); + + void PrintParameterMap( void ); + void PrintParameterMap( const ParameterMapType parameterMapVector ); + void PrintParameterMap( const ParameterMapVectorType parameterMapVector ); + + bool IsEmpty( const Image& image ); + + // Definitions for SimpleITK member factory + typedef Image ( Self::*MemberFunctionType )( void ); + template< class TFixedImage, class TMovingImage > Image DualExecuteInternal( void ); + friend struct detail::DualExecuteInternalAddressor< MemberFunctionType >; + nsstd::auto_ptr< detail::DualMemberFunctionFactory< MemberFunctionType > > m_DualMemberFactory; + + VectorOfImage m_FixedImages; + VectorOfImage m_MovingImages; + VectorOfImage m_FixedMasks; + VectorOfImage m_MovingMasks; + Image m_ResultImage; + + std::string m_InitialTransformParameterMapFileName; + std::string m_FixedPointSetFileName; + std::string m_MovingPointSetFileName; + + ParameterMapVectorType m_ParameterMapVector; + ParameterMapVectorType m_TransformParameterMapVector; + ParameterMapVectorType m_InverseTransformParameterMapVector; + + std::string m_OutputDirectory; + std::string m_LogFileName; + + bool m_LogToFile; + bool m_LogToConsole; + +}; + +} // end namespace simple +} // end namespace itk + +#endif // __sitksimpleelastiximpl_h_ \ No newline at end of file diff --git a/Code/Elastix/src/sitkSimpleTransformix.cxx b/Code/Elastix/src/sitkSimpleTransformix.cxx index 32a0970a5..4c9ab99b7 100644 --- a/Code/Elastix/src/sitkSimpleTransformix.cxx +++ b/Code/Elastix/src/sitkSimpleTransformix.cxx @@ -2,40 +2,14 @@ #define __sitksimpletransformix_cxx_ #include "sitkSimpleTransformix.h" -#include "sitkSimpleTransformix.hxx" +#include "sitkSimpleTransformixImpl.h" namespace itk { namespace simple { - - SimpleTransformix -::SimpleTransformix( void ) +::SimpleTransformix( void ) : m_Pimple( new SimpleTransformixImpl ) { - // Register this class with SimpleITK - this->m_MemberFactory.reset( new detail::MemberFunctionFactory< MemberFunctionType >( this ) ); - this->m_MemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, 2 >(); - this->m_MemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, 3 >(); - -#ifdef SITK_4D_IMAGES - m_MemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, 4 >(); -#endif - - this->m_MovingImage = Image(); - this->m_ResultImage = Image(); - - this->m_TransformParameterMapVector = ParameterMapVectorType(); - - this->m_ComputeSpatialJacobian = false; - this->m_ComputeDeterminantOfSpatialJacobian = false; - this->m_ComputeDeformationField = false; - this->m_MovingPointSetFileName = ""; - - this->m_OutputDirectory = ""; - this->m_LogFileName = ""; - - this->m_LogToFile = ""; - this->m_LogToConsole = ""; } SimpleTransformix @@ -47,15 +21,14 @@ const std::string SimpleTransformix ::GetName( void ) { - const std::string name = std::string( "SimpleTransformix" ); - return name; + return this->m_Pimple->GetName(); } SimpleTransformix::Self& SimpleTransformix ::SetMovingImage( const Image& movingImage ) { - this->m_MovingImage = movingImage; + this->m_Pimple->SetMovingImage( movingImage ); return *this; } @@ -63,14 +36,14 @@ Image& SimpleTransformix ::GetMovingImage( void ) { - return this->m_MovingImage; + return this->m_Pimple->GetMovingImage(); } SimpleTransformix::Self& SimpleTransformix ::RemoveMovingImage( void ) { - this->SetMovingImage( Image() ); + this->m_Pimple->RemoveMovingImage(); return *this; } @@ -78,7 +51,7 @@ SimpleTransformix::Self& SimpleTransformix ::SetFixedPointSetFileName( const std::string movingPointSetFileName ) { - this->m_MovingPointSetFileName = movingPointSetFileName; + this->m_Pimple->SetFixedPointSetFileName( movingPointSetFileName ); return *this; } @@ -86,14 +59,14 @@ std::string SimpleTransformix ::GetFixedPointSetFileName( void ) { - return this->m_MovingPointSetFileName; + return this->m_Pimple->GetFixedPointSetFileName(); } SimpleTransformix::Self& SimpleTransformix ::RemoveFixedPointSetFileName( void ) { - this->m_MovingPointSetFileName = std::string(); + this->m_Pimple->RemoveFixedPointSetFileName(); return *this; } @@ -101,7 +74,7 @@ SimpleTransformix::Self& SimpleTransformix ::SetComputeSpatialJacobian( const bool computeSpatialJacobian ) { - this->m_ComputeSpatialJacobian = computeSpatialJacobian; + this->m_Pimple->SetComputeSpatialJacobian( computeSpatialJacobian ); return *this; } @@ -109,14 +82,14 @@ bool SimpleTransformix ::GetComputeSpatialJacobian( void ) { - return this->m_ComputeSpatialJacobian; + return this->m_Pimple->GetComputeSpatialJacobian(); } SimpleTransformix::Self& SimpleTransformix ::ComputeSpatialJacobianOn( void ) { - this->SetComputeSpatialJacobian( true ); + this->m_Pimple->SetComputeSpatialJacobian( true ); return *this; } @@ -124,7 +97,7 @@ SimpleTransformix::Self& SimpleTransformix ::ComputeSpatialJacobianOff( void ) { - this->SetComputeSpatialJacobian( false ); + this->m_Pimple->SetComputeSpatialJacobian( false ); return *this; } @@ -132,7 +105,7 @@ SimpleTransformix::Self& SimpleTransformix ::SetComputeDeterminantOfSpatialJacobian( const bool computeDeterminantOfSpatialJacobian ) { - this->m_ComputeDeterminantOfSpatialJacobian = computeDeterminantOfSpatialJacobian; + this->m_Pimple->SetComputeDeterminantOfSpatialJacobian( computeDeterminantOfSpatialJacobian ); return *this; } @@ -140,14 +113,14 @@ bool SimpleTransformix ::GetComputeDeterminantOfSpatialJacobian( void ) { - return this->m_ComputeDeterminantOfSpatialJacobian; + return this->m_Pimple->GetComputeDeterminantOfSpatialJacobian(); } SimpleTransformix::Self& SimpleTransformix ::ComputeDeterminantOfSpatialJacobianOn( void ) { - this->SetComputeDeterminantOfSpatialJacobian( true ); + this->m_Pimple->SetComputeDeterminantOfSpatialJacobian( true ); return *this; } @@ -155,7 +128,7 @@ SimpleTransformix::Self& SimpleTransformix ::ComputeDeterminantOfSpatialJacobianOff( void ) { - this->SetComputeDeterminantOfSpatialJacobian( false ); + this->m_Pimple->SetComputeDeterminantOfSpatialJacobian( false ); return *this; } @@ -163,7 +136,7 @@ SimpleTransformix::Self& SimpleTransformix ::SetComputeDeformationField( const bool computeDeformationField ) { - this->m_ComputeDeformationField = computeDeformationField; + this->m_Pimple->SetComputeDeformationField( computeDeformationField ); return *this; } @@ -171,14 +144,14 @@ bool SimpleTransformix ::GetComputeDeformationField( void ) { - return this->m_ComputeDeformationField; + return this->m_Pimple->GetComputeDeformationField(); } SimpleTransformix::Self& SimpleTransformix ::ComputeDeformationFieldOn( void ) { - this->SetComputeDeformationField( true ); + this->m_Pimple->SetComputeDeformationField( true ); return *this; } @@ -186,7 +159,7 @@ SimpleTransformix::Self& SimpleTransformix ::ComputeDeformationFieldOff( void ) { - this->SetComputeDeformationField( false ); + this->m_Pimple->SetComputeDeformationField( false ); return *this; } @@ -194,7 +167,7 @@ SimpleTransformix::Self& SimpleTransformix ::SetOutputDirectory( const std::string outputDirectory ) { - this->m_OutputDirectory = outputDirectory; + this->m_Pimple->SetOutputDirectory( outputDirectory ); return *this; } @@ -202,14 +175,14 @@ std::string SimpleTransformix ::GetOutputDirectory( void ) { - return this->m_OutputDirectory; + return this->m_Pimple->GetOutputDirectory(); } SimpleTransformix::Self& SimpleTransformix ::RemoveOutputDirectory( void ) { - this->m_OutputDirectory = std::string(); + this->m_Pimple->RemoveOutputDirectory(); return *this; } @@ -217,7 +190,7 @@ SimpleTransformix::Self& SimpleTransformix ::SetLogFileName( std::string logFileName ) { - this->m_LogFileName = logFileName; + this->m_Pimple->SetLogFileName( logFileName ); return *this; } @@ -225,14 +198,14 @@ std::string SimpleTransformix ::GetLogFileName( void ) { - return this->m_LogFileName; + return this->m_Pimple->GetLogFileName(); } SimpleTransformix::Self& SimpleTransformix ::RemoveLogFileName( void ) { - this->m_LogFileName = std::string(); + this->m_Pimple->RemoveLogFileName(); return *this; } @@ -240,7 +213,7 @@ SimpleTransformix::Self& SimpleTransformix ::SetLogToFile( bool logToFile ) { - this->m_LogToFile = logToFile; + this->m_Pimple->SetLogToFile( logToFile ); return *this; } @@ -248,14 +221,14 @@ bool SimpleTransformix ::GetLogToFile( void ) { - return this->m_LogToFile; + return this->m_Pimple->GetLogToFile(); } SimpleTransformix::Self& SimpleTransformix ::LogToFileOn() { - this->SetLogToFile( true ); + this->m_Pimple->SetLogToFile( true ); return *this; } @@ -263,7 +236,7 @@ SimpleTransformix::Self& SimpleTransformix ::LogToFileOff() { - this->SetLogToFile( false ); + this->m_Pimple->SetLogToFile( false ); return *this; } @@ -271,7 +244,7 @@ SimpleTransformix::Self& SimpleTransformix ::SetLogToConsole( bool logToConsole ) { - this->m_LogToConsole = logToConsole; + this->m_Pimple->SetLogToConsole( logToConsole ); return *this; } @@ -279,14 +252,14 @@ bool SimpleTransformix ::GetLogToConsole( void ) { - return this->m_LogToConsole; + return this->m_Pimple->GetLogToConsole(); } SimpleTransformix::Self& SimpleTransformix ::LogToConsoleOn() { - this->SetLogToConsole( true ); + this->m_Pimple->SetLogToConsole( true ); return *this; } @@ -294,33 +267,31 @@ SimpleTransformix::Self& SimpleTransformix ::LogToConsoleOff() { - this->SetLogToConsole( false ); + this->m_Pimple->SetLogToConsole( false ); return *this; } SimpleTransformix::Self& SimpleTransformix -::SetTransformParameterMap( const ParameterMapVectorType parameterMapVector ) +::SetTransformParameterMap( const ParameterMapVectorType transformParameterMapVector ) { - this->m_TransformParameterMapVector = parameterMapVector; + this->m_Pimple->SetTransformParameterMap( transformParameterMapVector ); return *this; } SimpleTransformix::Self& SimpleTransformix -::SetTransformParameterMap( const ParameterMapType parameterMap ) +::SetTransformParameterMap( const ParameterMapType transformParameterMap ) { - ParameterMapVectorType parameterMapVector; - parameterMapVector.push_back( parameterMap ); - this->SetTransformParameterMap( parameterMapVector ); + this->m_Pimple->SetTransformParameterMap( transformParameterMap ); return *this; } SimpleTransformix::Self& SimpleTransformix -::AddTransformParameterMap( const ParameterMapType parameterMap ) +::AddTransformParameterMap( const ParameterMapType transformParameterMap ) { - this->m_TransformParameterMapVector.push_back( parameterMap ); + this->m_Pimple->AddTransformParameterMap( transformParameterMap ); return *this; } @@ -328,25 +299,21 @@ SimpleTransformix::ParameterMapVectorType SimpleTransformix ::GetTransformParameterMap( void ) { - return this->m_TransformParameterMapVector; + return this->m_Pimple->GetTransformParameterMap(); } unsigned int SimpleTransformix ::GetNumberOfTransformParameterMaps( void ) { - return this->m_TransformParameterMapVector.size(); + return this->m_Pimple->GetNumberOfTransformParameterMaps(); } SimpleTransformix::Self& SimpleTransformix ::SetTransformParameter( const ParameterKeyType key, const ParameterValueType value ) { - for( unsigned int i = 0; i < this->m_TransformParameterMapVector.size(); i++ ) - { - this->SetTransformParameter( i, key, value ); - } - + this->m_Pimple->SetTransformParameter( key, value ); return *this; } @@ -354,11 +321,7 @@ SimpleTransformix::Self& SimpleTransformix ::SetTransformParameter( const ParameterKeyType key, const ParameterValueVectorType value ) { - for( unsigned int i = 0; i < this->m_TransformParameterMapVector.size(); i++ ) - { - this->SetTransformParameter( i, key, value ); - } - + this->m_Pimple->SetTransformParameter( key, value ); return *this; } @@ -366,13 +329,7 @@ SimpleTransformix::Self& SimpleTransformix ::SetTransformParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueType value ) { - if( index >= this->m_TransformParameterMapVector.size() ) - { - sitkExceptionMacro( "Parameter map index is out of range (index: " << index << "; number of transform parameters maps: " << this->m_TransformParameterMapVector.size() << "). Note that indexes are zero-based." ); - } - - this->m_TransformParameterMapVector[ index ][ key ] = ParameterValueVectorType( 1, value ); - + this->m_Pimple->SetTransformParameter( index, key, value ); return *this; } @@ -380,13 +337,7 @@ SimpleTransformix::Self& SimpleTransformix ::SetTransformParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueVectorType value ) { - if( index >= this->m_TransformParameterMapVector.size() ) - { - sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of transform parameters maps: " << this->m_TransformParameterMapVector.size() << "). Note that indexes are zero-based." ); - } - - this->m_TransformParameterMapVector[ index ][ key ] = value; - + this->m_Pimple->SetTransformParameter( index, key, value ); return *this; } @@ -394,11 +345,7 @@ SimpleTransformix::Self& SimpleTransformix ::AddTransformParameter( const ParameterKeyType key, const ParameterValueType value ) { - for( unsigned int i = 0; i < this->m_TransformParameterMapVector.size(); i++ ) - { - this->AddTransformParameter( i, key, value ); - } - + this->m_Pimple->AddTransformParameter( key, value ); return *this; } @@ -406,20 +353,7 @@ SimpleTransformix::Self& SimpleTransformix ::AddTransformParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueType value ) { - if( index >= this->m_TransformParameterMapVector.size() ) - { - sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of transform parameters maps: " << this->m_TransformParameterMapVector.size() << "). Note that indexes are zero-based." ); - } - - if( this->m_TransformParameterMapVector[ index ].find( key ) == this->m_TransformParameterMapVector[ index ].end() ) - { - this->SetTransformParameter( index, key, value ); - } - else - { - this->m_TransformParameterMapVector[ index ][ key ].push_back( value ); - } - + this->m_Pimple->AddTransformParameter( index, key, value ); return *this; } @@ -427,35 +361,21 @@ SimpleTransformix::ParameterValueVectorType SimpleTransformix ::GetTransformParameter( const ParameterKeyType key ) { - if( this->m_TransformParameterMapVector.size() > 0 ) - { - sitkExceptionMacro( "An index is needed when more than one transform parameter map is present. Please specify the parameter map number as the first argument." ); - } - - return this->GetTransformParameter( 0, key ); + return this->m_Pimple->GetTransformParameter( key ); } SimpleTransformix::ParameterValueVectorType SimpleTransformix ::GetTransformParameter( const unsigned int index, const ParameterKeyType key ) { - if( index >= this->m_TransformParameterMapVector.size() ) - { - sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of transform parameters maps: " << this->m_TransformParameterMapVector.size() << "). Note that indexes are zero-based." ); - } - - return this->m_TransformParameterMapVector[ index ][ key ]; + return this->m_Pimple->GetTransformParameter( index, key ); } SimpleTransformix::Self& SimpleTransformix ::RemoveTransformParameter( const ParameterKeyType key ) { - for( unsigned int i = 0; i < this->m_TransformParameterMapVector.size(); i++ ) - { - this->RemoveTransformParameter( i, key ); - } - + this->m_Pimple->RemoveTransformParameter( key ); return *this; } @@ -463,40 +383,22 @@ SimpleTransformix::Self& SimpleTransformix ::RemoveTransformParameter( const unsigned int index, const ParameterKeyType key ) { - if( index >= this->m_TransformParameterMapVector.size() ) - { - sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of transform parameters maps: " << this->m_TransformParameterMapVector.size() << "). Note that indexes are zero-based." ); - } - - this->m_TransformParameterMapVector[ index ].erase( key ); - + this->m_Pimple->RemoveTransformParameter( index, key ); return *this; } SimpleTransformix::ParameterMapType SimpleTransformix -::ReadParameterFile( const std::string filename ) +::ReadParameterFile( const std::string parameterFileName ) { - ParameterFileParserPointer parser = ParameterFileParserType::New(); - parser->SetParameterFileName( filename ); - try - { - parser->ReadParameterFile(); - } - catch( itk::ExceptionObject &e ) - { - std::cout << e.what() << std::endl; - } - - return parser->GetParameterMap(); + return this->m_Pimple->ReadParameterFile( parameterFileName ); } SimpleTransformix::Self& SimpleTransformix ::WriteParameterFile( const ParameterMapType parameterMap, const std::string parameterFileName ) { - ParameterObjectPointer parameterObject = ParameterObjectType::New(); - parameterObject->WriteParameterFile( parameterMap, parameterFileName ); + this->m_Pimple->WriteParameterFile( parameterMap, parameterFileName ); return *this; } @@ -504,7 +406,7 @@ SimpleTransformix::Self& SimpleTransformix ::PrintParameterMap( void ) { - this->PrintParameterMap( this->GetTransformParameterMap() ); + this->m_Pimple->PrintParameterMap(); return *this; } @@ -512,9 +414,7 @@ SimpleTransformix::Self& SimpleTransformix ::PrintParameterMap( const ParameterMapType parameterMap ) { - ParameterMapVectorType parameterMapVector = ParameterMapVectorType( 1 ); - parameterMapVector[ 0 ] = parameterMap; - this->PrintParameterMap( parameterMapVector ); + this->m_Pimple->PrintParameterMap( parameterMap ); return *this; } @@ -522,9 +422,7 @@ SimpleTransformix::Self& SimpleTransformix ::PrintParameterMap( const ParameterMapVectorType parameterMapVector ) { - ParameterObjectPointer parameterObject = ParameterObjectType::New(); - parameterObject->SetParameterMap( parameterMapVector ); - parameterObject->Print( std::cout ); + this->m_Pimple->PrintParameterMap( parameterMapVector ); return *this; } @@ -532,39 +430,14 @@ Image SimpleTransformix ::Execute( void ) { - const PixelIDValueEnum MovingImagePixelEnum = this->m_MovingImage.GetPixelID(); - const unsigned int MovingImageDimension = this->m_MovingImage.GetDimension(); - - if( this->m_MemberFactory->HasMemberFunction( sitkFloat32, MovingImageDimension ) ) - { - return this->m_MemberFactory->GetMemberFunction( sitkFloat32, MovingImageDimension )(); - } - - sitkExceptionMacro( << "SimpleTransformix does not support the combination of image type " - << GetPixelIDValueAsElastixParameter( MovingImagePixelEnum ) << " and dimension " - << MovingImageDimension << ". This a serious error. " - << "Contact developers at https://github.com/kaspermarstal/SimpleElastix/issues." ); + return this->m_Pimple->Execute(); } Image SimpleTransformix ::GetResultImage( void ) { - if( this->IsEmpty( this->m_ResultImage ) ) - { - sitkExceptionMacro( "No result image was found. Has transformix run yet?" ) - } - - return this->m_ResultImage; -} - - -bool -SimpleTransformix -::IsEmpty( const Image& image ) -{ - bool isEmpty = image.GetWidth() == 0 && image.GetHeight() == 0; - return isEmpty; + return this->m_Pimple->GetResultImage(); } /** diff --git a/Code/Elastix/src/sitkSimpleTransformixImpl.cxx b/Code/Elastix/src/sitkSimpleTransformixImpl.cxx new file mode 100644 index 000000000..4264b445c --- /dev/null +++ b/Code/Elastix/src/sitkSimpleTransformixImpl.cxx @@ -0,0 +1,585 @@ +#ifndef __sitksimpletransformiximpl_cxx_ +#define __sitksimpletransformiximpl_cxx_ + +#include "sitkSimpleTransformix.h" +#include "sitkSimpleTransformixImpl.h" +#include "sitkCastImageFilter.h" + +namespace itk { + namespace simple { + +SimpleTransformix::SimpleTransformixImpl +::SimpleTransformixImpl( void ) +{ + // Register this class with SimpleITK + this->m_MemberFactory.reset( new detail::MemberFunctionFactory< MemberFunctionType >( this ) ); + this->m_MemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, 2 >(); + this->m_MemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, 3 >(); + +#ifdef SITK_4D_IMAGES + m_MemberFactory->RegisterMemberFunctions< FloatPixelIDTypeList, 4 >(); +#endif + + this->m_MovingImage = Image(); + this->m_ResultImage = Image(); + + this->m_TransformParameterMapVector = ParameterMapVectorType(); + + this->m_ComputeSpatialJacobian = false; + this->m_ComputeDeterminantOfSpatialJacobian = false; + this->m_ComputeDeformationField = false; + this->m_MovingPointSetFileName = ""; + + this->m_OutputDirectory = ""; + this->m_LogFileName = ""; + + this->m_LogToFile = ""; + this->m_LogToConsole = ""; +} + +SimpleTransformix::SimpleTransformixImpl +::~SimpleTransformixImpl( void ) +{ +} + +Image +SimpleTransformix::SimpleTransformixImpl +::Execute( void ) +{ + const PixelIDValueEnum MovingImagePixelEnum = this->m_MovingImage.GetPixelID(); + const unsigned int MovingImageDimension = this->m_MovingImage.GetDimension(); + + if( this->m_MemberFactory->HasMemberFunction( sitkFloat32, MovingImageDimension ) ) + { + return this->m_MemberFactory->GetMemberFunction( sitkFloat32, MovingImageDimension )(); + } + + sitkExceptionMacro( << "SimpleTransformix does not support the combination of image type " + << GetPixelIDValueAsElastixParameter( MovingImagePixelEnum ) << " and dimension " + << MovingImageDimension << ". This a serious error. " + << "Contact developers at https://github.com/kaspermarstal/SimpleElastix/issues." ); +} + +template< typename TMovingImage > +Image +SimpleTransformix::SimpleTransformixImpl +::ExecuteInternal( void ) +{ + typedef elastix::TransformixFilter< TMovingImage > TransformixFilterType; + typedef typename TransformixFilterType::Pointer TransforimxFilterPointer; + + try + { + TransforimxFilterPointer transformixFilter = TransformixFilterType::New(); + + if( !this->IsEmpty( this->m_MovingImage ) ) { + transformixFilter->SetMovingImage( itkDynamicCastInDebugMode< TMovingImage* >( Cast( this->GetMovingImage(), static_cast< PixelIDValueEnum >( GetPixelIDValueFromElastixString( "float" ) ) ).GetITKBase() ) ); + } + + transformixFilter->SetFixedPointSetFileName( this->GetFixedPointSetFileName() ); + transformixFilter->SetComputeSpatialJacobian( this->GetComputeSpatialJacobian() ); + transformixFilter->SetComputeDeterminantOfSpatialJacobian( this->GetComputeDeterminantOfSpatialJacobian() ); + transformixFilter->SetComputeDeformationField( this->GetComputeDeformationField() ); + + transformixFilter->SetOutputDirectory( this->GetOutputDirectory() ); + transformixFilter->SetLogFileName( this->GetLogFileName() ); + transformixFilter->SetLogToFile( this->GetLogToFile() ); + transformixFilter->SetLogToConsole( this->GetLogToConsole() ); + + ParameterMapVectorType transformParameterMapVector = this->m_TransformParameterMapVector; + for( unsigned int i = 0; i < transformParameterMapVector.size(); i++ ) + { + transformParameterMapVector[ i ][ "FixedInternalImagePixelType" ] = ParameterValueVectorType( 1, "float" ); + transformParameterMapVector[ i ][ "MovingInternalImagePixelType" ] = ParameterValueVectorType( 1, "float" ); + transformParameterMapVector[ i ][ "ResultImagePixelType" ] = ParameterValueVectorType( 1, "float" ); + } + + ParameterObjectPointer parameterObject = ParameterObjectType::New(); + parameterObject->SetParameterMap( transformParameterMapVector ); + transformixFilter->SetTransformParameterObject( parameterObject ); + transformixFilter->Update(); + + if( !this->IsEmpty( this->GetMovingImage() ) ) + { + this->m_ResultImage = Image( itkDynamicCastInDebugMode< TMovingImage * >( transformixFilter->GetOutput() ) ); + this->m_ResultImage.MakeUnique(); + } + } + catch( itk::ExceptionObject &e ) + { + sitkExceptionMacro( << e ); + } + + return this->m_ResultImage; +} + +const std::string +SimpleTransformix::SimpleTransformixImpl +::GetName( void ) +{ + const std::string name = std::string( "SimpleTransformix" ); + return name; +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetMovingImage( const Image& movingImage ) +{ + this->m_MovingImage = movingImage; +} + +Image& +SimpleTransformix::SimpleTransformixImpl +::GetMovingImage( void ) +{ + return this->m_MovingImage; +} + +void +SimpleTransformix::SimpleTransformixImpl +::RemoveMovingImage( void ) +{ + this->SetMovingImage( Image() ); +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetFixedPointSetFileName( const std::string movingPointSetFileName ) +{ + this->m_MovingPointSetFileName = movingPointSetFileName; +} + +std::string +SimpleTransformix::SimpleTransformixImpl +::GetFixedPointSetFileName( void ) +{ + return this->m_MovingPointSetFileName; +} + +void +SimpleTransformix::SimpleTransformixImpl +::RemoveFixedPointSetFileName( void ) +{ + this->m_MovingPointSetFileName = std::string(); +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetComputeSpatialJacobian( const bool computeSpatialJacobian ) +{ + this->m_ComputeSpatialJacobian = computeSpatialJacobian; +} + +bool +SimpleTransformix::SimpleTransformixImpl +::GetComputeSpatialJacobian( void ) +{ + return this->m_ComputeSpatialJacobian; +} + +void +SimpleTransformix::SimpleTransformixImpl +::ComputeSpatialJacobianOn( void ) +{ + this->SetComputeSpatialJacobian( true ); + +} + +void +SimpleTransformix::SimpleTransformixImpl +::ComputeSpatialJacobianOff( void ) +{ + this->SetComputeSpatialJacobian( false ); +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetComputeDeterminantOfSpatialJacobian( const bool computeDeterminantOfSpatialJacobian ) +{ + this->m_ComputeDeterminantOfSpatialJacobian = computeDeterminantOfSpatialJacobian; +} + +bool +SimpleTransformix::SimpleTransformixImpl +::GetComputeDeterminantOfSpatialJacobian( void ) +{ + return this->m_ComputeDeterminantOfSpatialJacobian; +} + +void +SimpleTransformix::SimpleTransformixImpl +::ComputeDeterminantOfSpatialJacobianOn( void ) +{ + this->SetComputeDeterminantOfSpatialJacobian( true ); +} + +void +SimpleTransformix::SimpleTransformixImpl +::ComputeDeterminantOfSpatialJacobianOff( void ) +{ + this->SetComputeDeterminantOfSpatialJacobian( false ); + +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetComputeDeformationField( const bool computeDeformationField ) +{ + this->m_ComputeDeformationField = computeDeformationField; +} + +bool +SimpleTransformix::SimpleTransformixImpl +::GetComputeDeformationField( void ) +{ + return this->m_ComputeDeformationField; +} + +void +SimpleTransformix::SimpleTransformixImpl +::ComputeDeformationFieldOn( void ) +{ + this->SetComputeDeformationField( true ); +} + +void +SimpleTransformix::SimpleTransformixImpl +::ComputeDeformationFieldOff( void ) +{ + this->SetComputeDeformationField( false ); + +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetOutputDirectory( const std::string outputDirectory ) +{ + this->m_OutputDirectory = outputDirectory; +} + +std::string +SimpleTransformix::SimpleTransformixImpl +::GetOutputDirectory( void ) +{ + return this->m_OutputDirectory; +} + +void +SimpleTransformix::SimpleTransformixImpl +::RemoveOutputDirectory( void ) +{ + this->m_OutputDirectory = std::string(); +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetLogFileName( std::string logFileName ) +{ + this->m_LogFileName = logFileName; +} + +std::string +SimpleTransformix::SimpleTransformixImpl +::GetLogFileName( void ) +{ + return this->m_LogFileName; +} + +void +SimpleTransformix::SimpleTransformixImpl +::RemoveLogFileName( void ) +{ + this->m_LogFileName = std::string(); +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetLogToFile( bool logToFile ) +{ + this->m_LogToFile = logToFile; + +} + +bool +SimpleTransformix::SimpleTransformixImpl +::GetLogToFile( void ) +{ + return this->m_LogToFile; +} + +void +SimpleTransformix::SimpleTransformixImpl +::LogToFileOn() +{ + this->SetLogToFile( true ); +} + +void +SimpleTransformix::SimpleTransformixImpl +::LogToFileOff() +{ + this->SetLogToFile( false ); +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetLogToConsole( bool logToConsole ) +{ + this->m_LogToConsole = logToConsole; +} + +bool +SimpleTransformix::SimpleTransformixImpl +::GetLogToConsole( void ) +{ + return this->m_LogToConsole; +} + +void +SimpleTransformix::SimpleTransformixImpl +::LogToConsoleOn() +{ + this->SetLogToConsole( true ); +} + +void +SimpleTransformix::SimpleTransformixImpl +::LogToConsoleOff() +{ + this->SetLogToConsole( false ); +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetTransformParameterMap( const ParameterMapVectorType parameterMapVector ) +{ + this->m_TransformParameterMapVector = parameterMapVector; +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetTransformParameterMap( const ParameterMapType parameterMap ) +{ + ParameterMapVectorType parameterMapVector; + parameterMapVector.push_back( parameterMap ); + this->SetTransformParameterMap( parameterMapVector ); + +} + +void +SimpleTransformix::SimpleTransformixImpl +::AddTransformParameterMap( const ParameterMapType parameterMap ) +{ + this->m_TransformParameterMapVector.push_back( parameterMap ); +} + +SimpleTransformix::SimpleTransformixImpl::ParameterMapVectorType +SimpleTransformix::SimpleTransformixImpl +::GetTransformParameterMap( void ) +{ + return this->m_TransformParameterMapVector; +} + +unsigned int +SimpleTransformix::SimpleTransformixImpl +::GetNumberOfTransformParameterMaps( void ) +{ + return this->m_TransformParameterMapVector.size(); +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetTransformParameter( const ParameterKeyType key, const ParameterValueType value ) +{ + for( unsigned int i = 0; i < this->m_TransformParameterMapVector.size(); i++ ) + { + this->SetTransformParameter( i, key, value ); + } +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetTransformParameter( const ParameterKeyType key, const ParameterValueVectorType value ) +{ + for( unsigned int i = 0; i < this->m_TransformParameterMapVector.size(); i++ ) + { + this->SetTransformParameter( i, key, value ); + } +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetTransformParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueType value ) +{ + if( index >= this->m_TransformParameterMapVector.size() ) + { + sitkExceptionMacro( "Parameter map index is out of range (index: " << index << "; number of transform parameters maps: " << this->m_TransformParameterMapVector.size() << "). Note that indexes are zero-based." ); + } + + this->m_TransformParameterMapVector[ index ][ key ] = ParameterValueVectorType( 1, value ); +} + +void +SimpleTransformix::SimpleTransformixImpl +::SetTransformParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueVectorType value ) +{ + if( index >= this->m_TransformParameterMapVector.size() ) + { + sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of transform parameters maps: " << this->m_TransformParameterMapVector.size() << "). Note that indexes are zero-based." ); + } + + this->m_TransformParameterMapVector[ index ][ key ] = value; +} + +void +SimpleTransformix::SimpleTransformixImpl +::AddTransformParameter( const ParameterKeyType key, const ParameterValueType value ) +{ + for( unsigned int i = 0; i < this->m_TransformParameterMapVector.size(); i++ ) + { + this->AddTransformParameter( i, key, value ); + } +} + +void +SimpleTransformix::SimpleTransformixImpl +::AddTransformParameter( const unsigned int index, const ParameterKeyType key, const ParameterValueType value ) +{ + if( index >= this->m_TransformParameterMapVector.size() ) + { + sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of transform parameters maps: " << this->m_TransformParameterMapVector.size() << "). Note that indexes are zero-based." ); + } + + if( this->m_TransformParameterMapVector[ index ].find( key ) == this->m_TransformParameterMapVector[ index ].end() ) + { + this->SetTransformParameter( index, key, value ); + } + else + { + this->m_TransformParameterMapVector[ index ][ key ].push_back( value ); + } +} + +SimpleTransformix::SimpleTransformixImpl::ParameterValueVectorType +SimpleTransformix::SimpleTransformixImpl +::GetTransformParameter( const ParameterKeyType key ) +{ + if( this->m_TransformParameterMapVector.size() > 0 ) + { + sitkExceptionMacro( "An index is needed when more than one transform parameter map is present. Please specify the parameter map number as the first argument." ); + } + + return this->GetTransformParameter( 0, key ); +} + +SimpleTransformix::SimpleTransformixImpl::ParameterValueVectorType +SimpleTransformix::SimpleTransformixImpl +::GetTransformParameter( const unsigned int index, const ParameterKeyType key ) +{ + if( index >= this->m_TransformParameterMapVector.size() ) + { + sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of transform parameters maps: " << this->m_TransformParameterMapVector.size() << "). Note that indexes are zero-based." ); + } + + return this->m_TransformParameterMapVector[ index ][ key ]; +} + +void +SimpleTransformix::SimpleTransformixImpl +::RemoveTransformParameter( const ParameterKeyType key ) +{ + for( unsigned int i = 0; i < this->m_TransformParameterMapVector.size(); i++ ) + { + this->RemoveTransformParameter( i, key ); + } +} + +void +SimpleTransformix::SimpleTransformixImpl +::RemoveTransformParameter( const unsigned int index, const ParameterKeyType key ) +{ + if( index >= this->m_TransformParameterMapVector.size() ) + { + sitkExceptionMacro( "Parameter map index is out of range (index: " << index << ", number of transform parameters maps: " << this->m_TransformParameterMapVector.size() << "). Note that indexes are zero-based." ); + } + + this->m_TransformParameterMapVector[ index ].erase( key ); +} + +SimpleTransformix::SimpleTransformixImpl::ParameterMapType +SimpleTransformix::SimpleTransformixImpl +::ReadParameterFile( const std::string filename ) +{ + ParameterFileParserPointer parser = ParameterFileParserType::New(); + parser->SetParameterFileName( filename ); + try + { + parser->ReadParameterFile(); + } + catch( itk::ExceptionObject &e ) + { + std::cout << e.what() << std::endl; + } + + return parser->GetParameterMap(); +} + +void +SimpleTransformix::SimpleTransformixImpl +::WriteParameterFile( const ParameterMapType parameterMap, const std::string parameterFileName ) +{ + ParameterObjectPointer parameterObject = ParameterObjectType::New(); + parameterObject->WriteParameterFile( parameterMap, parameterFileName ); +} + +void +SimpleTransformix::SimpleTransformixImpl +::PrintParameterMap( void ) +{ + this->PrintParameterMap( this->GetTransformParameterMap() ); +} + +void +SimpleTransformix::SimpleTransformixImpl +::PrintParameterMap( const ParameterMapType parameterMap ) +{ + ParameterMapVectorType parameterMapVector = ParameterMapVectorType( 1 ); + parameterMapVector[ 0 ] = parameterMap; + this->PrintParameterMap( parameterMapVector ); +} + +void +SimpleTransformix::SimpleTransformixImpl +::PrintParameterMap( const ParameterMapVectorType parameterMapVector ) +{ + ParameterObjectPointer parameterObject = ParameterObjectType::New(); + parameterObject->SetParameterMap( parameterMapVector ); + parameterObject->Print( std::cout ); + +} + +Image +SimpleTransformix::SimpleTransformixImpl +::GetResultImage( void ) +{ + if( this->IsEmpty( this->m_ResultImage ) ) + { + sitkExceptionMacro( "No result image was found. Has transformix run yet?" ) + } + + return this->m_ResultImage; +} + + +bool +SimpleTransformix::SimpleTransformixImpl +::IsEmpty( const Image& image ) +{ + bool isEmpty = image.GetWidth() == 0 && image.GetHeight() == 0; + return isEmpty; +} + +} // end namespace simple +} // end namespace itk + +#endif // __sitksimpletransformiximpl_cxx_ \ No newline at end of file diff --git a/Code/Elastix/src/sitkSimpleTransformixImpl.h b/Code/Elastix/src/sitkSimpleTransformixImpl.h new file mode 100644 index 000000000..546fd4641 --- /dev/null +++ b/Code/Elastix/src/sitkSimpleTransformixImpl.h @@ -0,0 +1,134 @@ +#ifndef __sitksimpletransformiximpl_h_ +#define __sitksimpletransformiximpl_h_ + +// SimpleITK +#include "sitkSimpleTransformix.h" +#include "sitkMemberFunctionFactory.h" + +// Transformix +#include "elxTransformixFilter.h" +#include "elxParameterObject.h" + +namespace itk { + namespace simple { + +struct SimpleTransformix::SimpleTransformixImpl +{ + + SimpleTransformixImpl( void ); + ~SimpleTransformixImpl( void ); + + typedef SimpleTransformixImpl Self; + + typedef elastix::ParameterObject ParameterObjectType; + typedef ParameterObjectType::Pointer ParameterObjectPointer; + typedef ParameterObjectType::ParameterMapType ParameterMapType; + typedef ParameterObjectType::ParameterMapVectorType ParameterMapVectorType; + typedef ParameterMapType::iterator ParameterMapIterator; + typedef ParameterMapType::const_iterator ParameterMapConstIterator; + typedef itk::ParameterFileParser ParameterFileParserType; + typedef ParameterFileParserType::Pointer ParameterFileParserPointer; + typedef ParameterObjectType::ParameterKeyType ParameterKeyType; + typedef ParameterObjectType::ParameterValueType ParameterValueType; + typedef ParameterObjectType::ParameterValueVectorType ParameterValueVectorType; + + const std::string GetName( void ); + + void SetMovingImage( const Image& movingImage ); + Image& GetMovingImage( void ); + void RemoveMovingImage( void ); + + void SetFixedPointSetFileName( const std::string movingPointSetFileName ); + std::string GetFixedPointSetFileName( void ); + void RemoveFixedPointSetFileName( void ); + + void SetComputeSpatialJacobian( const bool ); + bool GetComputeSpatialJacobian( void ); + void ComputeSpatialJacobianOn( void ); + void ComputeSpatialJacobianOff( void ); + + void SetComputeDeterminantOfSpatialJacobian( const bool ); + bool GetComputeDeterminantOfSpatialJacobian( void ); + void ComputeDeterminantOfSpatialJacobianOn( void ); + void ComputeDeterminantOfSpatialJacobianOff( void ); + + void SetComputeDeformationField( bool ); + bool GetComputeDeformationField( void ); + void ComputeDeformationFieldOn( void ); + void ComputeDeformationFieldOff( void ); + + void SetOutputDirectory( const std::string outputDirectory ); + std::string GetOutputDirectory( void ); + void RemoveOutputDirectory( void ); + + void SetLogFileName( const std::string logFileName ); + std::string GetLogFileName( void ); + void RemoveLogFileName( void ); + + void SetLogToFile( const bool logToFile ); + bool GetLogToFile( void ); + void LogToFileOn( void ); + void LogToFileOff( void ); + + void SetLogToConsole( const bool logToConsole ); + bool GetLogToConsole( void ); + void LogToConsoleOn(); + void LogToConsoleOff(); + + void SetTransformParameterMap( const std::vector< std::map< std::string, std::vector< std::string > > > parameterMapVector ); + void SetTransformParameterMap( const std::map< std::string, std::vector< std::string > > parameterMap ); + void AddTransformParameterMap( const std::map< std::string, std::vector< std::string > > parameterMap ); + std::vector< std::map< std::string, std::vector< std::string > > > GetTransformParameterMap( void ); + unsigned int GetNumberOfTransformParameterMaps( void ); + + void SetTransformParameter( const std::string key, const std::string value ); + void SetTransformParameter( const std::string key, const std::vector< std::string > value ); + void SetTransformParameter( const unsigned int index, const std::string key, const std::string value ); + void SetTransformParameter( const unsigned int index, const std::string key, const std::vector< std::string > value ); + void AddTransformParameter( const std::string key, const std::string value ); + void AddTransformParameter( const unsigned int index, const std::string key, const std::string value ); + std::vector< std::string > GetTransformParameter( const std::string key ); + std::vector< std::string > GetTransformParameter( const unsigned int index, const std::string key ); + void RemoveTransformParameter( const std::string key ); + void RemoveTransformParameter( const unsigned int index, const std::string key ); + + std::map< std::string, std::vector< std::string > > ReadParameterFile( const std::string filename ); + void WriteParameterFile( const std::map< std::string, std::vector< std::string > > parameterMap, const std::string parameterFileName ); + + void PrintParameterMap( void ); + void PrintParameterMap( const std::map< std::string, std::vector< std::string > > parameterMap ); + void PrintParameterMap( const std::vector< std::map< std::string, std::vector< std::string > > > parameterMapVector ); + + Image Execute( void ); + + Image GetResultImage( void ); + + bool IsEmpty( const Image& image ); + + // Definitions for SimpleITK member factory + typedef Image ( Self::*MemberFunctionType )( void ); + template< class TMovingImage > Image ExecuteInternal( void ); + friend struct detail::MemberFunctionAddressor< MemberFunctionType >; + nsstd::auto_ptr< detail::MemberFunctionFactory< MemberFunctionType > > m_MemberFactory; + + Image m_MovingImage; + Image m_ResultImage; + + ParameterMapVectorType m_TransformParameterMapVector; + + bool m_ComputeSpatialJacobian; + bool m_ComputeDeterminantOfSpatialJacobian; + bool m_ComputeDeformationField; + std::string m_MovingPointSetFileName; + + std::string m_OutputDirectory; + std::string m_LogFileName; + + bool m_LogToConsole; + bool m_LogToFile; +}; + +} // end namespace simple +} // end namespace itk + +#endif // __sitksimpletransformiximpl_h_ diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index 7a3cb11cd..bb7221bc5 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -14,6 +14,12 @@ if(NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK") find_package(SimpleITK REQUIRED) include(${SimpleITK_USE_FILE}) + if( NOT EXISTS ${ELASTIX_USE_FILE} ) + set( ELASTIX_USE_FILE "" CACHE PATH "Path to UseElastix.cmake" ) + message(FATAL_ERROR "Could not find UseElastix.cmake. The CMake variable ELASTIX_USE_FILE must point to UseElastix.cmake when using SimpleElastix as an external project.") + endif() + include(${ELASTIX_USE_FILE}) + # Add compiler flags needed to use SimpleITK. set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SimpleITK_REQUIRED_C_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SimpleITK_REQUIRED_CXX_FLAGS}") @@ -22,11 +28,6 @@ if(NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") endif() -# ITK and Elastix is required to build SimpleElastix examples -set(ITK_NO_IO_FACTORY_REGISTER_MANAGER 1) -include(${ITK_USE_FILE}) -include(${ELASTIX_USE_FILE}) - # Add individual cxx executables add_executable ( SimpleElastix1 SimpleElastix1.cxx ) target_link_libraries ( SimpleElastix1 ${SimpleITK_LIBRARIES} ) diff --git a/Examples/ITKIntegration/CMakeLists.txt b/Examples/ITKIntegration/CMakeLists.txt index 8634a5405..b492b2660 100644 --- a/Examples/ITKIntegration/CMakeLists.txt +++ b/Examples/ITKIntegration/CMakeLists.txt @@ -1,8 +1,12 @@ + +find_package(ITK REQUIRED ) +include(${ITK_USE_FILE}) + add_executable ( ITKIntegration ITKIntegration.cxx ) -target_link_libraries ( ITKIntegration ${SimpleITK_LIBRARIES} ) +target_link_libraries ( ITKIntegration ${SimpleITK_LIBRARIES} ${ITK_LIBRARIES} ) -add_executable( ElastixFilter ElastixFilter.cxx ) -target_link_libraries( ElastixFilter ${SimpleITK_LIBRARIES} elastix ${ITK_LIBRARIES} ) +add_executable ( ElastixFilter ElastixFilter.cxx ) +target_link_libraries( ElastixFilter ${SimpleITK_LIBRARIES} ${ITK_LIBRARIES} ) -add_executable( TransformixFilter TransformixFilter.cxx ) -target_link_libraries( TransformixFilter ${SimpleITK_LIBRARIES} transformix ${ITK_LIBRARIES} ) +add_executable ( TransformixFilter TransformixFilter.cxx ) +target_link_libraries( TransformixFilter ${SimpleITK_LIBRARIES} ${ITK_LIBRARIES} ) diff --git a/SuperBuild/External_Elastix.cmake b/SuperBuild/External_Elastix.cmake index 659d8e567..e144afa49 100644 --- a/SuperBuild/External_Elastix.cmake +++ b/SuperBuild/External_Elastix.cmake @@ -11,7 +11,7 @@ endif() file( WRITE "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" "${ep_common_cache}" ) set( ELASTIX_GIT_REPOSITORY ${git_protocol}://github.com/kaspermarstal/elastix ) -set( ELASTIX_GIT_TAG fa451dd33ac72dbded40dbf408db2c4e958469ac ) +set( ELASTIX_GIT_TAG e29be08c65ee4b204e89ddc144b1f6d931c41fe1 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ELASTIX_BUILD_SHARED_LIBS ON ) diff --git a/SuperBuild/External_SimpleITKExamples.cmake b/SuperBuild/External_SimpleITKExamples.cmake index 262dba839..945a3adb3 100644 --- a/SuperBuild/External_SimpleITKExamples.cmake +++ b/SuperBuild/External_SimpleITKExamples.cmake @@ -18,8 +18,7 @@ if (${BUILD_EXAMPLES} ) -C "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" ${ep_common_args} -DSimpleITK_DIR:PATH=${CMAKE_CURRENT_BINARY_DIR}/lib/cmake/SimpleITK-0.10/ - -DITK_USE_FILE:PATH=${ITK_USE_FILE} - -DELASTIX_USE_FILE:PATH=${ELASTIX_USE_FILE} + -DITK_DIR:PATH=${ITK_DIR} -DCMAKE_SKIP_RPATH:BOOL=ON -DCMAKE_INSTALL_PREFIX:PATH= BUILD_COMMAND ${BUILD_COMMAND_STRING} diff --git a/Testing/Unit/sitkSimpleElastixTests.cxx b/Testing/Unit/sitkSimpleElastixTests.cxx index 7a7f57156..e862f8dd0 100644 --- a/Testing/Unit/sitkSimpleElastixTests.cxx +++ b/Testing/Unit/sitkSimpleElastixTests.cxx @@ -3,6 +3,8 @@ #include "sitkSimpleElastix.h" #include "sitkImageFileWriter.h" #include "sitkBinaryThresholdImageFilter.h" + +#include namespace itk { namespace simple { @@ -302,7 +304,7 @@ TEST( SimpleElastix, RegistrationWithPointSets ) { // We generate the point sets manually std::string fixedPointSetFileName = dataFinder.GetOutputFile( "FixedPointSet.pts" ); - std::ofstream fixedPointSetFile; + std::ofstream fixedPointSetFile = std::ofstream(); fixedPointSetFile.open( fixedPointSetFileName.c_str() ); fixedPointSetFile << "point\n"; fixedPointSetFile << "1\n"; @@ -310,7 +312,7 @@ TEST( SimpleElastix, RegistrationWithPointSets ) fixedPointSetFile.close(); std::string movingPointSetFileName = dataFinder.GetOutputFile( "MovingPointSet.pts" ); - std::ofstream movingPointSetFile; + std::ofstream movingPointSetFile = std::ofstream(); movingPointSetFile.open( movingPointSetFileName.c_str() ); movingPointSetFile << "point\n"; movingPointSetFile << "1\n"; diff --git a/UseSimpleITK.cmake.in b/UseSimpleITK.cmake.in index b6ab3f6c7..32c670c2c 100644 --- a/UseSimpleITK.cmake.in +++ b/UseSimpleITK.cmake.in @@ -17,8 +17,3 @@ include_directories(${SimpleITK_INCLUDE_DIRS}) # Add link directories needed to use SimpleITK. link_directories(${SimpleITK_LIBRARY_DIRS}) - -# Add itk and elastix needed to use SimpleElastix. -set( ITK_NO_IO_FACTORY_REGISTER_MANAGER 1 ) -include( ${ITK_USE_FILE} ) -include( ${ELASTIX_USE_FILE} ) From 3b6834f33a80c0bcaba26ed955be1578037ac62a Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Tue, 22 Nov 2016 00:00:04 +0100 Subject: [PATCH 408/412] BUG: Fix ElastixFilter and TransformixFilter regression --- Code/Elastix/src/sitkSimpleElastixImpl.cxx | 2 - .../Elastix/src/sitkSimpleTransformixImpl.cxx | 1 - Testing/Unit/sitkElastixFilterTests.cxx | 65 ------------------- Testing/Unit/sitkTransformixFilterTests.cxx | 4 -- 4 files changed, 72 deletions(-) diff --git a/Code/Elastix/src/sitkSimpleElastixImpl.cxx b/Code/Elastix/src/sitkSimpleElastixImpl.cxx index 6c93f2321..06c7b1e2d 100644 --- a/Code/Elastix/src/sitkSimpleElastixImpl.cxx +++ b/Code/Elastix/src/sitkSimpleElastixImpl.cxx @@ -191,8 +191,6 @@ ::DualExecuteInternal( void ) = ParameterValueVectorType( 1, "float" ); parameterMapVector[ i ][ "MovingInternalImagePixelType" ] = ParameterValueVectorType( 1, "float" ); - parameterMapVector[ i ][ "ResultImagePixelType" ] - = ParameterValueVectorType( 1, "float" ); } ParameterObjectPointer parameterObject = ParameterObjectType::New(); diff --git a/Code/Elastix/src/sitkSimpleTransformixImpl.cxx b/Code/Elastix/src/sitkSimpleTransformixImpl.cxx index 4264b445c..7a4e0c93a 100644 --- a/Code/Elastix/src/sitkSimpleTransformixImpl.cxx +++ b/Code/Elastix/src/sitkSimpleTransformixImpl.cxx @@ -91,7 +91,6 @@ ::ExecuteInternal( void ) { transformParameterMapVector[ i ][ "FixedInternalImagePixelType" ] = ParameterValueVectorType( 1, "float" ); transformParameterMapVector[ i ][ "MovingInternalImagePixelType" ] = ParameterValueVectorType( 1, "float" ); - transformParameterMapVector[ i ][ "ResultImagePixelType" ] = ParameterValueVectorType( 1, "float" ); } ParameterObjectPointer parameterObject = ParameterObjectType::New(); diff --git a/Testing/Unit/sitkElastixFilterTests.cxx b/Testing/Unit/sitkElastixFilterTests.cxx index 7b40b0f5b..0201b3863 100644 --- a/Testing/Unit/sitkElastixFilterTests.cxx +++ b/Testing/Unit/sitkElastixFilterTests.cxx @@ -25,7 +25,6 @@ TEST( ElastixFilterTest, DefaultParameterObject2D ) { typedef itk::Image< float, 2 > ImageType; typedef itk::ImageFileReader< ImageType > ImageFileReaderType; - typedef itk::ImageFileWriter< ImageType > ImageFileWriterType; typedef ElastixFilter< ImageType, ImageType > ElastixFilterType; ImageFileReaderType::Pointer fixedImageReader = ImageFileReaderType::New(); @@ -244,74 +243,10 @@ TEST( ElastixFilterTest, InitialTransformTestEuler2D ) EXPECT_NO_THROW( writer->Update() ); } -TEST( ElastixFilterTest, InverseTransformTestEuler2D ) -{ - ParameterObject::Pointer parameterObject; - EXPECT_NO_THROW( parameterObject = ParameterObject::New() ); - EXPECT_NO_THROW( parameterObject->SetParameterMap( ParameterObject::GetDefaultParameterMap( "rigid" ) ) ); - - typedef itk::Image< float, 2 > ImageType; - typedef itk::ImageFileReader< ImageType > ImageFileReaderType; - typedef itk::ImageFileWriter< ImageType > ImageFileWriterType; - typedef ElastixFilter< ImageType, ImageType > ElastixFilterType; - typedef TransformixFilter< ImageType > TransformixFilterType; - - ImageFileReaderType::Pointer fixedImageReader = ImageFileReaderType::New(); - fixedImageReader->SetFileName( dataFinder.GetFile( "Input/BrainProtonDensitySliceBorder20.png" ) ); - - ImageFileReaderType::Pointer inputImageReader = ImageFileReaderType::New(); - inputImageReader->SetFileName( dataFinder.GetFile( "Input/BrainProtonDensitySliceBorder20.png" ) ); - - ImageFileReaderType::Pointer movingImageReader = ImageFileReaderType::New(); - movingImageReader->SetFileName( dataFinder.GetFile( "Input/BrainProtonDensitySliceR10X13Y17.png" ) ); - - // Forward registration - ElastixFilterType::Pointer forwardElastixFilter; - EXPECT_NO_THROW( forwardElastixFilter = ElastixFilterType::New() ); - EXPECT_NO_THROW( forwardElastixFilter->SetFixedImage( fixedImageReader->GetOutput() ) ); - EXPECT_NO_THROW( forwardElastixFilter->SetMovingImage( movingImageReader->GetOutput() ) ); - EXPECT_NO_THROW( forwardElastixFilter->SetParameterObject( parameterObject ) ); - EXPECT_NO_THROW( forwardElastixFilter->Update() ); - EXPECT_NO_THROW( forwardElastixFilter->GetTransformParameterObject()->WriteParameterFile( dataFinder.GetOutputFile( "inverseTransformTestEuler2D.txt" ) ) ); - - // Inverse registration - ElastixFilterType::ParameterMapType parameterMap = ParameterObject::GetDefaultParameterMap( "rigid" ); - parameterMap[ "Metric" ] = ElastixFilterType::ParameterValueVectorType( 1, "DisplacementMagnitudePenalty" ); - ParameterObject::Pointer inverseParameterObject; - EXPECT_NO_THROW( inverseParameterObject = ParameterObject::New() ); - EXPECT_NO_THROW( inverseParameterObject->SetParameterMap( parameterMap ) ); - - ElastixFilterType::Pointer inverseElastixFilter; - EXPECT_NO_THROW( inverseElastixFilter = ElastixFilterType::New() ); - EXPECT_NO_THROW( inverseElastixFilter->SetFixedImage( fixedImageReader->GetOutput() ) ); - EXPECT_NO_THROW( inverseElastixFilter->SetMovingImage( fixedImageReader->GetOutput() ) ); - EXPECT_NO_THROW( inverseElastixFilter->SetParameterObject( inverseParameterObject ) ); - EXPECT_NO_THROW( inverseElastixFilter->SetInitialTransformParameterFileName( dataFinder.GetOutputFile( "inverseTransformTestEuler2D.txt" ) ) ); - EXPECT_NO_THROW( inverseElastixFilter->Update() ); - - ElastixFilterType::ParameterMapVectorType inverseParameterMap; - EXPECT_NO_THROW( inverseParameterMap = inverseElastixFilter->GetTransformParameterObject()->GetParameterMap() ); - EXPECT_NO_THROW( inverseParameterMap[ 0 ][ "InitialTransformParametersFileName" ] = ElastixFilterType::ParameterValueVectorType( 1, "NoInitialTransform" ) ); - - ParameterObject::Pointer inverseTransformParameterObject = ParameterObject::New(); - inverseTransformParameterObject->SetParameterMap( inverseParameterMap ); - - // Warp fixed image to moving image with the inverse transform - TransformixFilterType::Pointer transformixFilter = TransformixFilterType::New(); - EXPECT_NO_THROW( transformixFilter->SetMovingImage( inputImageReader->GetOutput() ) ); - EXPECT_NO_THROW( transformixFilter->SetTransformParameterObject( inverseTransformParameterObject ) ); - - ImageFileWriterType::Pointer writer = ImageFileWriterType::New(); - EXPECT_NO_THROW( writer->SetFileName( dataFinder.GetOutputFile( "InverseTransformTestEuler2DResultImage.nii" ) ) ); - EXPECT_NO_THROW( writer->SetInput( transformixFilter->GetOutput() ) ); - EXPECT_NO_THROW( writer->Update() ); -} - TEST( ElastixFilterTest, SameFixedImageForMultipleRegistrations ) { typedef itk::Image< float, 2 > ImageType; typedef itk::ImageFileReader< ImageType > ImageFileReaderType; - typedef itk::ImageFileWriter< ImageType > ImageFileWriterType; typedef ElastixFilter< ImageType, ImageType > ElastixFilterType; ImageFileReaderType::Pointer fixedImageReader = ImageFileReaderType::New(); diff --git a/Testing/Unit/sitkTransformixFilterTests.cxx b/Testing/Unit/sitkTransformixFilterTests.cxx index eb3fd3c68..bd496d066 100644 --- a/Testing/Unit/sitkTransformixFilterTests.cxx +++ b/Testing/Unit/sitkTransformixFilterTests.cxx @@ -86,7 +86,6 @@ TEST( TransformixFilterTest, ComputeSpatialJacobian ) { typedef itk::Image< float, 2 > ImageType; typedef itk::ImageFileReader< ImageType > ImageFileReaderType; - typedef itk::ImageFileWriter< ImageType > ImageFileWriterType; typedef ElastixFilter< ImageType, ImageType > ElastixFilterType; typedef TransformixFilter< ImageType > TransformixFilterType; @@ -115,7 +114,6 @@ TEST( TransformixFilterTest, ComputeDeterminantOfSpatialJacobian ) { typedef itk::Image< float, 2 > ImageType; typedef itk::ImageFileReader< ImageType > ImageFileReaderType; - typedef itk::ImageFileWriter< ImageType > ImageFileWriterType; typedef ElastixFilter< ImageType, ImageType > ElastixFilterType; typedef TransformixFilter< ImageType > TransformixFilterType; @@ -143,7 +141,6 @@ TEST( TransformixFilterTest, ComputeDeformationField ) { typedef itk::Image< float, 2 > ImageType; typedef itk::ImageFileReader< ImageType > ImageFileReaderType; - typedef itk::ImageFileWriter< ImageType > ImageFileWriterType; typedef ElastixFilter< ImageType, ImageType > ElastixFilterType; typedef TransformixFilter< ImageType > TransformixFilterType; @@ -171,7 +168,6 @@ TEST( TransformixFilterTest, TransformPointSet ) { typedef itk::Image< float, 2 > ImageType; typedef itk::ImageFileReader< ImageType > ImageFileReaderType; - typedef itk::ImageFileWriter< ImageType > ImageFileWriterType; typedef ElastixFilter< ImageType, ImageType > ElastixFilterType; typedef TransformixFilter< ImageType > TransformixFilterType; From 4b73ac1d83aa34ab83a2177597b994080f629970 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Tue, 22 Nov 2016 13:53:43 +0100 Subject: [PATCH 409/412] BUG: Use raw pointers instead of SimpleITK's nsstd::auto_ptr MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This YOLO commit makes SimpleElastix and SimpleTransformix facade classes use raw pimple pointers and manually free them again instead of using SimpleITK’s nsstd::auto_ptr. The nsstd::auto_ptr is a unique_ptr when C++11 is enabled but introduces problems with SWIG wrapping. --- Code/Elastix/include/sitkSimpleElastix.h | 3 +-- Code/Elastix/include/sitkSimpleTransformix.h | 5 +++-- Code/Elastix/src/sitkSimpleElastix.cxx | 2 ++ Code/Elastix/src/sitkSimpleTransformix.cxx | 2 ++ 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/Code/Elastix/include/sitkSimpleElastix.h b/Code/Elastix/include/sitkSimpleElastix.h index 42c569665..53d1ed966 100644 --- a/Code/Elastix/include/sitkSimpleElastix.h +++ b/Code/Elastix/include/sitkSimpleElastix.h @@ -1,7 +1,6 @@ #ifndef __sitksimpleelastix_h_ #define __sitksimpleelastix_h_ -#include "nsstd/auto_ptr.h" #include "sitkCommon.h" #include "sitkImage.h" @@ -137,7 +136,7 @@ class SITKCommon_EXPORT SimpleElastix private: struct SimpleElastixImpl; - nsstd::auto_ptr< SimpleElastixImpl > m_Pimple; + SimpleElastixImpl* m_Pimple; }; diff --git a/Code/Elastix/include/sitkSimpleTransformix.h b/Code/Elastix/include/sitkSimpleTransformix.h index 5377233cf..9e7f03db5 100644 --- a/Code/Elastix/include/sitkSimpleTransformix.h +++ b/Code/Elastix/include/sitkSimpleTransformix.h @@ -1,7 +1,6 @@ #ifndef __sitksimpletransformix_h_ #define __sitksimpletransformix_h_ -#include "nsstd/auto_ptr.h" #include "sitkCommon.h" #include "sitkImage.h" @@ -97,8 +96,10 @@ class SITKCommon_EXPORT SimpleTransformix Image GetResultImage( void ); + private: + struct SimpleTransformixImpl; - nsstd::auto_ptr< SimpleTransformixImpl > m_Pimple; + SimpleTransformixImpl* m_Pimple; }; diff --git a/Code/Elastix/src/sitkSimpleElastix.cxx b/Code/Elastix/src/sitkSimpleElastix.cxx index 8c18259a8..4a80c0cf3 100644 --- a/Code/Elastix/src/sitkSimpleElastix.cxx +++ b/Code/Elastix/src/sitkSimpleElastix.cxx @@ -15,6 +15,8 @@ ::SimpleElastix( void ) : m_Pimple( new SimpleElastixImpl ) SimpleElastix ::~SimpleElastix( void ) { + delete m_Pimple; + m_Pimple = NULL; } const std::string diff --git a/Code/Elastix/src/sitkSimpleTransformix.cxx b/Code/Elastix/src/sitkSimpleTransformix.cxx index 4c9ab99b7..f1839d924 100644 --- a/Code/Elastix/src/sitkSimpleTransformix.cxx +++ b/Code/Elastix/src/sitkSimpleTransformix.cxx @@ -15,6 +15,8 @@ ::SimpleTransformix( void ) : m_Pimple( new SimpleTransformixImpl ) SimpleTransformix ::~SimpleTransformix( void ) { + delete m_Pimple; + m_Pimple = NULL; } const std::string From e9cfb336a84a489feb5a24efa3a4814f5e08b5b3 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Tue, 22 Nov 2016 15:18:24 +0100 Subject: [PATCH 410/412] COMP: Fix OpenMP flags not being added OpenMP flags was added to SimpleITK_REQUIRED_C_FLAGS and SimpleITK_REQUIRED_CXX_FLAGS after these had been used. --- CMakeLists.txt | 20 ++++++++++---------- Examples/CMakeLists.txt | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0b94cea80..1043cadce 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -79,20 +79,12 @@ if(ITK_FOUND) link_directories( "${ITK_LIBRARY_DIRS}") endif() -#---------------------------------------------------------- -# Set flags and directories -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SimpleITK_REQUIRED_C_FLAGS}") -set(CMAKE_CXX_FLAGS "${CXX_ADDITIONAL_WARNING_FLAGS} ${CMAKE_CXX_FLAGS} ${SimpleITK_REQUIRED_CXX_FLAGS}") -set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") -set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") - #----------------------------------------------------------- # Configure Elastix find_package( OpenMP ) if( OPENMP_FOUND ) - set( SimpleITK_REQUIRED_C_FLAGS "${SimpleITK_REQUIRED_C_FLAGS} ${OpenMP_C_FLAGS} " ) - set( SimpleITK_REQUIRED_CXX_FLAGS "${SimpleITK_REQUIRED_CXX_FLAGS} ${OpenMP_CXX_FLAGS} " ) + set(SimpleITK_REQUIRED_C_FLAGS "${SimpleITK_REQUIRED_C_FLAGS} ${OpenMP_C_FLAGS}") + set(SimpleITK_REQUIRED_CXX_FLAGS "${SimpleITK_REQUIRED_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") endif() # Find UseElastix.cmake @@ -113,6 +105,14 @@ if( ELASTIX_BUILD_EXECUTABLE ) message(FATAL_ERROR "SimpleElastix requires elastix libraries, please set ELASTIX_BUILD_EXECUTABLE=OFF and rebuild elastix") endif() +#---------------------------------------------------------- +# Set flags and directories +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SimpleITK_REQUIRED_C_FLAGS}") +set(CMAKE_CXX_FLAGS "${CXX_ADDITIONAL_WARNING_FLAGS} ${SimpleITK_REQUIRED_CXX_FLAGS}") +set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") +set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") +set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${SimpleITK_REQUIRED_LINK_FLAGS}") + #---------------------------------------------------------- # Place all options to go into sitkConfigure.h here option(BUILD_SHARED_LIBS "Build SimpleITK ITK with shared libraries. This does not effect wrapped languages." OFF) diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index bb7221bc5..fd718bbfd 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -14,7 +14,7 @@ if(NOT CMAKE_PROJECT_NAME STREQUAL "SimpleITK") find_package(SimpleITK REQUIRED) include(${SimpleITK_USE_FILE}) - if( NOT EXISTS ${ELASTIX_USE_FILE} ) + if(NOT EXISTS ${ELASTIX_USE_FILE}) set( ELASTIX_USE_FILE "" CACHE PATH "Path to UseElastix.cmake" ) message(FATAL_ERROR "Could not find UseElastix.cmake. The CMake variable ELASTIX_USE_FILE must point to UseElastix.cmake when using SimpleElastix as an external project.") endif() From 93a38d66133c5ea679cac7449b9f156bbc6c82af Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Tue, 22 Nov 2016 16:47:37 +0100 Subject: [PATCH 411/412] BUG: Fix initialisation of ofstreams --- Testing/Unit/sitkSimpleElastixTests.cxx | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Testing/Unit/sitkSimpleElastixTests.cxx b/Testing/Unit/sitkSimpleElastixTests.cxx index e862f8dd0..78b39c203 100644 --- a/Testing/Unit/sitkSimpleElastixTests.cxx +++ b/Testing/Unit/sitkSimpleElastixTests.cxx @@ -304,16 +304,14 @@ TEST( SimpleElastix, RegistrationWithPointSets ) { // We generate the point sets manually std::string fixedPointSetFileName = dataFinder.GetOutputFile( "FixedPointSet.pts" ); - std::ofstream fixedPointSetFile = std::ofstream(); - fixedPointSetFile.open( fixedPointSetFileName.c_str() ); + std::ofstream fixedPointSetFile( fixedPointSetFileName.c_str(), std::ofstream::out ); fixedPointSetFile << "point\n"; fixedPointSetFile << "1\n"; fixedPointSetFile << "128.0 128.0\n"; fixedPointSetFile.close(); std::string movingPointSetFileName = dataFinder.GetOutputFile( "MovingPointSet.pts" ); - std::ofstream movingPointSetFile = std::ofstream(); - movingPointSetFile.open( movingPointSetFileName.c_str() ); + std::ofstream movingPointSetFile( movingPointSetFileName.c_str(), std::ofstream::out ); movingPointSetFile << "point\n"; movingPointSetFile << "1\n"; movingPointSetFile << "115.0 111.0\n"; From cf6bf22a8ea1b36f17ec1de3bfce84e8fb2cf779 Mon Sep 17 00:00:00 2001 From: Kasper Marstal Date: Tue, 22 Nov 2016 21:06:21 +0100 Subject: [PATCH 412/412] ENH: Update elastix --- SuperBuild/External_Elastix.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SuperBuild/External_Elastix.cmake b/SuperBuild/External_Elastix.cmake index e144afa49..9dcf4b6ab 100644 --- a/SuperBuild/External_Elastix.cmake +++ b/SuperBuild/External_Elastix.cmake @@ -11,7 +11,7 @@ endif() file( WRITE "${CMAKE_CURRENT_BINARY_DIR}/${proj}-build/CMakeCacheInit.txt" "${ep_common_cache}" ) set( ELASTIX_GIT_REPOSITORY ${git_protocol}://github.com/kaspermarstal/elastix ) -set( ELASTIX_GIT_TAG e29be08c65ee4b204e89ddc144b1f6d931c41fe1 ) +set( ELASTIX_GIT_TAG 99251130b1d04841a1b94f7023be74124d9d9c43 ) if( ${ITK_WRAPPING} OR ${BUILD_SHARED_LIBS} ) set( ELASTIX_BUILD_SHARED_LIBS ON )